text:
Q: Daily Dog with C#, WhatsApp and Azure functions not running I hope someone can help me with this:
I've been trying to learn a bit about azure functions to create a chatbot using twilio.
I was following this blog tutorial:
https://www.twilio.com/blog/draft-daily-dog-with-c-whatsapp-and-azure-functions-2
I did all the steps correctly, but when I try to run it I get an error ...
=====================================================
2020-05-06T01:04:27.202 [Error] Function compilation error
Microsoft.CodeAnalysis.Scripting.CompilationErrorException : Script compilation failed.
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.CreateFunctionTarget(CancellationToken cancellationToken) at D:\a\1\s\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 314
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionLoader`1.GetFunctionTargetAsync[T](Int32 attemptCount) at D:\a\1\s\src\WebJobs.Script\Description\FunctionLoader.cs : 55
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetFunctionTargetAsync(Boolean isInvocation) at D:\a\1\s\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 183
2020-05-06T01:04:27.247 [Warning] D:\home\site\wwwroot\TimerTrigger1\sendMessage.csx(8,26): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
2020-05-06T01:04:27.273 [Error] run.csx(19,29): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
2020-05-06T01:04:27.324 [Error] run.csx(25,9): error CS0103: The name 'responseMessage' does not exist in the current context
2020-05-06T01:04:27.354 [Error] run.csx(27,31): error CS0103: The name 'responseMessage' does not exist in the current context
2020-05-06T01:04:27.395 [Error] run.csx(27,25): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
2020-05-06T01:04:27.430 [Error] run.csx(31,5): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
2020-05-06T01:04:27.478 [Error] Executed 'Functions.TimerTrigger1' (Failed, Id=24245bff-8b18-47e2-8019-fec74f735540)
Script compilation failed.

I write "copy" the following three files...

run.csx

#r "Newtonsoft.Json"
#load "sendMessage.csx"

using System;
using System.Net;
using System.Net.Http.Headers;
using Newtonsoft.Json;

public static void Run(TimerInfo myTimer, ILogger log)
{
    var imageUrl = "https://images.dog.ceo/breeds/pinscher-miniature/n02107312_4650.jpg";

    using(var client = new HttpClient())
    {
      var apiEndPoint = "https://dog.ceo/api/breeds/image/random";
      client.BaseAddress = new Uri(apiEndPoint);
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

      var responseMessage = await
          client
              .GetAsync(apiEndPoint);

    }

    if (responseMessage.IsSuccessStatusCode)
    {
      var jsonContent = await responseMessage.Content.ReadAsStringAsync();
      dynamic data = JsonConvert.DeserializeObject(jsonContent);
      imageUrl = data.message;
    }
    await SendMessage(imageUrl);
}

sendMessage.csx

using System;
using System.Net;
using System.Net.Http.Headers;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

public static async Task SendMessage(string imageUrl)
{

   TwilioClient.Init(
              Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID"),
              Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN")

        );

   var message =  MessageResource.Create(
        from: new PhoneNumber("whatsapp:+14155238886"),
        to: new PhoneNumber("whatsapp:" + Environment.GetEnvironmentVariable("MY_PHONE_NUMBER")),
        body: "Your daily cat!",
        mediaUrl: new List<Uri>{new Uri(imageUrl)}

        );

    Console.WriteLine("Message SID: " + message.Sid);

}

function.proj

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="twilio" Version="5.27.2"/>
    </ItemGroup>
</Project>

Could you please give me an advise about what am I doing wrong?
I will really appreciate your help!
Thanks!!

A: There are lot of compile errors as it shown in the error messages,

*

*You can only use await in an async method

*you should declarare responseMessage globally


text:
Q: How to make changes to .config files in the Installation folder using Wix? I'm using WiX to create an installer for my application. There are some config files which I need to edit AFTER they are installed on the target system based on values entered by the user during installation. I'm using HEAT command to harvest all the files that need to be installed on the target machine to avoid describing all the files and directories manually. I'm also able to change the configuration of the config files using xml:Util element. Although, I have RECREATE the entire folder structure again to make those changes. Is there a way these changes can be made without having to create the folder structure ?
Basically,
TARGETSYSTEM ---> INSTALLFOLDER ---> Dir1
                                |---> Dir2---> SubDir1
                                         |--->SubDir2 ----> file.config

     <File Id="log4netCONFG" Source="WHATSHOULDCOMEHERE?/file.config" KeyPath="yes" />
        <util:XmlFile Id="UpdateLogFileAppenderFilePath"
                  File="[#log4netCONFG]"
                  Action="setValue"
                  ElementPath="//appender[\[]@name='LogFileAppender'[\]]/param[\    []@name='File'[\]]"
                  Name="value"
                  Value="[LOGFILEAPPENDERFILEPATH]"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reference a public static class in the global namespace in another assembly In C#, is there a way to access a public static class in the global namespace in assembly A from assembly B (assuming assembly B references assembly A), when assembly B has public static class in the global namespace that has the same name?  For example in Bar.cs in assembly A:
using System.Diagnostics;
// NOTE: No namespace declared here - this is in the global:: ns
public static class Bar
{
    public static void DoSomethingSilly()
    {
        Debug.WriteLine("I'm silly!");
    }
}

How could I use this in Bar.cs in assembly B?
public static class Bar
{
    public static void DoSomethingSilly()
    {
        // call Bar.DoSomethingSilly() from assembly A here
    }
}

I tried things like global::Bar.DoSomethingSilly(), which doesn't work in assembly B (it just gets me the reference back to assembly B).
I also know I could use reflection to get at it (something like Assembly.GetType()), but I'm more wondering if there's some native C# syntax for it.  In the end I added a namespace around the code in assembly A, which I own and which was only in the global namespace because it was generated by another tool - adding the namespace didn't cause any problems, but I'm curious if there's syntax to allow this kind of referencing.

A: Thanks to @Jon Skeet for this direction - extern alias is what can make this work.  On the properties for the reference to the assembly, add an alias (for example assemblyA, or in the screen shot taken from here FooVersion1):

, and at the top of the .cs file add:
extern alias assemblyA;

which will then allow either:
assemblyA::Foo.DoSomethingSilly();
assemblyA.Foo.DoSomethingSilly();

I still went for adding a namespace to the generated code - it's more straightforward and avoids polluting the global namespace.


text:
Q: Is it good to Have instance variable assigned to some value instead declared in constructor I have a Class USER which has instance variables with default values. like give below
public class User{
   private String username="";
   private String password = "";
   private Boolean isValidUser = true;
   private Boolean email = "sample@gmail.com"
  ........
}

now i have changed my class like
public class User{
       private String username;
       private String password;
       private Boolean isValidUser;
       private Boolean email
      ........

      public User(){
         email = "sample@gmail.com";
         isValidUser = true;
         .......
      }
  }

I though keeping those default values in constructor is good practice.
i know it's stupid Question =D but wanna know your opinion.

A: The point is that you don't put down classes "as you go". The exact design of a class is just one small facet within your overall design.
Coming from DDD (domain driven design) the very first thing to consider is the model that you intend to build. Meaning: you are creating a User class for the purpose of modelling Users within a system. This means that you (and all the other people involved in that project) need a very clear understanding what a "user really is".
Example: it seems that none of your fields are final. But I am pretty sure: in any reasonable model of users, a user will have certain properties that never change; for example a specific user id. And on the other hand; it seems very much wrong to assign some "default" email address to new users; and declare those users to be "valid". To the contrary.
What I am saying in essence is: you should focus on creating a consistent model first. And then, when you really understand what your system is doing with "User objects" and which properties those users have; then you look into the many possible patterns how to actually create such objects later on.
Your approach is to define your system by the details of your implementation. And as lined out - that is not a good idea.


text:
Q: Automatically delete temporary files in Google Drive submitted by Google Form I have a Google Form that is used internally within our Organization. It allows people to submit files. The files are placed into a folder based off the name of the question in the form. The problem is that when the form is loading the files, it stores them in the root folder of drive, then sends them. Most of the users don't know that it does this and therefore it keeps creating files in their drive. How can i use a script that would get permission from them the first time they use the form with the script and then every time thereafter that they use the form it submits the files then removes the temporary ones from their root folder?
I have found ways to delete files older than X amount of days, but I cannot find anything that shows anything about the temporary file that is created. That is the only information lacking.


text:
Q: How to trim leading spaces in Sublime Text 3 I have list of strings which all have leading whitespace

How do I remove it

A: so I found a way to do this by using a sublime package Trimmer
trimmer screenshot


text:
Q: Ubuntu 20.04 System Menu shutdown buttons turn into Dropdown I have just installed Ubuntu 20.04 LTS on my laptop, previously using 19.04.
I've noticed that previously, there are buttons on the system menu for settings, logout and turn off:

Now, it shows an dropdown:

I want to know if it's possible to change it back to the buttons. I have Gnome Tweak tools and tried other gnome themes.


text:
Q: How to explain two possible problems with dark matter Can someone please answer how dark matter theory resolves/eliminates these two possible problems

*

*Dark matter, per my understanding, due to gravity, keeps moving, and due to its non-interactive nature,  does not stick to itself or normal matter. Therefore, it is in continuous (and may be somewhat random) movement. Wouldn't this make the speed curve of spiral galaxies pretty unstable, or unpredictable?

*Dark matter, due to gravity, keeps moving, (usually most dense at the center of the galaxy). Whenever some of it enters the event horizon of the central black hole, it should not be able to come out ever again. Over million/billions of years, all of it, little by little, should eventually end up inside the central black hole, making it impossible to maintain the uniform speed curve. Even though it is non-interactive, is it correct that it still could not escape the event horizon? If so, how it is still possible to maintain the uniform speed curve of galaxies for billions of years?
I am thinking due to non-interactive, non-sticking nature, movement/rotation of dark matter should not be uniform, and it should be crossing in and out passing the central black hole, thereby some of it being consumed for ever. Once this process starts, the central black hole would begin to become heavier making the process even faster.
Also, I am thinking that to cause uniform speed curve, dark matter has to be distributed over the galaxy in certain way. All or most of it in the central black hole would not support the uniform speed curve.
Do the dark matter simulations take these two problems into account? How they are resolved/avoided?

A: The properties you attribute to dark matter (non-interacting, affected only by gravity) are alo properties of a large fraction of the visible matter in our Galaxy. i.e. Stars orbit in the Galactic potential without directly interacting with other stars and their trajectories are only influenced by gravitational forces.
Far from being "random", dark matter is expected to orbit the Galaxy in a similar way to stars. The main difference being that most of the dark matter is on much larger orbits and the orbital axes are distributed more uniformly in space.
In the same way that stars on circular or even quite elliptical orbits never come anywhere near the BH at the centre of the galaxy, nor does most dark matter. Some dark matter will have been captured in the past, but only that which had almost perfectly radial orbits. The rest continues to orbit in the same way that the Earth continues to orbit the Sun, with nothing to dissipate its orbital kinetic energy. To extend the analogy between non-interacting stars and dark matter - there is a class of stars formed very early on in the Milky Way's history called population II or halo stars. These have been orbiting the Milky Way in pseudo-spherical orbits since they first formed more than 10 billion years ago - like dark matter.
Yes, the dark matter density is higher near the centre of the galaxy but the mass of dark matter is dominated by that which occupies the enormous volume at large distances from the centre.
To summarise, neither of the problems you have invented are problems.

A: To answer the question about falling into the central black hole.
If we start off with most of the dark matter having some significant angular momentum (ie it is on some kind of elliptical orbit) then for Newtonian gravity it can't fall into the black hole since it can't shed the angular momentum.
In fact it can shed angular momentum by interacting gravitationally with other matter -- dark and light -- in the galaxy, but the system as a whole can't.  So neither dark nor light matter somehow gets sucked into the black hole, because to do so requires dumping angular momentum somewhere.
Well, this isn't quite true: GR does allow some systems to spin down.  But the time-constants for this to happen for something like a galaxy would be absolutely enormous since the fields are very weak.

A: The answer by Rob disentangles some of the similarities with dark matter and ordinary matter, but forgets to point out an important difference between them (apart from dark matter being dark).
Because Dark matter does not interact electromagnetically it will not "collide" with other matter. This is important since it prevents the dark matter from losing excess kinetic energy through collisions. The process I'm describing is one of the main reasons galaxies tend to be flat. Anything not orbiting in the plane of the galactic disc will need to pass through that disc as it orbits. This passage is prone to collisions, causing the orbit to get caught in the galactic disc.
Since dark matter does not collide in this way, it does not get accreted in the disc. As a consequence the dark matter forms a halo instead of a disc.


text:
Q: Is smarty dangerous for my server? I use smarty for my free weblog service templates and users can edit templates.
Is this dangerous for my server ?
can they run shell or etc ... by smarty codes?

A: Everything depends what you allow user and what code you have. For example if you have some plugins, user can use them in their code and if plugin displays some data that shouldn't be revealed for all users, that could also be a huge problem.
Users can also put JavaScript into template files so you should also consider to remove JavaScript from generated output.
You should also update your Smarty to the newest one 3.1.18 - because some bugs were removed and probably some of them could be related to security. In 3.1 Smarty you cannot use PHP code using {php} code if you don't use SmartyBC in your code but of course it's better to remove {php} just in case


text:
Q: Unison -repeat watch will only sync when a change is made client side I have 3 computers, two clients (A,B), and one central server (C), that they both connect to via Unison/ssh, folders are set to -repeat watch so that changes are sent to the server as soon as they are made, (think dropbox).
This system works perfectly, changes are made on the server as soon as something changes in my watch folders on either client. But, changes made on (A) are not pushed to (B), through (C) until (B) makes a change itself, and visa-versa.
Is there some way to get Unison to check for changes on (C), and not just the clients?
Thanks for any help, Please let me know if you need clarification.

A: Well, this just turned out to be a dumb mistake on my part. The Unison versions did not match between the server and the clients. Simply updating the server's Unison version corrected the issue.
A private dropbox alternative is as simple as compiling the same latest svn version on each computer you'd like to sync, then running unison with -repeat watch!


text:
Q: SSLHandshakeException Error in Jmeter I am encountering this error while recording the Jmeter scripts.
I already have JDK 1.7 installed in my machine however it did not help. I am getting the following error message:

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure at sun.security.ssl.Alerts.getSSLException(Unknown Source) at sun.security.ssl.Alerts.getSSLException(Unknown Source) at sun.security.ssl.SSLSocketImpl.recvAlert(Unknown Source) at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source) at org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.sample(HTTPJavaImpl.java:487) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:74) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1105) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1094) at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:429) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:257) at java.lang.Thread.run(Unknown Source)

A: As per Recording HTTPS Traffic with JMeter's Proxy Server guide clearing your browser's history should help.


text:
Q: How to filter data with the highest number I have thousands data like this:
abc_1
abc_2
abc_3
abc_4
def_1
def_2
def_3
ghi_1
ghi_2

I want to filter it to get only data with the highest number which is abc_4, def_3, ghi_2.
How I can get it?

A: Using awk, as implied by your tags:
$ awk -F_ '
    {m[$1] = $2 > m[$1] ? $2 : m[$1]}
    END {OFS = FS; for(x in m) print x, m[x]}
  ' file | sort
abc_4
def_3
ghi_2

If you have GNU awk > 4.0 you can do the sorting internally
$ awk -F_ '
    {m[$1] = $2 > m[$1] ? $2 : m[$1]}
    END {
      OFS = FS; PROCINFO["sorted_in"] = "@ind_str_asc";
      for(x in m) print x, m[x]
    }
  ' file
abc_4
def_3
ghi_2

Alternatively, if you have Miller you can do a groupwise max using the stat1 verb:
$ mlr --nidx --fs _ stats1 -a max -f 2 -g 1 file
abc_4
def_3
ghi_2

or with GNU datamash
$ datamash -t_ groupby 1 max 2 < file
abc_4
def_3
ghi_2

or for your specific input, assuming that the prefix strings are fixed length, using standard utilities sort and uniq:
$ sort -t_ -k1,1 -k2,2nr file | uniq -w4
abc_4
def_3
ghi_2


text:
Q: Regex validity for Degree i have an assignment where i should check validity of the string where :

*

*N90 -> North and must have key degree between 0-90

*W180 -> have degree between 91-180

*S270 -> have degree between 181-270

*E360 -> have degree between 271-360

how can i create a reg ex like this.

A: Don't use a regular expression. This is a classic example of the kind of problem that regular expressions are not appropriate for. Just split the string into a direction (the first character) and a number, and check that the number meets the required conditions for the direction.

A: Regex doesn't really understand numeric ranges, and must match these numbers as digit sequences, so it's not the best tool for the job. That said, this can be done, but it's going to be ugly

N90 -> North and must have key degree between 0-90

N([0-9]|[1-8][0-9]|90)

W180 -> have degree between 91-180

W(9[1-9]|1[0-7][0-9]|180)

S270 -> have degree between 181-270

S(18[1-9]|19[0-9]|2[0-6][0-9]|270)

E360 -> have degree between 271-360

E(27[1-9]|2[8-9][0-9]|3[0-5][0-9]|360)
References

*

*regular-expressions.info/Numeric Ranges
Related questions

*

*Regex: why doesn't [01-12] range work as expected?


text:
Q: Does Wolfram say all functional graphs have countably many vertices? Does Wolfram here say all functional graphs have countably many vertices?
Let a functional graph $G$ map the orbit of the following function $f:\Bbb Z_p\to\Bbb Z_p$
$x\mapsto p^{-1}\cdot(x-(x\pmod p))$ through the $p-$adic integers.
(Here $x\pmod p$ is the function that maps to the natural number $n$ representative of some element of $\Bbb Z/p\Bbb Z$ which is $0\leq n<p$)  So you can think of $f$ as simply deleting the most significant digit of any $p-$adic number.
Then this functional graph comprises uncountably many connected subgraphs.  The ones with eventually periodic orbits of period $m$ can be represented by the base $p$ Lyndon words of length $m$. Then there are uncountably many left over, which one needs the axiom of choice to pick representatives of.
I'm confused by where Wolfram says;

and can therefore be specified by a function mapping $\{1,...,n\}$ onto itself

which appears to imply a functional graph must be countable.  How does this sentence apply to my example? As I'm pretty sure I'm misunderstanding it.

A: The functional graphs in the MathWorld article wouldn't just be countable; they'd be finite. This is not surprising to see in that article:

*

*Many, perhaps most discussions of graph theory only consider finite graphs; many results about finite graphs do not extend to infinite graphs, or take considerably more work to do so. If I read anything about graph theory, I would not assume it applies to infinite graphs unless this is specifically mentioned.

*In particular, if 50% of the article is devoted to implementation details in Mathematica, which cannot possibly hope to deal with infinite graphs, I think it's safe to say that it only considers the finite case.

Nevertheless, there's nothing wrong with talking about an infinite functional graph; it can be specified by a function mapping the vertex set $V$ to itself, but there's nothing inherently wrong with $V$ being infinite. Some definitions for finite graphs break down for infinite graphs before you even try to prove anything about them, but this isn't one of them.
Your example is a perfectly good uncountably infinite functional graph, though there are two warnings that should always be given in this situation:

*

*Be careful about applying any particular theorems about functional graphs you encounter, before you check if those theorems make sense in the infinite (and the uncountable) settings.

*If you're discussing it with graph theorists, you should be upfront about the vertex set being uncountably infinite if you want to avoid any confusion.


text:
Q: How can I print map key/value with std::variant? I'm trying to print the key of a certain value in my dictionary. I defined my map like this:
std::map<std::string, std::variant<float,int,bool,std::string>> kwargs;
kwargs["interface"] = "probe";
kwargs["flag"] = true;
kwargs["Height"] = 5;
kwargs["length"] = 6;

I tried to print the value normally but a (no operator "<<" matches these operands) error occurs.
std::cout << kwargs["flag"] << std::endl;

Can someone help me with this error?

A: There's no operator<< for std::variant, which can't be printed out directly. You need to read the value from the variant (by index or type), e.g.
std::cout << std::get<bool>(kwargs["flag"]) << std::endl;

Or
std::cout << std::get<2>(kwargs["flag"]) << std::endl;

A: You can define operator<< for your type:
std::ostream& operator<<(std::ostream& os, std::variant<float,int,bool,std::string> const& v) {
    std::visit([&os](auto const& x) { os << x; }, v);
    return os;
}

You can generalize the solution to work with any variant specialization:
template <class Var, class = std::variant_alternative_t<0, Var>>
std::ostream& operator<<(std::ostream& os, Var const& v) {
    std::visit([&os](auto const& x) { os << x; }, v);
    return os;
}

Note, the second template parameter exists to disable the definition if the Var is not a std::variant specialization.

A: I would use std::visit with a generic lambda that prints any type to std::cout, as follows:
std::map<std::string, std::variant<float,int,bool,std::string>> kwargs;
kwargs["interface"] = "probe"s;
kwargs["flag"] = true;
kwargs["Height"] = 5;
kwargs["length"] = 6;

for (const auto& [k, v] : kwargs){
    std::cout << k << " : ";
    std::visit([](const auto& x){ std::cout << x; }, v);
    std::cout << '\n';
}

This works because all of float, int, bool, and std::string have overloads for the output stream operator <<. For other types, or to override this behaviour, you could use a custom functor class instead of a lambda:
struct PrintVisitor {
    template<typename T>
    void operator()(const T& t) const {
        std::cout << t;
    }

    // prints std::string in quotes
    void operator(const std::string& s) const {
        std::cout << '\"' << s << '\"';
    }
};

[...]

std::visit(PrintVisitor{}, kwargs);

NOTE: unfortunately, the line kwargs["interface"] = "probe"; doesn't actually select the std::string constructor for the variant type, because the string literal preferentially converts to a bool rather than a std::string (further reading). You can avoid this by explicitly making a std::string using, for example, std::string{"probe"} or the standard std::string user-defined literal, as in "probe"s.
Live demo


text:
Q: How to automatically set the time-series value for the current date in Google Docs Script? I have the following rows and columns. The value is coming from a simple API call. Is it possible to store that value for the current day and keep the previously stored value automatically? Right now, I simply copy paste the value for the day, but if I forget to update it, I might miss some data.
26/06/2019  0.01887913
27/06/2019
28/06/2019
29/06/2019

For example, for 27/06/2019, each time I open the doc, it would update the value if it is 27th, but then if I load the doc the next day, it will not be touching the 27th any more and will be updating the 28th.


text:
Q: reactjs-saga login with 2fa otp have a completed React application and I want to enable two-factor authentication in it
I did all the required things regarding this feature in terms of the back end and the front end
Activate the feature for the user - Scan the code with the phone application and verify it - Verify the otp code .. etc
Of course the user who did not activate this feature in his account can login
the Backend when trying to login and after verifying the user name and password
it will return the user information with the token
so I will know if the user has activated the feature Here I have to convert it to a page to verify the otp code and then complete it on the dashboard
this login
    function* loginUser({ payload: { user, history } }) {
  try {
      const response = yield call(postJwtLogin, {
        username: user.email,
        password: user.password,
      });
      if(response.data.token){
        sessionStorage.setItem("authUser", JSON.stringify(response));
      }
      if (response.status === "SUCCESS") {
        yield put(loginSuccess(response));
/*
         Here the conversion takes place to the verification page
         but of course there will be an error in the logic,
         which is that the user can skip the page
*/
        if (response.data.Is2FA === true){
          window.location.href = '/auth-twostep-cover';
        }

        window.location.href = '/dashboard';
      } else {
        yield put(apiError(response));
      }

  } catch (error) {
    yield put(apiError(error));
    toast.error(error, { autoClose: 6000 });
  }
}

this Verifyotp
function* onVerifyOTP({ payload: otp }) {
    try {

        const response = yield call(VerifyOTPApi, otp);

        yield put(VerifyOTPSuccess(response.data));
       // toast.success("", { autoClose: 3000 });
    } catch (error) {
        yield put(VerifyOTPFail(error));
     toast.error(error, { autoClose: 6000 });

    }
}


text:
Q: SSL/TLS connections not working when deployed as Azure App Service My team has an application that is currently deployed as an azure cloud service. The application works well, but after deploying as an app service (as a continuous web job), we're seeing many types of TLS connection failures. The TLS certificates are loaded into HTTPS clients and TCP socket clients. Why are these breaking when running as an app service?
TCP:
System.ComponentModel.Win32Exception (0x80004005): The credentials supplied to the package were not recognized
System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint)
System.Net.Security.SecureChannel.GenerateToken(Byte[] input, Int32 offset, Int32 count, Byte[]& output)
System.Net.Security.SecureChannel.NextMessage(Byte[] incoming, Int32 offset, Int32 count)
System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)

HTTP:
System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
System.Net.ConnectStream.WriteHeaders(Boolean async)   --- End of inner exception stack trace ---
System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
System.Net.HttpWebRequest.GetRequestStream()

Remote Certificate:
-----BEGIN CERTIFICATE-----
MIIHMDCCBhigAwIBAgIQTVJjt9EMcV3VkbZ5cKqBNzANBgkqhkiG9w0BAQsFADBDMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3RlLCBJbmMuMR0wGwYDVQQDExR0aGF3dGUgU0hBMjU2IFNTTCBDQTAeFw0xNzAxMDkwMDAwMDBaFw0yMDAxMTMyMzU5NTlaMIGJMQswCQYDVQQGEwJVUzEQMA4GA1UECAwHQXJpem9uYTEQMA4GA1UEBwwHUGhvZW5peDEpMCcGA1UECgwgQmVzdCBXZXN0ZXJuIEludGVybmF0aW9uYWwsIEluYy4xDzANBgNVBAsMBkJXSSBJVDEaMBgGA1UEAwwRKi5iZXN0d2VzdGVybi5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCfGMbiDXX6nJRxXqUuRXNaRX89lhEDmfEZkhdIcVBcaOiplb/e+lECPVtQt9+b8e8P+cOcz8vkH7tK5v/z0kkzjnoewVZCpXUHjrlJ7zjMgxPAS6oXR92UMQuVF2t0FbYDQpVOH5Sd5tB/nIiTz2bkTL+9ugUNeXNZGxGcXJOQGbpCB2s+a85bqy1Fd8R2apfKmBNrYRGHzW/WmuWaJBBjnKJDLjDuT/zdhrlwmNGerKNsxVNDycWKdoWTvR0Kc79vVuy8yKn3iMvti87xlFOhKtKupJeQdJZrGOD7fxXTwrXNU2f+Xs9AzaEnHk8OONBLNyGaDEnnQKJ1cDqoMHEXAgMBAAGjggPXMIID0zCBhgYDVR0RBH8wfYIVKi5kZXYuYmVzdHdlc3Rlcm4uY29tghMqLmguYmVzdHdlc3Rlcm4uY29tghQqLnFhLmJlc3R3ZXN0ZXJuLmNvbYIVKi51YXQuYmVzdHdlc3Rlcm4uY29tghEqLmJlc3R3ZXN0ZXJuLmNvbYIPYmVzdHdlc3Rlcm4uY29tMAkGA1UdEwQCMAAwbgYDVR0gBGcwZTBjBgZngQwBAgIwWTAmBggrBgEFBQcCARYaaHR0cHM6Ly93d3cudGhhd3RlLmNvbS9jcHMwLwYIKwYBBQUHAgIwIwwhaHR0cHM6Ly93d3cudGhhd3RlLmNvbS9yZXBvc2l0b3J5MA4GA1UdDwEB/wQEAwIFoDAfBgNVHSMEGDAWgBQrmjWuARg4MOFwegXgEXajzr2QFDArBgNVHR8EJDAiMCCgHqAchhpodHRwOi8vdGcuc3ltY2IuY29tL3RnLmNybDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwVwYIKwYBBQUHAQEESzBJMB8GCCsGAQUFBzABhhNodHRwOi8vdGcuc3ltY2QuY29tMCYGCCsGAQUFBzAChhpodHRwOi8vdGcuc3ltY2IuY29tL3RnLmNydDCCAfUGCisGAQQB1nkCBAIEggHlBIIB4QHfAHUA3esdK3oNT6Ygi4GtgWhwfi6OnQHVXIiNPRHEzbbsvswAAAFZg/5pBAAABAMARjBEAiAO/RJNQohPu9QH3jhKEAauOhwgipewvLI46YdajWVXhwIgGVLL+3CzMnstr3dbpTg4pTLPTQMLj7qFZhv7SjrzNOQAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAVmD/mlVAAAEAwBHMEUCIQC/THA9utbL280ZvItjzqQ2RzwByfujkNfva5c9LW/52QIgc6AqANaG+4ZX7JdnTcSXZWxASM+bQYzR3Yjg+EXRoGUAdQC8eOHfxfY8aEZJM02hD6FfCXlpIAnAgbTz9pF/Ptm4pQAAAVmD/mn2AAAEAwBGMEQCICOuhzZtHyvKhRuVkMSYlppmuXKWbhVYkgekN+wbnphSAiAwhIV7WJtGM8yhvvUmUj28Vle6taNvoB9YDF8uv/Z6BwB3AKS5CZC0GFgUh7sTosxncAo8NZgE+RvfuON3zQ7IDdwQAAABWYP+aSMAAAQDAEgwRgIhAJI8jzswB8cmOXVp8IKLspA7Orq8MGmOc+3cv0U/i0T8AiEAszn07XmjFxWBztILLpNTo4IRXUhyFaeh8BjyzFLk+2EwDQYJKoZIhvcNAQELBQADggEBACcA2n8ltg34ZZiNkUmefNja1sZ/9tXJzROmCXkrjFE8zuUwKp0Ie7w5T0DYpdolvb5OvVG05C5Yo7Uke086XzYroFWnU+bcQIdn57cZKc5+aOuAhofIGouKi99srXjJuNatT/K0q1XKEkjMB8VYLHELXsFixwxRQz1MDeEEw+9+AS09qkKfflCoWvmerk8QXwxWwbMGvdO+PI21sw12dHk0bLUuIRriSbga8/PbE/sUM4vPKxMiimDUhwp7vjan06XtjsjHZryGbiNrB77iJH69ob8cKNzcgxM9+MdoqFV+EgC33iaTgSW2wL2w2s64IoJHWLbagec3qAcqySO+4Ng=
-----END CERTIFICATE-----

A: The
thawte Primary Root CA - G3 certificate, with thumbprintF18B538D1BE903B6A6F056435B171589CAF36BF2, is not present in the Trusted Root store on the App Service worker, thus remote cert validation fails. The leaf cert (intermediate) is missing as well.

Which doesn't make for terribly good news. I see two options, either build a chain on-the-fly (which loads the missing CA cert from disk), or blindly return true from WebRequestHandler and its ServerCertificateValidationCallback delegate property.
NOTE:
I do have a working sample somewhere for the first part, let me know if i should look that up. In essence:

*

*Load the missing root CA from disk into X509Certificate2

*Build a chain and add it in

*Pass it to ServerCertificateValidationCallback in WebRequestHandler

A: Add this to the App Settings in the portal for your app service
WEBSITE_LOAD_CERTIFICATES = *

*

*You still need this even if you're not loading certs in the SSL Certificates area of the portal

*This will impact the web jobs for that app service


text:
Q: Does GetInt() automatically create \n outputs here? Suppose I have code that asks the user to give 2 integers, and when the user give the integers, the program prints the sum.
int main(void)

{
printf("Please give me an int: ");
int x = GetInt();

printf("Please give me an int: ");
int y = GetInt();

printf("%d\n", x + y);
}

When I run the program, all three printf's appear on separate lines.
My question: What I don't understand is why the first two printf's do not require \n in order to move to a new line, yet the third printf does require \n.

A: The \n for the first two is provided by the user when they hit enter after inputting their number.


text:
Q: Quill.js not firing "text-changed" event properly I'm using vue3-quill as a wrapper around quill editor for my vue3 application.
Out of the blue, the component stopped emitting an event when the text content of quill editor changes. Inspecting
the code of vue3-quill, I noticed the problem is that the inner instance of quill isn't emitting the text-change event.
The event is however emitted correctly when one of the following keys are pressed: enter, space, tab, delete. Other keys don't trigger the event.
I made this repo to reproduce the error. You can just npm run serve it and try and type something in the editor. You'll see the text isn't displayed below, but if you type enter, space, tab, or delete, you'll see the text correctly updated.
I'll add that this started happening today, or at least went unnoticed by my team and me until now. Does this seem to be a bug on Quill's end or am I doing something wrong?


text:
Q: Horizontal background css position using jquery I want to set only horizontal background property , adding background-position-x works in chrome , safari, IE. but FF and Opera not supporting
I want to add dynamic left value of position
var ppp = 10px;
var pLeft = ppp+' top";
jQuery(".bg-test").css("background-position" , pLeft );

Update
var ppp = jQuery(".someClass").width();
var pLeft = ppp+' top";
jQuery(".bg-test").css("background-position" , pLeft );

http://jsfiddle.net/hQ5dj/6/#run

A: You could do it like this:
$('.bg-test').css('backgroundPosition','left top');

Or with a dynamic value:
$().ready(function() {
    var leftPos = 10+2+5+'px';
    $('.bg-test').css('background-position', leftPos +' bottom');
});

See updated fiddle

A: Use:
background: url(http://png.findicons.com/files/icons/1035/human_o2/128/object_rotate_left.png) 100px 0px no-repeat #cc0; ,
see http://jsfiddle.net/hQ5dj/9/


text:
Q: How do i use JPA 2 to connect to multiple data sources? I have two databases in MSSQL ,and i want to connect to them using JPA2 I have managed to get it working with one . Can some one help me how do i do that?
Thanks a Lot.

A: Configure two persistence units and use two EntityManagerFactory (one per persistence unit).


text:
Q: Jackson deserialization/serialization does not sort properties I'm using Jackson 2.8.9 in my application to generate some JSON. I have some unit tests in which I compare generated JSON with some files content.
When I compare my generated JSON with my file content, it does not match due to the properties order.
For the tests to be repeatable I need to have the properties sorted alphabetically. But with Jackson, it does not seems to work.
I wrote some tests for illustation. Only should_indent_properties pass.
public class FormatJsonWithJacksonTest {

private static final String INDENTED_UNSORTED = "{\r\n" +
        "  \"firstChild\" : {\r\n" +
        "    \"subChild\" : {\r\n" +
        "      \"alphaItem\" : \"1234567891234567\",\r\n" +
        "      \"otherProperty\" : \"2017-06-21\",\r\n" +
        "      \"someOtherProperty\" : \"NONE\",\r\n" +
        "      \"alphaType\" : \"KIND_OF_TYPE\"\r\n" +
        "    }\r\n" +
        "  }\r\n" +
        "}";

private static final String INDENTED_SORTED = "{\r\n" +
        "  \"firstChild\" : {\r\n" +
        "    \"subChild\" : {\r\n" +
        "      \"alphaItem\" : \"1234567891234567\",\r\n" +
        "      \"alphaType\" : \"KIND_OF_TYPE\",\r\n" +
        "      \"otherProperty\" : \"2017-06-21\",\r\n" +
        "      \"someOtherProperty\" : \"NONE\"\r\n" +
        "    }\r\n" +
        "  }\r\n" +
        "}";

private static final String UNINDENTED_UNSORTED = "{" +
        "\"firstChild\":{" +
        "\"subChild\":{" +
        "\"alphaItem\":\"1234567891234567\"," +
        "\"otherProperty\":\"2017-06-21\"," +
        "\"someOtherProperty\":\"NONE\"," +
        "\"alphaType\":\"KIND_OF_TYPE\"" +
        "}" +
        "}" +
        "}";

private static final String UNINDENTED_SORTED = "{" +
        "\"firstChild\":{" +
        "\"subChild\":{" +
        "\"alphaItem\":\"1234567891234567\"," +
        "\"alphaType\":\"KIND_OF_TYPE\"," +
        "\"otherProperty\":\"2017-06-21\"," +
        "\"someOtherProperty\":\"NONE\"" +
        "}" +
        "}" +
        "}";

@Test
public void should_sort_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper
            .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, INDENTED_UNSORTED);

    // Then
    assertEquals(UNINDENTED_SORTED, formattedJson);
}

@Test
public void should_indent_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, UNINDENTED_UNSORTED);

    // Then
    assertEquals(INDENTED_UNSORTED, formattedJson);
}

@Test
public void should_sort_and_indent_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper
            .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
            .enable(SerializationFeature.INDENT_OUTPUT);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, INDENTED_UNSORTED);

    // Then
    assertEquals(INDENTED_SORTED, formattedJson);
}

//
// Utils
//

private String tryingToFormatJson(ObjectMapper objectMapper, String unformattedJson)
        throws IOException, JsonProcessingException {
    JsonNode unsortedTree = objectMapper.readTree(unformattedJson);
    Object treeToValue = objectMapper.treeToValue(unsortedTree, Object.class);
    return objectMapper.writeValueAsString(treeToValue);
}

}

*

*How could I sort my JSON with Jackson?

*Do you have any solution for implementing my method tryingToFormatJson?

*Is Jackson the right tool I want for doing this?

A: When you call objectMapper.treeToValue(unsortedTree, Object.class), the Object's type is a subclass of Map - just put a System.out.println(treeToValue.getClass()) to check.
And according to javadoc, SORT_PROPERTIES_ALPHABETICALLY doesn't sort map keys:

Feature that defines default property serialization order used for POJO fields (note: does not apply to Map serialization!)

If you want to sort the fields, you have to create a custom class for you structure, like this:
public class Tree {
    private Map<String, Child> firstChild;

    // getters and setters
}

public class Child {
    private String alphaItem;

    private String otherProperty;

    private String someOtherProperty;

    private String alphaType;

    // getters and setters
}

And change the treeToValue call to:
Tree treeToValue = objectMapper.treeToValue(unsortedTree, Tree.class);

With this, the fields will be sorted and the test will work.


text:
Q: Error undefined columns selected I am new to coding and I received this code from a colleague for research purposes. The original data set for this code had 4 spectral variables, 12 texture variables and a combination of spectra and texture resulting in 16 variables in total. I am running the code only with texture variables but now I only have 6 texture variables in the new data set. I have attached the first part of the original code below where I have 12 texture variables..Please could someone assist me in changing my code using the new data set with 6 texture variables...I have attached an example of how my data is set up which is exactly the way the original data set is set up just with only 6 texture variables at the end.
Here is the image:

#change your work directory
#############################
setwd("C:/Texture")

############################

#output all resuls to a text file
#change apend to TRUE to record all analysis
#sink("Results.txt",append =F)

 source("plsrfsource.r")

    data<-read.csv("texture0ratios.csv",header=T, na.strings=c(".", "NA", "", "?"))

# Check the dataset

colnames(data)

#select response variable
#this example uses EnumAge

################
y <-data$EnumAge
################

#make sure that your explantory variables are in the same order as the example dataset

#######################
#texture variables only

x<-data[,16:27]

#spectral variables only
#x<-data[,12:15]

#using all the variables
#x<-data[,12:27]
######################

colnames(x)

#there must be 12 texture variables
#4 spectral variables
length (x)

#join the x and y

dataset<-cbind(y,x)

# split into test and training datasets

set.seed(123)

inTrain <- createDataPartition(y, p = 0.7, list = F)
dataTrain<- dataset[inTrain[,1],]
dataTest <- dataset[-inTrain,]

trainY<-dataTrain$y
trainX<-as.matrix(dataTrain[-1])

testY<-dataTest$y
testX<-as.matrix(dataTest[-1])

A: You only need to make a few minor adjustments:
#######################
#texture variables only

x<-data[,16:21]

#spectral variables only
#x<-data[,12:15]

#using all the variables
#x<-data[,12:21]
######################

Let me know if this does not solve your problem!


text:
Q: Iterate over a specific column in a dictionary in Python I'm trying to iterate over the second column (first index) in a dictionary similar to:
dict    =   {
"Me": [("Blue", 37, 1,  2, "up", "left")],
"You": [("Green",  03, 3, 4, "up", "right"),
    ("Red", 29, 5, 6, "down", "right"),
    ("Yellow", 35, 7,  8, "straight", "down")],
"Them": [("Black", 08, 9, 10, "up", "up"),
    }

and retrun the largest value.  What I have is:
    for c in dict[1:2]:

    x = 0

    if c > x:

        x = c

return x

I'm getting an unhashable type error.  I know it has something to do with how the code iterates over the dictionary but I'm stuck on how to fix it.  Language is Python.  What is wrong here?  Any help is greatly appreciated!

A: First, STOP using reserved names (like dict) for your variables
Second, by writing mydict[1:2] you request the value from dictionary that refers to the element with the key 1:2, which is the slice operator.
   Now the slice operator can't be a key in a dictionary (there isn't a hash function that takes the operator and returns a numeric value which is used as index in the values array).
   So, you should use the slice operator on the list of keys and list of values, or on the list of items - lists which have an order and it makes sense to have slices on them (the dictionary is not guaranteed to have the same order after it's changed)
Third, why do you set the x to 0 in every iteration in the for loop?
And fourth, you could do this:
for value in mydict.values():
    (a, b, c, d, e, f) = value[0]
    print(b)

A: 1:2 is a slice object, which is unhashable, what you want instead is something like this:
max(d[1] for l in dict.values() for d in l)

A: Have you tried using dict.iteritems() to iterate over key-value pairs?
ex:
for key, val in dic.iteritems():
    print "Key: " + str(key) + "\t Value:" + str(val)


text:
Q: Quarto html display of a raw output table with the knitr engine I'm trying to obtain the same HTML display from Quatro when writing a table
the usual way and as raw output.
The issue is that the raw output is missing the striped rows.
As a workaround, I surrounded the code block with an explicit cell ::: {.cell} ... :::.
Here is a simple example to illustrate my point.
test.qmd
---
tbl-colwidths: [75,25]
format: html
---

```{r}
df <- data.frame(A=1:3, B=1:3)
```

1. Usual way of displaying a table

```{r}
knitr::kable(df)
```

2. Raw output (no stripes as the html table misses the `table-striped` class)

```{r}
#| results: asis
print(knitr::kable(df))
```

3. Surrouneded by `{.cell}` block

::: {.cell}
```{r}
#| results: asis
print(knitr::kable(df))
```
:::

Screenshot:
 of the rendered page (quarto render test.qmd)
Is there a better way?

A: You could create separate (styles.css) css file where you can specify the background color of your tables using this code:
tbody tr:nth-child(odd){
  background-color: #DCDCDC;
}

Then you can say css: styles.css for your html format like this:
---
tbl-colwidths: [75,25]
format:
  html:
       css: styles.css
---

{r}
df <- data.frame(A=1:3, B=1:3)

{r}
#| results: asis
print(knitr::kable(df))

Output:


text:
Q: UITableView on top UIScrollView not working I putting UITableView on top UIScrollView, and when I want to scroll the UITableView, it is not scrolling .... (the UIScrollView didScroll function isn't running).
I worked in the storyboard.
My code:
CGRect screenSize = [[UIScreen mainScreen]bounds];
  [_myScrollView setContentSize: CGSizeMake(screenSize.size.width, screenSize.size.height)];
   _myScrollView.delegate = self;
     _tableView.scrollEnabled = NO;
    _myScrollView.scrollEnabled = YES;

V. B.
I wont the UIScrollView to scroll, not the UITableView...

A: Change the contentSize of your scrollView. It is set to screen size now. Use this code
[_myScrollView setContentSize: CGSizeMake(screenSize.size.width, 2 * screenSize.size.height)];

A: I tought you're hierarchy is like::
UIView
  - UIScrollView  (outerscroll)
       - Some other views and buttons
       - UITableView (tableView)

From Apple Documentation, you shouldn't embed a UITableViewinside a UIScrollView.
Important: You should not embed UIWebView or UITableView objects in UIScrollView objects. If you do so, unexpected behavior can result because touch events for the two objects can be mixed up and wrongly handled.
Your problem is really related to what your UIScrollView does.
But if it's just to hide the tableview when needed (that was my case), you can just move the UITableView in its superview.
I found a small example here : https://github.com/rvirin/SoundCloud/


text:
Q: How do I securely manage one-off scripts to fix data? Occasionally, things go wrong with software. When things go wrong, one of the worst things that can happen is that the system leaves some data in an inconsistent or invalid state. Of course we try to reduce these cases, but they do happen.
When they happen, we often must take corrective action in the form of some data cleanup. (In addition to hardening the code that allowed the inconsistency.) Some of the techniques I've seen for that cleanup include

*

*editing the production database directly

*using a REPL like Rails's rails console to edit the production data through code

*writing a script and then running it

*writing a Rails migration and then running it

The script and migration versions have a couple of advantages over the direct-access versions:

*

*the team can use pull-requests or other code-review techniques to ensure that the script will operate as expected

*the script stays behind as a record of what the team did

*the script can be run in non-production environments or in a "dry-run" mode

Unfortunately, if checked in, these scripts also have a significant security disadvantage: they leak PII or other sensitive data from the database into source control. For example,
# 2013-07-05: delete all of Susan Yee's OAuth tokens because she's locked out
User.find_by_email('susan.yee@example.com').oauth_tokens.delete_all!

I can think of a couple solutions to this risk:

*

*prefer opaque identifiers in the script. I'm for this, but (a) it's not always possible and (b) it also obfuscates exactly what is happening, reducing the value of the audit log.

*move all source-control inside your firewall. This is definitely more secure, but means the team can't take advantage of many cloud-based tools (e.g. Code Climate, TravisCI)

*separate the scripts from the seed data. Write the scripts in a parameterized fashion even though they will only be used once. This keeps the sensitive data out of source-control, but it means the record of what was done is harder to piece together.

Does anyone have a proven technique?

A: I'll start by saying that the corrective actions I had to do during my work have never been so frequent or complex to require the writing of dedicated scripts; so I've always stopped to the points 1. and 2. that you said (editing database directly or using rails console).
Anyway, here are a couple of solutions that come to mind:

*

*Make the script general, so it covers the case you want to fix without specifying "ad personam" data. In this case, your example (I report it here for completeness):
# Delete all of Susan Yee's OAuth tokens because she's locked out
User.find_by_email('susan.yee@example.com').oauth_tokens.delete_all!

becomes something like:
# Delete locked out people OAuth tokens
User.locked_out.each{ |u| u.oauth_tokens.delete_all! }

The advantages are that the script is based on a logic and covers general cases; the (big) disadvantage is that not always you have a state that you can use to find the data you want to edit, and for these cases (the "ad personam" cases) this solution is not applicable.

*Pass sensible data via arguments / environment variables / git-ignored files
This is what I use when I have to store per-app informations, like f.e. the Rails secret key: I put it into a file config/.secret_key, something like this) which is git-ignored, and I put the app secret key there.
But the git-ignored file is for persistent data; since you're dealing with one-off scripts I think arguments are a good solution:
# Delete all OAuth tokens of the specified user
User.find_by_email(ARGV[0]).oauth_tokens.delete_all!

and then run history -c so you're safe even if someone manages to leak your history (although you probably have bigger problems in that case :P )
This solution doesn't suite well if you have also to store the informations of the edits you did; but I don't think this is your case, and anyway the log files should contain the informations about what you did. If you have this need probably is better using some database versioning logic (here some resources about this, if you are interested about it)


text:
Q: xpath function syntax javascript I am very new to Xpath and although its concepts are simple for a long-time programmer, I am a bit confused on the syntax for functions .... any help appreciated.
let's say you have (for simplicity this is partial from southwind.xml) an xml file
<Orders>
    <Order OrderID="10248">
        <CustomerID>VINET</CustomerID>
        <EmployeeID>5</EmployeeID>
        <OrderDate>1996-07-04T14:25:55</OrderDate>
        <RequiredDate>1996-08-01T06:43:44</RequiredDate>
        <ShippedDate>1996-07-16T04:00:12</ShippedDate>
        <ShipVia>3</ShipVia>
        <Freight>32.3800</Freight>
        <ShipName>Vins et alcools Chevalier</ShipName>
        <ShipAddress>59 rue de l'Abbaye</ShipAddress>
        <ShipCity>Reims</ShipCity>
        <ShipRegion/>
        <ShipPostalCode>51100</ShipPostalCode>
        <ShipCountry>France</ShipCountry>
        <OrderDetails>
            <OrderDetail>
                <ProductID>11</ProductID>
                <UnitPrice>14.0000</UnitPrice>
                <Quantity>12</Quantity>
                <Discount>0</Discount>
            </OrderDetail>
            <OrderDetail>
                <ProductID>42</ProductID>
                <UnitPrice>9.8000</UnitPrice>
                <Quantity>10</Quantity>
                <Discount>0</Discount>
            </OrderDetail>
            <OrderDetail>
                <ProductID>72</ProductID>
                <UnitPrice>34.8000</UnitPrice>
                <Quantity>5</Quantity>
                <Discount>0</Discount>
            </OrderDetail>
        </OrderDetails>
    </Order>
    <Order OrderID="10249">
        <CustomerID>TOMSP</CustomerID>
        <EmployeeID>6</EmployeeID>
        <OrderDate>1996-07-05T06:39:18</OrderDate>
        <RequiredDate>1996-08-16T03:39:38</RequiredDate>
        <ShippedDate>1996-07-10T14:39:39</ShippedDate>
        <ShipVia>1</ShipVia>
        <Freight>11.6100</Freight>
        <ShipName>Toms Spezialitäten</ShipName>
        <ShipAddress>Luisenstr. 48</ShipAddress>
        <ShipCity>Münster</ShipCity>
        <ShipRegion/>
        <ShipPostalCode>44087</ShipPostalCode>
        <ShipCountry>Germany</ShipCountry>
        <OrderDetails>
            <OrderDetail>
                <ProductID>14</ProductID>
                <UnitPrice>18.6000</UnitPrice>
                <Quantity>9</Quantity>
                <Discount>0</Discount>
            </OrderDetail>
            <OrderDetail>
                <ProductID>51</ProductID>
                <UnitPrice>42.4000</UnitPrice>
                <Quantity>40</Quantity>
                <Discount>0</Discount>
            </OrderDetail>
        </OrderDetails>
    </Order>

in Javascript how do I construct a path (what is correct syntax) for using ANY of xpath functions...I understand the basics of selecting nodes, but what is the syntax for usting functions ..
For example let's say I wanted SUM of all Quantity for orders ... this is where I am getting stuck and if I understood the syntax for one function, the rest would be easy to get!
What would the path be I tried this, and I know it is very wrong..
path="/Orders/Order/OrderDetails/OrderDetail[sum(quantity)]";

Thank you in advance

A: First of all, your XML needs the tag closing the root node. (</Orders>)
This piece of javascript code using XPath sum function works in firefox, it returns 76 which is the sum of all Quantity tags in the XML. I hope it helps:
<script>
var xml=document.implementation.createDocument('', 'doc', null);
xml.load('books.xml');
path='sum(/Orders/Order/OrderDetails/OrderDetail/Quantity)';
var result=xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
document.write(result.numberValue);
</script>

You can find XPath functions here. And good example sintaxis here.

A: Use document.selectNodes (IE) or document.evaluate (Chrome, Firefox, Opera, Safari) functions. You will find the way to use them here: http://www.w3schools.com/xpath/xpath_examples.asp.
Mozilla also provides a useful documentation here: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript.
Here's how to sum the quantities per article using document.evaluate.
// retrieves xml document
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "southwind.xml", false);
xhttp.send("");
var xml = xhttp.responseXML;

// evaluates xpath expressions
var orders = xml.evaluate("//Order", xml, null, XPathResult.ANY_TYPE, null);
var order = orders.iterateNext();
while (order) {

  var result = xml.evaluate("sum(OrderDetails//Quantity)", order, null,
    XPathResult.NUMBER_TYPE, null);
  console.log(result.numberValue);
  order = orders.iterateNext();
}

A: just to followup... makes total sense that if you are using Xpath with Javascript, it all comes down to that XpathResult... so I found this site which answers my previous follow up question just in case any else has it...
thanks again
http://help.dottoro.com/ljagksjc.php


text:
Q: Pharo: menu error I broke something in my Pharo image, but i don't know exactly what. Now when I try to file-out my package to insert in a new image, I only see 'Why you see this menu' and 'Debug'. If I run menu debug in the playground, I get a FallbackMenu.
How can I fix this error?
EDIT: When I try to click on my package, The system browser is acting very weird an the following error pops up: link
Using  Max's your code, i get 2 nil keys:

*

*The first one is a mistake in my code (I assigned a class binding to nil instead of a instance variable with the same name). But I can't edit this because I can't access it through the System Browser.

*The second one is ActiveEvent. I don't know where this comes from and whether this or the previous nil causes the System Browser to act weird

A: One possibility is that you nilled a class binding. Inspect the following to get a list of keys and values that are nil:
Smalltalk globals associations select: [ :assoc |
    assoc value isNil or: [
        assoc key isNil ] ].

BTW: rather then attaching a screen shot it would help if you attached the stack. To get the stack trace, right click on the topmost entry in the stack list (the one that's selected in your screen shot) and select "Copy to clipboard". Then paste the contents (or at least the first 30 frames) here.
Update
ActiveEvent seems normal. I have the same. The second one is very likely problematic. You may be able to cheat your way out by removing the entry:
Smalltalk globals removeKey: nil.

If done a quick try and it seems to work.


text:
Q: How can I identify lost internet connection and timeout MySQL upload in under 1 second? [while using AWS RDS and pymysql] Context:
I have a simple program that gets sensor data once per second and immediately uploads it to AWS RDS MySQL instance. However, I have very spotty network connection that constantly goes in and out. Half the time the data uploads in under 1 second no problem, but when there is no internet connection, pymysql (mysql? aws?) takes 5 seconds to throw an error. Ideally it would only take 1 second to throw an error and then I could properly catch it and continue collecting sensor data without interruption.
Example Code:
import pymysql
import gpsd

def uploaddata(): #I want this to timeout in 1 second.
    try:
        db = pymysql.connect('host=xxx.region.rds.amazonaws.com', portxxxx,user='admin',password='xxxx')
        with db:
            with db.cursor() as cursor:
                cursor.executemany(insertstatement,datatoupload)
                db.commit()
        datatoupload.clear()
    except pymysql.err.OperationalError:
        logging.info('rds temp dns failure aka no internet, saving datatoupload for later')

datatoupload= []
lasttime = []
insertstatement = (
    "INSERT INTO db.tablename(timelogged,datatoupload)"
    "VALUES (%s)"
)

startpacket = gpsd.get_current()

while True:
    packet = gpsd.get_current() #get lastest value from gpsd
    newtime = packet.time[0:19]
    speed = packet.hspeed
    if newtime!= lastime: #if data is in the next second, save speed value
        data = [newtime,speed]
        datatoupload.append(data)
        uploaddata()
        lasttime = newtime

Solutions I've attempted with no luck:

*

*spinning up a nonbinding thread to wait the 5 seconds while the error is thrown, but maybe I implemented incorrectly because the program waited until the thread was complete before capturing more sensor data (even though I did not use join)

*implementing a timeout class, function, and context manager with the help of this tutorial: https://www.youtube.com/watch?v=vGWSdp9dyhI which works for all other functions except this one.

*implementing Panagiotis Simakis' solution which didn't work for pymysql query: How to set a timeout for a pymysql query

*modifying the db instance parameter group to change any global timeout parameters that looked relevant to 1 (maybe throwing spaghetti at the wall which I'm not above)


text:
Q: Embed a video in a pdf I'm using wicked_pdf with ruby on rails and am able to generate a pdf with images and texts, but no videos. Is it possible to do it? If so, how?

A: wicked_pdf is basically just a wrapper around wkhtmltopdf which uses the WebKit engine to convert HTML to PDF. If I understand this post correctly, wkhtmltopdf relies on a specific version of WebKit built for QT which currently doesn't support that tag. So the short answer is no, the long answer is to start asking the wkhtmltopdf people when the video tag will be supported.


text:
Q: Intel site says VT-x is supported on my CPU, but tests say otherwise I have a laptop with an Intel 2nd Gen. i7-2729QM (http://ark.intel.com/products/50067/) and the Intel site says that it supports VT-x, but I've downloaded the Intel Processor Identification Utility (http://www.intel.com/support/processors/tools/piu/sb/CS-014921.htm) and the test says that my CPU does not have VT-x.
There is no option in my BIOS that allows me to enable/disable VT-x. I researched my laptop model (SAGER NP8170) and most forums say that it's enabled by default and there's no option in the BIOS. So assuming that's true, what gives?
I also downloaded another tool called SecurAble from GRC and it also says that my CPU doesn't support VT-x. VirtualBox also says that my CPU does not support virtualization.
My mind is boggled by why it says on the Intel site that my CPU supports VT-x but all other tests show otherwise. Anyone know what's going on? Thanks in advance.

A: I realized that Hyper-V was enabled in my system, so I disabled it and everything worked normally. All the aforementioned tools are now reporting VT-x as enabled.


text:
Q: Generate all nonisomorphic rooted trees from a vertex set with a common root For a vertex set $v = \left\{v_1...v_n  \right\}$ and a common root $r$, is there an efficient (maybe $O(1)$ per tree) algorithm that generates all non-isomorphic trees on all nodes $v$ and with root $r$.
Two trees are isomorphic if all the parent-child relationships are the same, i.e. all equivalent nodes in the two trees have the same parent and the same children.
Example: $v = \left\{v_1, v_2, v_3\right\}$
All trees should have the same root an the same node set. The following image shows some valid trees:

Including a tree should lead to all other isomorphic trees being ignored

Another SO post shows a implementation that finds unrooted topologies:
https://codereview.stackexchange.com/questions/202773/generating-all-unlabeled-trees-with-up-to-n-nodes
In one answer, there appears this algorithm for creating unrooted non-isomorphic topologies on $n$ nodes in constant time per tree.
Robert Alan Wrights, Bruce Richmond, Andrew Odlyzko and Brendan D. Mckay (1986). "Constant time generation of free trees". SIAM J. Comput. 15:2, pp. 540–548.
I am not sure if it is possible to extend this algorithm efficiently to generate the desired rooted trees.

A: I can do it in $O(n^2)$ per tree.
The number of possible trees is $(n+1)^{n-1}$, since choosing a tree in your problem is equivalent to choosing an undirected tree on the vertex set $v\cup \{r\}=\{v_1,\dots,v_n,r\}$, and then directing all edges towards the root. The number of undirected trees on $n+1$ vertices is $(n+1)^{n-1}$ (this is Cayley's theorem), and these trees can be generated efficiently using Prüfer codes.
Specifically, iterate through all lists of length $n-1$ with entries in $\{0,1,2,\dots,n\}$, where $0$ represents $r$ and $1$ through $n$ represent $v_1$ through $v_n$. For each list, generate the corresponding tree with vertices $\{r,v_1,\dots,v_n\}$ using the algorithm to convert a Prüfer sequence into an undirected tree. Finally, turn this into a directed tree using breadth first search starting from vertex $r$.


text:
Q: How can i validate integer form in php? I want to validate integer form using PHP. Do anyone of you know how to validate it?
my code like this
`
          Thông tin thành viên
            ">

First name : 	<input type="text" class="form-control" name="firstname">

Last name : 	<input type="text" class="form-control" name="lastname" />

User Name: 	<input type="text" class="form-control" name="username"/>

Password: 	<input type="password" class="form-control" name="password">

Email: 	<input type="email" class="form-control" name="email"/>

Phone: 	<input type="text" class="form-control" name="phone"/>

Cấp độ :

                <select class="form-control" name="level">
                    <option selected>---Free choose---</option>
                    <option value="1">Administrator</option>
                    <option value="0">Member</option>
                </select>

         <button type="submit" name="add" class="btn btn-primary btn-md">Thêm thành viên</button>

`

When people input the phone i want to check whether it is integer or not? can you help?

A: Try using this is you want to check it on runtime.

Phone: 	<input type="number" class="form-control" name="phone"/>

Or use is_int or is_numeric if you want to check the phone number after POST.

A: You can use either:
is_int

or
is_numeric

A: A safe attitude for the input validation process in php is like this for integer numbers:
HTML form
<input type="text" name="phone"/>

PHP
if( !filter_var( $_POST['phone'], FILTER_VALIDATE_INT) === false){
    echo("Variable is an integer");
}else{
    echo("Variable is not an integer");
}

Keep in mind that you can never trust the traffic originated from user, thus things like:
<input type="number" name="phone"/>

could not be the answer to this problem. You may use such methods to just help the end users fill-in your forms.


text:
Q: How to export a DataTable variable to EXCEL and download the excel I'm trying to use NPOI like this:
private Stream RenderDataTableToExcel(DataTable SourceTable)
{
    XSSFWorkbook workbook = null;
    MemoryStream ms = null;
    ISheet sheet = null;
    XSSFRow headerRow = null;
    try
    {
        workbook = new XSSFWorkbook();
        ms = new MemoryStream();
        sheet = workbook.CreateSheet();
        headerRow = (XSSFRow)sheet.CreateRow(0);
        foreach(DataColumn column in SourceTable.Columns)
            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
        int rowIndex = 1;
        foreach(DataRow row in SourceTable.Rows)
        {
            XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
            foreach(DataColumn column in SourceTable.Columns)
                dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
            ++rowIndex;
        }
        for (int i = 0; i <= SourceTable.Columns.Count; ++i)
            sheet.AutoSizeColumn(i);
        workbook.Write(ms);
        ms.Flush();
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        ms.Close();
        sheet = null;
        headerRow = null;
        workbook = null;
    }
    return ms;
}
private void DownloadExcel(DataTable dt, string reportName)
{
    Stream s = RenderDataTableToExcel(dt);
    if (s != null)
    {
        MemoryStream ms = s as MemoryStream;
        Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + HttpUtility.UrlEncode(reportName) + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"));
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Length", ms.ToArray().Length.ToString());
        Response.BinaryWrite(ms.ToArray());
        Response.Flush();
        ms.Close();
        ms.Dispose();
    }
    else
        Response.Write("Error!Connot Download");
}

I've got binary stream instead of a ms-excel file.
PS: I really want to know how to generate a file for download, that is, why your code works, the browser generates the file or the server?

A: NPOI is a helper module to create excel files four you. This is created server-side and in memory. (workbook.Write(ms) write the excel file in memory )  The excel file goes over the wire as an byte[] and the browser decide based on file and contenttype what to do with it.
When u use classic asp.net then put a link in your aspx page like below
download...

Create a Handler.ashx and put the code fom DownloadExcel into  ProcessRequest from Handler.ashx.
public void ProcessRequest (HttpContext context)
{
    //create dumy data, or in youre case the data form somewhere else
    DataTable table = new DataTable();
    table.Columns.AddRange(new[]
        {
            new DataColumn("Name")
        });
    table.Rows.Add("david");
    table.Rows.Add("Ruud");

    // your code
    Stream s = RenderDataTableToExcel(dt);
    if (s != null)
    {
        MemoryStream ms = s as MemoryStream;
        Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + HttpUtility.UrlEncode(reportName) + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"));
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Length", ms.ToArray().Length.ToString());
        Response.BinaryWrite(ms.ToArray());
        Response.Flush();
        ms.Close();
        ms.Dispose();
    }
    else
        Response.Write("Error!Connot Download");
    }
}

in MVC its like below.
[HttpGet]
public ActionResult ExportToExcel(string reportName)
{
    byte [] reportDocument = RenderDataTableToExcel().ToArray();

    Response.StatusCode = (int)HttpStatusCode.OK;
    return File(reportDocument, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", reportName);
}

A: I've used ajax TVT.
window.location.href = "?action=DownloadAll";
    //$.ajax({
    //    url: "?action=DownloadAll",
    //    type: "get",
    //    success: function () { }
    //});

A: You can turn a DataTable into an Excel worksheet with some very readable code:
XLWorkbook wb = new XLWorkbook();
DataTable dt = GetDataTableOrWhatever();
wb.Worksheets.Add(dt,"WorksheetName");

It will run super-fast too!


text:
Q: JSESSIONID not passed through HTTP cookie Manage in JMeter Through JMeter is not able to pass the JSESSIONID although it happens very rarely, I am not able to find out the root cause.
My first request is login - POST on HTTPS protocol
Next request is using the JSESSIONID of the first request as i have added HTTP Cookie Manager from the Config Element, this request is GET over HTTPS and its giving 401 status code.
And the login successfully happened.
Anyone, please suggest ???


text:
Q: Facebook profile URL regular expression Given the following Facebook profile and page URLs, my intent is to extract profile ids or usernames into the first match position.
http://www.facebook.com/profile.php?id=123456789
http://www.facebook.com/someusername
www.facebook.com/pages/Regular-Expressions/207279373093

The regex I have so far looks like this:
(?:http:\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(\d.*))?([\w\-]*)?

Which produces the following results:
Result 1:

*

*123456789

*

Result 2:

*

*

*someusername

Result 3:

*

*

*207279373093

The ideal outcome would look like:
Result 1:

*

*123456789

Result 2:

*

*someusername

Result 3:

*

*207279373093

That is to say, I'd like to have the profile identifier to always be returned in the first position.
It would also be ideal of www.facebook.com/ and facebook.com/ didn't match either.

A: Only this regular expression works correctly for all FB URLs:
/(?:https?:\/\/)?(?:www\.)?(?:facebook|fb|m\.facebook)\.(?:com|me)\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[\w\-]*\/)*([\w\-\.]+)(?:\/)?/i

A: I've tried every single answer above and each one doesn't work for at least one reason. This most likely won't be helpful to OP, but if anybody like me finds this in a web search, I believe this is the correct answer:
^(?:.*)\/(?:pages\/[A-Za-z0-9-]+\/)?(?:profile\.php\?id=)?([A-Za-z0-9.]+)

Supports basically everything I can think of, except verifying that the domain contains facebook.com. If you need to check if the URL is valid, this should be done outside of a regular expression to make sure the page or profile actually exists. Why check it twice, especially when one of the checks is incomplete?

*

*Doesn't cut off the first character

*Grabs URLs with periods

*Ignores superfluous GET parameters

*Supports /usernames as provided by the Facebook app

*Supports both profile URL structures

*Doesn't match facebook.com/ or facebook.com (by ignoring them)

*Works with and without www. (by ignoring it)

*Supports both http and https (by ignoring them)

*Supports both facebook.com and fb.com (by ignoring them)

*Supports pages with special characters in the name (by ignoring them)

*Supports #! (by ignoring it)

*Supports bounce_page#! (by ignoring it)

A: The most completed pattern for Facebook profile url:
/(?:https?:\/\/)?(?:www\.)?facebook\.com\/.(?:(?:\w)*#!\/)?(?:pages\/)?(?:[\w\-]*\/)*([\w\-\.]*)/

It detects all the cases + one important difference. Other regex patterns recognize http://www.facebook.com/ as a valid Facebook Profile URL while it is not a valid Profile url. It is just the original Facebook URL and not a user or page address. But this regex can distinguish a normal url from a profile and page url and only accepts the valid one.

A: Matches facebook.com, m.facebook.com, mbasic.facebook.com and fb.me (short link)
/(?:https?:\/\/)?(?:www\.)?(mbasic.facebook|m\.facebook|facebook|fb)\.(com|me)\/(?:(?:\w\.)*#!\/)?(?:pages\/)?(?:[\w\-\.]*\/)*([\w\-\.]*)/ig

Facebook URL regex DEMO

A: I'd recommend Rad Software Regular Expression Designer.
Also this online tool is great https://regex101.com/ ( though most people prefer http://regexr.com/ )
(?:(?:http|https):\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\-]*)?

A: I made a gist a while back that works fine against the given examples:
# Matches patterns such as:
#    http://www.facebook.com/my_page_id => my_page_id
#    http://www.facebook.com/#!/my_page_id => my_page_id
#    http://www.facebook.com/pages/Paris-France/Vanity-Url/123456?v=app_555 => 45678
#    http://www.facebook.com/pages/Vanity-Url/45678 => 45678
#    http://www.facebook.com/#!/page_with_1_number => page_with_1_number
#    http://www.facebook.com/bounce_page#!/pages/Vanity-Url/45678 => 45678
#    http://www.facebook.com/bounce_page#!/my_page_id?v=app_166292090072334 => my_page_id

/(?:http:\/\/)?(?:www\.)?facebook\.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[\w\-]*\/)*([\w\-]*)/

To get the latest version: https://gist.github.com/733592

A: Regex that will correctly identify profile pages with a . in the name like www.facebook.com/my.name and it will also exclude www.facebook.com/ or home.php as it is not a valid facebook page.
https://regex101.com/r/koN8C2/2
(?:(?:http|https):\/\/)?(?:www.|m.)?facebook.com\/(?!home.php)(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\.-]+)

Let me know if you found any that are not matched.

A: This works well for me. It can detect personal profile url, and exclude all the fan pages, and groups.
.+www.facebook.com\/[^\/]+$


text:
Q: Merging datasets by id and maintain one row for each id I am attempting to merge 2 datasets belonging to a single id with a larger dataset.
However, I am having trouble merging the two single row datasets into a single row within the larger dataset.
Is there a simple way to merge with dplyr and only overwrite values if they are NA's?
My data:
df1 <- data.frame(id=1:5, b=6:10, c=c("a", "b", "c", "d", "e"), d=c(NA, 1,2,3, 4))
df2 <- data.frame(id=6, b=2, c="f", d=NA_real_)
df3 <- data.frame(id=6, b=NA_real_, c=NA_character_, d=5, e="a")

> df1
  id  b c  d
1  1  6 a NA
2  2  7 b  1
3  3  8 c  2
4  4  9 d  3
5  5 10 e  4
> df2
  id b c  d
1  6 2 f NA
> df3
  id  b    c d e
1  6 NA <NA> 5 a

My attempt:
merge1 <- dplyr::full_join(df1, df2) %>% full_join(df3)

Desired output:
output <- data.frame(id=1:6, b=c(6:10,2), c=c("a", "b", "c", "d", "e", "f"), d=c(NA, 1,2,3, 4, 5), e=c(NA,NA, NA, NA, NA, "a"))

> output
  id  b c  d    e
1  1  6 a NA <NA>
2  2  7 b  1 <NA>
3  3  8 c  2 <NA>
4  4  9 d  3 <NA>
5  5 10 e  4 <NA>
6  6  2 f  5    a

As opposed to:
  id  b    c  d    e
1  1  6    a NA <NA>
2  2  7    b  1 <NA>
3  3  8    c  2 <NA>
4  4  9    d  3 <NA>
5  5 10    e  4 <NA>
6  6  2    f NA <NA>
7  6 NA <NA>  5    a

Thank you

A: You can try:
list(df1, df2, df3) %>%
 bind_rows() %>%
 group_by(id) %>%
 summarise_all(~ first(na.omit(.)))

     id     b c         d e
  <dbl> <dbl> <chr> <dbl> <fct>
1     1     6 a        NA <NA>
2     2     7 b         1 <NA>
3     3     8 c         2 <NA>
4     4     9 d         3 <NA>
5     5    10 e         4 <NA>
6     6     2 f         5 a

A: you can try
library(tidyverse)
df1 %>%
  mutate_if(is.factor, as.character) %>%
  bind_rows(mutate_if(df2, is.factor, as.character)) %>%
  left_join(select(df3, id, d, e), by = "id") %>%
  mutate(d= ifelse(is.na(d.x), d.y, d.x)) %>%
  select(-d.x, -d.y)


text:
Q: Gradle variable from another applicationId flavor I need to build an application created with a flavor and create a dynamic variable who points to an applicationId of another flavor (Because the code of an internal library uses the applicationId of other applications) but I don't know how to do that.
Here is the sample code :
defaultConfig {
    applicationId "com.sample.mycompany"
}

buildTypes {
    release {
    }
    qualif {
        applicationIdSuffix = ".qual"
    }
    debug {
        applicationIdSuffix = ".dev"
    }
}

flavorDimensions "client", "nature"
    productFlavors {
        ClientA {
            dimension "client"
            applicationIdSuffix = ".A"
        }
        ClientB {
            dimension "client"
            applicationIdSuffix = ".B"
        }

        NatureX {
            dimension "nature"
            applicationIdSuffix = ".X"
        }
        NatureY {
            dimension "nature"
            applicationIdSuffix = ".Y"
            // A buildconfigField variable here to get com.sample.mycompany[client].X[buildTypes]
        }
        NatureZ {
            dimension "nature"
            applicationIdSuffix = ".Z"
            // A buildConfigField variable here to get com.sample.mycompany[client].X[buildTypes]
        }
}

When I compile with the Build Variant : ClientANatureYDebug
, final applicationId is com.sample.mycompany.A.Y.dev
I want a dynamic variable with buildConfigField (or something else to retrieve the new variable in Java) who is com.sample.mycompany.A.X.dev
I think to get the final applicationId and replace the applicationIdSuffix of the current nature compilation dimension by .X and get the result in a new variable but I do not know how. Can you help me ?

A: Fixed with :
buildConfigField "String", "VAL_SHARE_TO_RECEIVER_APP_ID", "APPLICATION_ID.replace(\".Y\", \".X\")"


text:
Q: Getting "React Hook useEffect has a missing dependency" error for a state that doesn't need to be in the dependency array My eslint is complaining about react-hooks/exhaustive-deps. I am not doing anything wrong here right, the function should only run if the pathname changes:
 const pathname = usePathname();

  useEffect(() => {
    setNavigation(
      navigation.map((item) => ({
        ...item,
        current:
          item.href.toLowerCase() === pathname?.substring(3).toLowerCase()
      }))
    );
  }, [pathname]);

Should I just disable the lint with eslint-disable-next-line react-hooks/exhaustive-deps on that function?
Thanks!

A: Eslint is yelling because the idea is to have in the dependency any variable defined outside of a useEffect, and that's used inside of it. In your case, you could use a function updater like so:
useEffect(() => {
  setNavigation((navigation) =>
    navigation.map((item) => ({
      ...item,
      current: item.href.toLowerCase() === pathname?.substring(3).toLowerCase(),
    }))
  );
}, [pathname]);

This way, you are not using navigation from the outside, but the one that React will give to the state setter. So the linter will let you be.
Side note: often, disabling the lint is not a good idea, as it might lead to bugs.


text:
Q: Choose which attributes to serialize When serializing a div into string with new XMLSerializer().serializeToString(), I would like to choose which DOM attributes to serialize.
Example :

var blah = document.getElementById('blah');
var blah1 = document.getElementById('blah1');
blah1.style.top = "100px";
console.log(new XMLSerializer().serializeToString(blah));
#blah1 { position: absolute; }

Bonjour1

For example, instead of ...

Bonjour1

... I would like to serialize everything except the top style attribute :

Bonjour1

How to choose which attributes to serialize when using new XMLSerializer().serializeToString()?

A: *

*deep clone the tree with node.cloneNode(true) and insert into a DocumentFragment

*use fragment.querySelectorAll("[style]") to find all elements that have the attribute you wish to remove

*remove attributes from matched elements

*serialize fragment

var blah = document.getElementById('blah');
var blah1 = document.getElementById('blah1');

blah1.style.top = "100px";

var frag = new DocumentFragment()
frag.appendChild(blah.cloneNode(true))

for(var e of frag.querySelectorAll("[style]")) {
   e.removeAttribute("style")
}

console.log(new XMLSerializer().serializeToString(frag))

Tested with Firefox 33


text:
Q: python pyqt5 progress bar indicator I have a script which reads data from a .xlsx file and put them in various DB tables. I would like to show the user the percentage of activity in progress. The processing time is variable and the user may get the feeling that something is wrong. I have read several articles in stackoverflow but they all had a definite time or quantity.
It should work inside pyqt5 enviroment.

A: tqdm is the package for you.
from tqdm import tqdm
from time import sleep

for i in tqdm(range(100)):
    sleep(0.2)

To install it, just run pip install tqdm in your active environment.


text:
Q: Añadir código en función.php para validar d.n.i con acf Necesito validar un campo de texto de acf con el d.n.i, tengo la función que sirve, pero fallo al ponerla en función.php para con los valores de acf, no se que estoy haciendo mal, este es mi código:
add_action('acf/render_field_settings/type=textarea', 'validar_dni');
function validar_dni($dni){
 $letra = substr($dni, -1);
    $numeros = substr($dni, 0, -1);
    if ( substr("TRWAGMYFPDXBNJZSQVHLCKE", $numeros%23, 1) == $letra && strlen($letra) == 1 && strlen ($numeros) == 8 ){
        echo 'valido';
    }else{
        echo 'no valido';
    }
}


text:
Q: Resoning on Terms if reused by refering to their URIs I want to reuse existing vocabulary. Instead of importing whole ontologies, I want to do it by referring to URIs of selected classes and properties in my ontology.
If ontologies are imported then axioms are also imported in my ontology, so reasoner obviously will take care of the imported axioms.
But if I reuse classes/properties by referring to their URIs then axioms are not imported in my ontology. So, My question is that  will the reasoner respect the rules applied on the referred terms?
====
Added Later
instead of copy past or OWL Import if terms are reused by referring to their URIs then axioms are not imported into target ontology.
But my question is that if internet is available then will the reasoner Fitch and respect axioms applied to that specific (reused) term.
for example, if I am reusing nfo:fileSize by referring to semanticdesktop.org/ontologies/2007/03/22/nfo/#fileSize , so if in case I am connected to internet then will reasoner go over internet to check for the axioms applied to nfo:filesSize?

A: The answer is no, reasoners are not expected to find out more axioms online if presented with the IRI of a class or property. They are meant to use all and only the axioms in the import closure of their ontology.
However, there are other ways of including only part of an ontology into a new ontology, for the purpose of reusing classes and properties with their original meaning. There are techniques such as modularisation and atomic decomposition that allow you to select a subset of the axioms of an ontology, e.g., all the axioms used in defining a specific class - which you can then copy over.


text:
Q: How to script: If value is this:xxx do this, BUT if value is this:yyyy then do this instead Looking for a how-to from the JavaScript gurus out there.
I'm not a developer, but mine is away for a while and I need to adapt a script. It is for handling specific email and is written if the email header contains THIS email address and the subject contains THIS INFORMATION or THIS information then grab this data from the email and make a ticket assigned to this group with this information...

if (headers.indexOf('####.####@yadayadablah.ca') > -1 &&
   (subject.indexOf('Test text: More test text') > -1 ||
   subject.indexOf('FW: Even more test text') > -1)) {

    // get user information
    var userFrom = '';
    var usr = new GlideRecord('sys_user');
    usr.addQuery('sys_id', email.from_sys_id);
    usr.query();
    if (usr.next()) {
        userFrom = ' from ' + usr.first_name + ' ' + usr.last_name;
    }

    // generate incident when phishing email is forwarded
    var inc = new GlideRecord('incident');
    inc.initialize();
    inc.caller_id = email.from_sys_id;
    inc.assignment_group = '2819caca1beb9c904b8c74ce0a4bcb33';
    inc.category = 'security'; // security 9441ce03db00d700dd0736ee9d96193a
    inc.subcategory = 'phishing';
    inc.contact_type = 'email';  // bbd7cb4bdbc73300dd0736ee9d961902 email
    inc.short_description = 'Suspected Phishing Attempt: ' + email.subject;
    inc.description = 'Email Body: '+ email.body_text;
    inc.insert();

    event.state = "stop_processing";

}

// email to send
/*
var gr = new GlideRecord('sys_email');
gr.initialize();
gr.type = 'send-ready';
gr.recipients = email.origemail;
gr.subject = 'Notification update: Insert app name here Update This Phishing
Test';
gr.body = '
ATTENTION: This
was just a test
' +
'
An Incident has been created with your reponse. You can view details at
' +
inc.number + '
';

gr.insert();
*/

What I need is to edit this so it does one thing if the header is the one group and it does another if the header is this other group...
I have no idea how to script that part, and this cannot wait until Monday when my Dev gets back.
Any and all suggestions are hugely appreciated.

A: I think you're looking for an if-else statement, this could look like this:
if(value == xxx){
doSomething();
}else if(value == yyy){
doSomethingElse();
}


text:
Q: Appending JavaScript to all pages in JIRA I'm trying to append two JavaScript files to all pages in JIRA, following this guide.
However, this only works on the Dashboard page when you login, not on other pages.
Does anyone have a clue why it does not work?

A: You can do that with a plugin:

*

*Define web resource module that will list your .js files you want included.

*Define servlet filter module and use URL pattern to specify which pages you'd like to intercept.

*In the servlet filter class, use web resource manager to require your web resource module: ComponentManager.getComponentInstanceOfType(WebResourceManager.class)
.requireResource("com.whatever.plugin:my-resource");

A: There is more easiest way to add javascript shared everywhere in jira.

*

*Open Jira Administration - System

*on the left side find USER INTERFACE section

*click Announcement Banner

or just simple push . (dot) and write Announcement Banner, push Enter button.


text:
Q: In eclipse I a getting the API level 20 .I want ot use lower versions of API How to change API level. when selecting this API level it shows no CPU/ABi available and also I am not able to add text fields it throws an exception.
Image 1Image 2

A: In Eclipse go to manifest.xml
<uses-sdk android:minSdkVersion="int" />

In android studio: go to your app Gradle there you can find the minSdkVersion. Lower it to the version you needed.
android {
    ....
    defaultConfig {
        ....
        minSdkVersion 17
        ....
    }

}

A: *

*Quick Fix: Uncheck installed checkbox to see other downloads and try to refresh android sdk manager, restart it or restart the computer. API 19 worked fine for me before I moved to android studio.

*I'm not sure if API 20 is supported in eclipse, I recommend Android Studio for android development. Anyway, if you have an old PC that does not meet android studio minimum requirement, download IntelliJ IDEA https://www.jetbrains.com/idea/, it's a bit lighter and free and require 1 GB of RAM (But 1 GB is very bad, you need at least 2 GB without running android emulator). However, if you still want to work with eclipse I think you need API 19 you have to download it manually from the web and move it to android SDK location. Or you can install android studio to download SDK without using it.

*Newer APIs are way better, they have more libraries that supports both old and new android versions. It's really worth upgrading to Android Studio.

*For the CPU/ABi error check this post Android 4.3 Virtual Device CPU/ABI - No system images installed (eclipse)


text:
Q: Is it possible to 'fork a fork' in Github? I am currently working on a project that is a spinoff (fork) from a framework I have been working on.
This project is intended to be pretty generic, but now I need to fork the codebase again for a client of mine.
At this moment, I have created a custom branch for my client, but I'd rather have a standalone repository for this.

*

*Is is possible to 'fork a fork'?

*If not, what alternatives do I have?
Outline of the situation:

*

*Framework repository (original)

*

*Generic application repository (fork)

*

*(not yet) Client repository (fork of application)

Note: when trying to  'fork a fork' in Github, you will receive a notification that you have already forked the project:

A: Simple answer: Yes and no.
No, for a single account as you are unable to create two repositories with the same name (and forks always have the same name).
Yes, for multiple accounts. So you could setup an organization for your second fork.

A:
This is now very possible. You just go to the fork you want to fork
  and click "fork" like you would always do. This only works if you
  don't have a different fork of that repository in your account
  already, though. If you do, you have to delete it.

Answered in a comment by iFreilicht
Since this is the correct answer now, it is better to highlight it.

A: I contacted GitHub support about this 'issue' and they confirmed this is not possible. Also, it is very unlikely that such a feature will be implemented in the future.

A: now,there is a drop-down arrow, you can chose base repository