text:
Q: Why does connection close automatically after 1 minute using Akka TCP? I'm writing an Interactive Broker API using Scala and Akka actors.
I have a Client actor that connects to the server and communicate with the IO manager to send requests and receive responses from TWS. The connection works fine and I'm able to send a request and get the response.
Then I receive automatically a PeerClosed message from the IO manager after 1 minute. I would like that the connection stays open unless I explicitly close it. I tried to set keepOpenOnPeerClosed = true but it changes nothing.
Here is the Actor:
class Client(remote: InetSocketAddress, clientId: Int, extraAuth: Boolean, onConnected: Session => Unit, listener: EWrapper) extends Actor {
    final val ClientVersion: Int = 63
    final val ServerVersion: Int = 38
    final val MinServerVerLinking: Int = 70

    import Tcp._
    import context.system

    IO(Tcp) ! Connect(remote)

    def receive = {

        case CommandFailed(_: Connect) =>
          print("connect failed")
          context stop self

        case c@Connected(remote, local) => {

          val connection = sender()
          connection ! Register(self, keepOpenOnPeerClosed = true)
          context become connected(connection,1)
          val clientVersionBytes = ByteString.fromArray(String.valueOf(ClientVersion).getBytes() ++ Array[Byte](0.toByte))
          println("Sending Client Version " + clientVersionBytes)
          sender() ! Write(clientVersionBytes)
       }
     }
      def connected(connection: ActorRef, serverVersion: Int): Receive = {
        case request: Request =>
          print("Send request " + request)
          connection ! Write(ByteString(request.toBytes(serverVersion)))
        case CommandFailed(w: Write) =>
          connection ! Close
          print("write failed")
        case Received(data) => {
          println(data)
          implicit val is = new DataInputStream(new ByteArrayInputStream(data.toArray))
          EventDispatcher.consumers.get(readInt()) match {
            case Some(consumer) => {
              consumer.consume(listener, serverVersion)
            }
            case None => {
              listener.error(EClientErrors.NoValidId, EClientErrors.UnknownId.code, EClientErrors.UnknownId.msg)
            }
          }
        }
        case _ : ConnectionClosed => context stop self
      }

I don't have the same behaviour if I connect using IBJts API (using a standard Java Socket)

A: Have you tried it with the keep alive option?
sender ! Tcp.SO.KeepAlive(on = true)


text:
Q: Why this loop become infinite loop in C? Here in this code, I am using unsigned int and want to terminate my loop as soon as it reaches '0'. But this never happens it passes '0'
#include <stdio.h>
typedef unsigned int uint32_t ;

delay (uint32_t x){
    uint32_t y = 0;
    for(y=x; y>= 0; y--){
         printf("Display number %d\n", y);
    }
}

int main()
{
    uint32_t times = 10;

    printf("Hello World!\n");
    delay(10);
    return 0;
}

Output:
Hello World!
Display number 10
Display number 9
Display number 8
Display number 7
Display number 6
Display number 5
Display number 4
Display number 3
Display number 2
Display number 1
Display number 0
Display number -1
Display number -2
Display number -3
Display number -4
Display number -5
Display number -6

Link: For code from: code.hackerearth.com

A: An unsigned number will always be bigger or equal 0.
Your compiler should warn you about this error.
The reason why you are seeing negative numbers in the output is that you are printing the unsigned number using %d.

A: Consider for(y=x; y>= 0; y--){ y can never be below 0 since it's an unsigned type. Once y is 0, y-- will wrap around to std::numeric_limits<uint32_t>::max(). So the for loop never terminates.
The fact that printf is displaying negatives is a manifestation of the undefined behaviour on your using an incorrect format specifier for an unsigned type.

A: An unsigned number will always be bigger or equal 0.
Change this
delay (uint32_t x){
    uint32_t y = 0;
    for(y=x; y>= 0; y--){
         printf("Display number %d\n", y);
    }
}

with
delay (uint32_t x){
    int y = 0;
    for(y=(int)x; y>= 0; y--){
         printf("Display number %d\n", y);
    }
}

A: y is unsigned, therefore it will never be negative. You can either define it as int
int y = 0;

or modify your for to a do while
y = x;
do {
     printf("Display number %d\n", y);
} while (--y >= 0);

redpajama_set_name: RedPajamaStackExchange


text:
Q: C Program to find the number of denominations for a given amount now I'am nearly finished with my program but I need a little help because the math is not right.
Since I'am linking to menge with euro i thought the script will use 414. But it's somehow using an other number.
I'am still a little bit confused with xyz.c files and header.h files. Should I put data entries into the .h file and functions into .c file. How should I use them correctly.
int main()
{
    double euro, ats, sum;
    // Eingabe euro
    printf("Input: ");
    scanf("%lf", &euro);

    ats = 13.760;  //fixierter Wert für die Umrechnung
    // Umrechung Euro mal ats
    sum = euro * ats;
    printf("Ausgabe:\n");
    printf("%.0f Euro entspricht ca. %.0f Schilling\n", euro, sum);

    //Textausgabe mit Geldnoten
    int menge, geldnoten;
    menge = euro;
    // Stueckelung Noten
    int stueckelung[SIZE] = {200,100,50,20,10,5,2,1};

    for (int i = 0; i < SIZE; i++)
    {
        geldnoten = menge / stueckelung[i];

        if(geldnoten)
        {
            geldnoten = menge % stueckelung[i]; //uebriges Geld

            printf("%d + %d = %d \n", geldnoten, stueckelung[i],
                geldnoten * stueckelung[i]);
        }
    }

    return 0;
}

Output:
Input: 414
Ausgabe:
414 Euro entspricht ca. 5697 Schilling
14 + 200 = 2800
14 + 100 = 1400
14 + 50 = 700
14 + 20 = 280
4 + 10 = 40
4 + 5 = 20
0 + 2 = 0
0 + 1 = 0

The goal of the output is this sentence:
In Geldscheinen und Münzen: 2 Scheine mit Wert 200, 1 Schien mit Wert 10 and 2 Münzen mit Wert 2
The translation would be: In banknotes and coins: 2 notes 200, 1 note of 10 and 2 coins of 2.
I'am struggling here with the printf command how should I do this?

A: If I understand the problem correctly, you need to reduce menge with geldnoten * stueckelung[i] (the product of the number of notes , geldnoten, and the value of each note, stueckelung[i]) in each iteration of the loop:
    for (int i = 0; i < SIZE; i++)
    {
        geldnoten = menge / stueckelung[i];

        if(geldnoten)
        {
            // geldnoten = menge % stueckelung[i]; // not this
            menge -= geldnoten * stueckelung[i];   // this instead

            printf("%d * %d = %d\n", geldnoten, stueckelung[i],
                geldnoten * stueckelung[i]);
        }
    }

With the input 414, the above would produce this output:
Input: 414
Ausgabe:
414 Euro entspricht ca. 5697 Schilling
2 * 200 = 400
1 * 10 = 10
2 * 2 = 4


text:
Q: How do I gather data from other websites for an app? I'm trying to build a news hub app, and my objective is to extract news articles from other news channels, summarize it, and present in the form of bullets in an unbiased manner.
I've got the algorithm up and running, all I need is the code to gather data from other websites like NDTV, CNN, etc.
Please gimme a description of how to carry this out.
Code, links, examples, and screen shots would help a lot.
Thanks! (Y)

A: webscraping is the way for you;
you can get  your news articles or everything you need with scrapy , beautifulsoup or selenium they are modules for python for getting data from html pages( text ) and after that you are able to save your data to anywhere you want such as databases ;
it's better to use rss pages for headlines and these things that you consider to get.

A: There is a php lib called QueryList(http://git.oschina.net/jae/QueryList), it use phpQuery internally, and use some css selector filter array to fetch the specific content in certain url.
the doc is in Chinese(I don't think there is a English version), but it's quite simple to use:
<?php
// include the lib
require_once('QueryList.class.php');

// url to fetch content
$url = 'http://www.example.com/index.html';

// filter rules using css selector grammar
$regArr = array(
    'time' => array('td:nth-child(2)', 'text'),
    'summary' => array('td:nth-child(3) td:nth-child(3)', 'text'),
    'imgSrc' => array('h1 > a > img', 'src')
    );

// optional, firstly find `.divbox > table`, then find the things defined by $regArr in each `.divbox > table`
$regRange = '.divbox > table';

// do the query
$result = QueryList::Query($url, $regArr, $regRange);

// the result will be an array like:
/** Array
 * (
 *    [0] => Array
 *    (
 *        'time' => ,
 *        'summary' => ,
 *        'imgSrc' =>
 *    )
 *    [1] => Array
 *    (
 *        'time' => ,
 *        'summary' => ,
 *        'imgSrc' =>
 *    )
 *    ...
 * )
 */
echo '<pre>';
print_r($result->jsonArr);
echo '</pre>';

you can also define a exclude pattern and a callback function in $regArr, I think this will meet your requirment.


text:
Q: How to get access token from Single Sign On portal for multiple sites We are building several websites/products, if a user has an account on one site they will also be allowed access to all other sites.
Let's say we have the following setup:
Clients

*

*site1.com

*site2.com

Single Sign On Portal

*

*sso.company.com

APIs

*

*api1.company.com

*api2.company.com

The Single Sign On Portal supports multiple OAuth providers, such as Google, Microsoft, Facebook, etc and this is all working great built on top of the default ASP.NET Web Forms template in VS 2015 using OWIN and Idenity.
The SSO site is logging the user in an using a cookie for authentication, which works fine while still on the SSO site. Now we need to return a token that the client site can use to know that the user is authenticated
Now the challange here is how do we exchange the cookie to a token that we can return to the client(s) to use in the Authorization header in request sent to our APIs?
Should we generate a token our selves or is there some built in functionality we can use for this purpose?

A: I've seen most people generate a token themselves and then multiple accounts can be linked to that same user in your account (i.e. a user could log into both FB and Google). Most of the SSO providers have a way to get an identity token or one time use code for your server to use and get user info like FacebookId. The key is ensuring that identity token came from FB and not a third party.
Auth0 is a pretty good service if you want a managed route. Even if you don't use them, they have a lot of good resources on oauth. (I have no affiliation with them other than that we used them before.) we also have a little more info on auth: https://www.moesif.com/blog/technical/restful-apis/Authorization-on-RESTful-APIs/


text:
Q: rails 4 simple form association translation lookup (i18n) here's something that has annoyed me for some time, and I couldn't find a solution yet.
Suppose I have a form with
f.association :driver

,then I expect Simple Form to look this up in de.yml under:
de:
  activerecord:
    models:
      driver: Fahrer

but it doesn't. I could copy this key to
de:
  activerecord:
    attributes:
      bus:
        driver: Fahrer

but that's not DRY...
help?


text:
Q: Android query SQLIte syntax error I receive data from an Activity in which I create a SQL query, but I'm getting syntax error in string. Thanks for help
String sql = "SELECT _Id,Date,cas,N,E,Altro FROM Ge WHERE Ea>0 AND cas LIKE "+c_ricevuta+" AND date LIKE '"+anno_ricevuto+"-%' ORDER BY data DESC";

here syntax error: cas LIKE "+c_ricevuta+"

A: c_ricevuta should likely be in single quotes '':
String sql = "SELECT _Id,Date,cas,N,E,Altro FROM Ge WHERE Ea>0 AND cas LIKE '"+c_ricevuta+"' AND date LIKE '"+anno_ricevuto+"-%' ORDER BY data DESC";

Note that using string params in your query like this is prone to both syntax errors and SQL injection. Have a look at ? literal placeholders instead, e.g. the selectionArgs in query functions.

A: just in case, I'd place spaces between the word and the "+". Plus, you're not using quotes to surround c_ricevuta


text:
Q: Why are my services not registering with Jaeger? I have deployed two services in kubernetes (bare-metal k0s. To do some tracing on Jaeger Service A makes a call to Service B for a JWT authentication token - this works perfectly when I test in Visual Studio (Service A is able to retrieve token from Service B).
However when I execute the call in Postman now that I have deployed to k0S , I cannot see neither the services or any traces Jaeger UI :

Using guide from here I have configured the services as below :
Service A (Startup.cs)
public class Startup
{
    private readonly IWebHostEnvironment _environment;
    public Startup(IConfiguration configuration, IWebHostEnvironment environment)
    {
        Configuration = configuration;
        _environment = environment;
    }
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddDbContext<ModelContext>(o => o.UseOracle(Configuration.GetConnectionString("OracleConn")));
        services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
        });
        services.AddTransient<IAsyncAccountService<SttmCustAccount>, AccountService>();
        services.AddTransient<IAsyncLookupResponse, LookupService>();
        services.AddOpenTracing();
        services.AddSingleton<ITracer>(cli =>
        {
            var serviceName = cli.GetRequiredService<IWebHostEnvironment>().ApplicationName;
            Environment.SetEnvironmentVariable("JAEGER_SERVICE_NAME", serviceName);

            if (_environment.IsDevelopment())
            {
                Environment.SetEnvironmentVariable("JAEGER_AGENT_HOST", "localhost");
                Environment.SetEnvironmentVariable("JAEGER_AGENT_PORT", "6831");
                Environment.SetEnvironmentVariable("JAEGER_SAMPLER_TYPE", "const");
            }
            ILoggerFactory loggerFactory = cli.GetRequiredService<ILoggerFactory>();

            ISampler sampler = new ConstSampler(sample: true);

            ITracer tracer = new Tracer.Builder(serviceName)
                .WithLoggerFactory(loggerFactory)
                .WithSampler(sampler)
                .Build();

            GlobalTracer.Register(tracer);
            return tracer;
        });

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Service B has the exact same configuration.
Jaeger operator is set up using NodePort with config as in this file :
[file][https://drive.google.com/file/d/1nAjQ2jHrLSZLWoV9vGb3l4b0M1_yTMTw/view?usp=sharing]
I have to tried to expose the operator as Traefik Ingress but failed and had to change to NodePort (Can this affect registering of services , if at all ?) :
This is the call in Service A that retrieves token from Service B :
    [HttpGet]
        public async Task<IActionResult> GetAccountAsync([FromQuery] AccountLookupRequest request)
        {
             string authenticationResponse = await GetTokenAsync();
            if (authenticationResponse != null)
            {
                _logger.LogInformation("Called AccountLookup API");
                List<AccountLookupResponse> res = new List<AccountLookupResponse>();
                var tranRef = String.Format("{1}{2}{0}", Helpers.aa, Helpers.bb, DateTime.Now.ToString("yyMMddHHmmss"));

...
}
}

 static  async Task<string> GetTokenAsync()
    {
        var payload = "{\"Username\": \"golide\",\"Password\": \"It@XXXXX\"}";
        Uri uri = new Uri("http://10.XXX.XXX.XXX:31306/users/authenticate");
        HttpContent c = new StringContent(payload, Encoding.UTF8, "application/json");
        AuthenticationResponse responseEntity = new AuthenticationResponse();
        var response = string.Empty;
        using (var client = new HttpClient())
        {
            HttpResponseMessage result = await client.PostAsync(uri, c);
            if (result.IsSuccessStatusCode)
            {
                response = result.StatusCode.ToString();
               // responseEntity = JsonConvert.DeserializeObject<AuthenticationResponse>(response);
            }
        }
        return response;
    }

In Postman context the call to http://10.170.XXX.XXX:30488/account?field4=3025202645050&field7=GENERIC01&field10=ABC076 will implicitly invoke the AuthenticationAPI at http://10.170.xxx.xxx:31306/users/authenticate
UPDATE
Container logs show that trace-id and span-id are being generated :
[02:54:03 INF] Executed action method

FlexToEcocash.Controllers.AccountController.GetAccountAsync (FlexToEcocash), returned result Microsoft.AspNetCore.Mvc.OkObjectResult in 416.2876ms.
[02:54:03 WRN] Event-Exception: Microsoft.AspNetCore.Mvc.BeforeActionResult
System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Object.GetType()
   at OpenTracing.Contrib.NetCore.AspNetCore.MvcEventProcessor.ProcessEvent(String eventName, Object arg)
   at OpenTracing.Contrib.NetCore.AspNetCore.AspNetCoreDiagnostics.OnNext(String eventName, Object untypedArg)
   at OpenTracing.Contrib.NetCore.Internal.DiagnosticListenerObserver.System.IObserver<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.OnNext(KeyValuePair`2 value)
[02:54:03 INF] Executing ObjectResult, writing value of type 'FlexToEcocash.Models.ResponseModels.AccountLookupResponse'.
[02:54:03 INF] Executed action FlexToEcocash.Controllers.AccountController.GetAccountAsync (FlexToEcocash) in 421.8383ms
[02:54:03 WRN] Span has already been finished; will not be reported again. Operation: HTTP GET Trace Id: c976e25bf21bfae5 Span Id: c976e25bf21bfae5
[02:54:03 INF] Executed endpoint 'FlexToEcocash.Controllers.AccountController.GetAccountAsync (FlexToEcocash)'
[02:54:03 INF] Request finished in 426.0567ms 200 application/json; charset=utf-8
[02:54:03 WRN] Span has already been finished; will not be reported again. Operation: HTTP GET Trace Id: c976e25bf21bfae5 Span Id: c976e25bf21bfae5

What am I missing ?


text:
Q: No headphone signal after installing Ubuntu 14.04 Regarding Ubuntu 14.04
Using laptop and internal speakers are working properly.
Sound card is detected.
When plugging in powered desktop computer speakers to headphone output there is no sound.
Nothing is muted, all volume is up.
Sound Settings automatically set to "play sound through headphones" when I plug speakers into headphone output.
I have purged/reinstalled Pulse Audio
I have purged/reinstalled ALSA.
Still, only internal speakers working properly.
When I boot up windows instead of Ubuntu, everything works fine again.
How can I track down this problem?

A: I had the same problem for days, and the solution was to do the following two things:

*

*Reset user configuration (as described in the Troubleshooting section of https://wiki.ubuntu.com/PulseAudio), but I guess you already did it when you purged pulseaudio;

*Make sure Independent HP is Disabled in alsamixer. To do that, just type alsamixer in a terminal, then choose your sound card (by pressing F6) and move to the Independent HP column.
Hope it helps!


text:
Q: C# VSTO - dynamically set RibbonControl I have a customized Ribbon in Word. The Ribbon has one comboBox: comboBox_recentConditions which was defined using the Designer - so it's initalized and is empty at load. Now, I would like to dynamically set this comboBox each time the Application_WindowActivate event is fired.
Each Word document has its own instance of class called RibbonControls:
class RibbonControls
{
    private RibbonComboBox recentConditionComboBox;

    public RibbonControls()
    {
        this.recentConditionComboBox = new RibbonComboBox();
    }

    public RibbonComboBox RecentConditionComboBox
    {
        get
        {
            return recentConditionComboBox;
        }
        set
        {
            recentConditionComboBox = value;
        }
    }
}

Now in Application_WindowActivate event i do the following:
    static void Application_WindowActivate(Document doc, Window Wn)
    {
        Globals.Ribbons.SourceRibbon.comboBox_recentConditions = WordGate.docRibbonControls.RecentConditionComboBox;
    }

The problem is that the Ribbon comboBox control doesn't changes, it's always empty, even after Application_WindowActivate is called.
I tested at run-time to see if each document indeed has its own comboBox with its items - which seems to work.
What am I missing?
To clear my question:
Let's say I have 3 items in the comboBox.Items. When clicking on it I see nothing, but if I add this:
MessageBox.Show(Globals.Ribbons.SourceRibbon.comboBox_recentConditions.Items.Count.ToString());

at the end of Application_WindowActivate it will print the number 3.
Thanks.

A: You cant do it that way. Please have a read on Ribbon callbacks
You have to use the getItemLabel event which will add items to combo box. If you want to load the combobox during WindowActivate then call Ribbon.Invalidate or Ribbon.InvalidateControl which will call all relevant ribbon callbacks.


text:
Q: JSBin: How to create demo example's of sapui5? I want share working live example of SAPUI5 on stackoverflow, but I don't know how to create the JSBin example or which things we have to add or is there any simple way to create demo example of JSBin.

A: Or, you can create a Stack Snippet which is runnable by clicking the blue 'Run Code Snippet' button:

sap.ui.controller("view1.initial", {
onInit : function(oEvent) {
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({
        rows : [
            { value : "sap-icon://syringe",    col2 : "Value 2",  col3 : "Value 3",  ol4 : "Value 4" },
            { value : "sap-icon://account",    col2 : "Value 10", col3 : "Value 11", col4 : "Value 12" },
            { value : "sap-icon://chalkboard", col2 : "Value 14", col3 : "Value 15", col4 : "Value 16" },
            { value : "sap-icon://e-care",     col2 : "Value 18", col3 : "Value 19", col4 : "Value 20" }
        ]
    });

    this.getView().setModel(oModel);
}
});

sap.ui.xmlview("main", {
viewContent: jQuery("#view1").html()
})
.placeAt("uiArea");
/* extra CSS classes here */

A: You will need bootstrap script, View which will be in HTML tab only and its Controller under Javascript tab.
You can save this as your template after logging in and use it as starting point for your expamples.


text:
Q: How do I verify that an interface VPC endpoint is functioning well? I am pretty new to AWS, and here is my scenario:
I create a sagemaker endpoint that can be called with AWS SDK IAmazonSageMakerRuntime::InvokeEndpointAsync() from a EC2 web server in a private subnet over public internet via NAT instance.
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(mydata)))
{
   InvokeEndpointRequest req = new InvokeEndpointRequest()
   {
      EndpointName = "MyEndpoint",
      ContentType = "application/json",
      Body = ms
   };
   var resp = await _sageMakerRuntime.InvokeEndpointAsync(req);
}

And to further secure the connection and avoid traffic over public internet, I set up a interface VPC endpoint(the associated security group inbound rule allows the cidr ip range in my VPC with port 80/443) for SageMakerRuntime service to take advantage of the benefits from using AWS PrivteConnection.
EndpointSageMakerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
  GroupDescription: Enable access from app to interface VPC endpoint for sagemaker runtime
  VpcId: !Ref VPC
  SecurityGroupIngress:
  - CidrIp: 10.50.0.0/16
    IpProtocol: tcp
    ToPort: 80
    FromPort: 80
  - CidrIp: 10.50.0.0/16
    IpProtocol: tcp
    ToPort: 443
    FromPort: 443
  Tags:
  - Key: Name
    Value: !Sub "${AWS::StackName}-EndpointSageMakerSecurityGroup"

EndpointSageMakerRuntime:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal: '*'
            Action:
              - sagemaker:InvokeEndpoint
            Resource: !Sub arn:${AWS::Partition}:sagemaker:${AWS::Region}:${AWS::AccountId}:endpoint/MyEndpoint
      SubnetIds: !Ref PrivateSubnets
      SecurityGroupIds:
      - !Ref EndpointSageMakerSecurityGroup
      ServiceName: !Sub com.amazonaws.${AWS::Region}.sagemaker.runtime #runtime.sagemaker.${AWS::Region}.amazonaws.com
      PrivateDnsEnabled: true
      VpcEndpointType: Interface
      VpcId: !Ref VPC

However, I really have no idea whether the interface VPC endpoint does take effect and my function call InvokeEndpointAsync() indeed calls to the interface VPC endpoint into AWS SageMakerRuntime service. I tried creating a notification in the interface VPC endpoint to publish message to a SNS topic and subscribing that SNS topic with my email, but I was not able to get any email from it. I guess there is something wrong but can't not figure out how to get the interface VPC endpoint right. Any ideas would be appreciated.


text:
Q: ant Design Carousel: how to access the goto(), next(), & prev() methods We're using ant Design in our project and I'm trying to use their Carousel component. The documentation shows methods goto(), next(), prev() but I am unable to access these methods. The way we've done this with other antD components would be to:
const { goto, next, prev } = Carousel;

once you've imported Carousel, but this doesn't work -- those methods are all undefined. These methods were exposed in this 2017 pull request (although the original pull request references previous() instead of prev()) but I see no way to access them. This PR also mentioned that the purpose of the PR was to make the methods available without having to useRefs, which is what all the SO examples seem to show are class-based solutions, not Hooks as we are using.
What am I missing here?

A: You can create a ref and pass it to the carousel and from that you can access the carousel methods.

 const carouselRef = React.createRef();

 <Carousel dotPosition={dotPosition} ref={carouselRef}>
 <Button  onClick={() => {
       carouselRef.current.next();
     }}
 >
            goto next
          </Button>
  <Button
            onClick={() => {
              carouselRef.current.prev();
            }}
          >
            goto prev
          </Button>
</Carousel>

A: if you want to use the Carousel's methods,you shoule get the instance of Carousel Component.
like this:
codesandbox


text:
Q: Laptop "thinks" it's overheating, shuts down itself Short version: When I turn on the laptop fans go full speed even though the the laptop is ice cold. After about 20 seconds it shuts down itself which I guess it's "thinking" CPU is overheating.
Long version: Recently I had an overheating issue with it, I thought open it up and clean the fan. I knew the problem was with the fan because I did not do any heavy tasks with this laptop which would need a lot of resources to compute and the fan didn't seem to push any air out from the air vents.
Now this is not my first time opening my laptop so it wasn't hard, I follow the disassembly video just to make sure I would not forget anything. I open it open clear the dusts stuck in the fan which was a lot. The vents were completely clear. I assembled the laptop again, turned it on, it was on for a couple of minutes and then it shuts down. The problem seemed to be the battery since it only lasts for 5 minutes. I connected the charger and turned it on again. In the middle of boot up it shuts down. The strange thing is fans are working full speed the whole time even though it's cold.
I am pretty sure I have connected everything. But of course there's something I have missed which causes this problem. I did not disassemble the heatsink from CPU. I only opened the fan.
What could be the problem

A: I opened up the laptop again. Problem was that the I had loosened up one of the four screws that connect heatsink to the CPU and forgot to tighten it up. This caused the fan go crazy and the CPU shut itself down in order to prevent overheating.


text:
Q: Firestore insert object field I want to save a value inside a field in firestore, like this image.

As you can see in the picture, I want shopId to be dynamic, then it will contain date and time fields with a boolean value.
My objective is to track a user's Checkin history on different shops. Hope you understand what i'm saying here.
now this is my current code:
checkInShop() {
  let currentUser = firebase.auth().currentUser;
  if (currentUser) {
    const db = firebase.firestore();
    const batch = db.batch();
    const docRef = db.collection("userCheckInHistory").doc(currentUser.uid);
    const timestamp = firebase.firestore.FieldValue.serverTimestamp();
    batch.set(docRef, {
      `${this.state.shopId}`: {
        `${timestamp}`: true
      }
    });
    // Commit the batch
    batch.commit().then(function() {
      AlertIOS.alert(`ShopId: Sent!`);
    });
  }
};

Is this possible to firestore?

A: you can do:
docRef.set({ [this.state.shopId]: { [timestamp]: true } });

you probably want to set merge to true in this case as well:
docRef.set({ [this.state.shopId]: { [timestamp]: true } }, { merge: true });

if you have to use template literals:
docRef.set(
  { [`${this.state.shopId}`]: { [`${timestamp}`]: true } },
  { merge: true }
);


text:
Q: What causes a Hadoop datanode to die? I have been running a Hadoop 2.3.0 cluster and I have been noticing on the status page (:50070/dfshealth.html) shows data nodes that have died which happens every couple of days. After noticing a datanode failure, I restart the process with the command:
/usr/local/hadoop/sbin/hadoop-daemon.sh stop datanode && /usr/local/hadoop/sbin/yarn-daemon.sh stop nodemanager && /usr/local/hadoop/sbin/hadoop-daemon.sh start datanode && /usr/local/hadoop/sbin/yarn-daemon.sh start nodemanager

and everything keeps on going.
What can cause a datanode to die? Are there are good tools to diagnose past failures?

A: The above exception (java.net.BindException: Problem binding to [0.0.0.0:50010]) indicates that there's another instance of our datanode is running, Since you have started datanode using hadoop-daemon.sh start datanode. Data node process is running fine still it is not able to effectively communicate with namenode.
Stop and start namenode and datanode daemons in debug mode, following command can be used.
On Namenode host, Execute the following command
/usr/local/hadoop/sbin/hadoop-daemon.sh stop namenode ; hadoop namenode

On datanode host, Execute the following command
/usr/local/hadoop/sbin/hadoop-daemon.sh stop datanode ; hadoop datanode

Check the logs messages from both daemons.


text:
Q: Style apex:inputText as required within apex:pageBlockSectionItem I have a number of fields that I'm binding to within a pageBlockSection. In most cases I can use an inputField to get the standard Salesforce presentation.
However, one of the required fields I want to bind to isn't an SObject field. It is a property defined on an inner class of the controller.
Basic Visualforce
<apex:pageBlock id="dropBlock" mode="edit">
     <apex:pageBlockSection title="Elements" columns="1" showHeader="false">

         <apex:pageBlockSectionItem >
             <apex:outputLabel value="Required String Property" />
             <apex:inputText value="{!innerClassInstance.innerClassField}" required="true"/>
         </apex:pageBlockSectionItem>
     </apex:pageBlockSection>
</apex:pageBlock>

Attempting to use an inputField for the default rendering results in the error message:

Save error: Could not resolve the entity from  value
  binding '{!innerClassInstance.innerClassField}'.   can only be used with
  SObject fields.

If I take the inputText field out of the pageBlockSectionItem and pageBlockSection I can fake it by using a couple of divs and the Salesforce styles, but then it is no longer aligned with the other fields in the pageBlockSection.

    <apex:inputText value="{!innerClassInstance.innerClassField}" required="true"/>

I can't put the extra divs in the pageBlockSectionItem as I get the error:

Save error:  may have no more than 2 child components

How can I add the default Salesforce required mark to an inputText within a pageBlockSectionItem?
I did see the related question Visualforce markup used to display a required password field, with field type "password". The issue is very similar, and the like to the discussion boards is useful. This question differs slightly as I specifically want to work within a pageBlockSectionItem for presentation reasons.

A: While writing out the question I came up with one possible solution. Just enclose the inputField and the additional divs in an outputPanel.
Hopefully it helps someone else who has this requirement.
<apex:pageBlock id="dropBlock" mode="edit">
    <apex:pageBlockSection title="Elements" columns="1" showHeader="false">

        <apex:pageBlockSectionItem >
            <apex:outputLabel value="Required String Property" />
            <apex:outputPanel layout="block" styleClass="requiredInput">

                    <apex:inputText value="{!innerClassInstance.innerClassField}" required="true"/>
            </apex:outputPanel>
        </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
</apex:pageBlock>


text:
Q: Display data as Tree angular I am trying to display the people data as a tree with a filter following "select fields: area", does angular give a possibility to display the data in this form  ? and how can I do it?
I have data in this structure
public rowData = [
{
  area : area A',
  Persons: [
    { person:  'person 1', position :'lvl 1' , sup: '' } ,
    { person:  'person 2', position :'lvl 2' , sup :'person 1' },
    { person:  'person 3', position :'lvl 2' , sup :'person 1'  } ,
    { person:  'person 4', position :'lvl 3' , sup :'person 3'} ,
    { person:  'person 5', position :'lvl 3' , sup :'person 4'} ,
    { person:  'person 6', position :'lvl 3' , sup :'person 5'} ,
    { person:  'person 7', position :'lvl 4' , sup :'person 6'}

},
{
  area : area B',
  Persons: [
    { person:  'person 21', position :'lvl 1' , sup :''} ,
    { person:  'person 22', position :'lvl 2' , sup :'person 1'},
    { person:  'person 23', position :'lvl 2' , sup :'person 1'} ,
    { person:  'person 24', position :'lvl 3' , sup :'person 2'} ,
    { person:  'person 25', position :'lvl 3' , sup :'person 2'} ,

},
  ]

A: I'm working on create a TreeView Graphic in pure Angular.  To not "re-invent the wheel" I copied the code from this old CodeProject article
I put the code in this stackblitz
It's hard (and too large) explain all the code, futhermore I need to do some cleanup because there are functions that are not implemented
Usage
Basically you need to copy the tree-view.component.ts and the econode.ts. Works simply using

    <tree-view #treeView [data]="data" [template]="treeTemplate">
    </tree-view>
    <ng-template #treeTemplate let-node>
      {{node.data.id}}
    </ng-template>

Where data is a typical object with children. The nodes are of type IECONode
in the way
    export interface IECONode
    {
      data:any;
      linkColor?:string;
      background?:string;
      color?:string;
      width?:number;
      height?:number;
      children?:IECONode[];
    }

And the properties are inherited from the parent elements

*

*NOTE: As I update the code, I'll update this post *

Update 1
I improved the component adding three functions:

*

*getChildren

*getParent

*getSlibingNodes
Futhermore, I got out the div element. the template is more complex but allows usage of (click) or (mouseover) to select one node or its parent/children.
Only the "nodes" are "colored" if they are selected, and only the "lines" are "colored" if go to a node selected.
This allow, e.g. select the nodes in a mouse over (or in a click)
    <ng-template #treeTemplate let-node>
      <div class="item" (mouseover)="selectSlibingNodes(treeView,node)"
            [ngStyle]="node.isSelected?{'background-color':node.bc,color:node.c}:null">
      {{node.data.id}}
      </div>
    </ng-template>

The function selectSlibingNodes like:
      selectSlibingNodes(treeView: TreeViewComponent, node: ECONode) {
        if (node==this.nodeSelected) {
          this.nodeSelected=null;
          treeView.nodes.forEach(x => {
            x.isSelected = false;
          });
        } else {
          this.nodeSelected=node;
          const nodes = treeView.getSlibingNodes(node).map(x => x.id);
          treeView.nodes.forEach(x => {
            x.isSelected = x.id == node.id || nodes.indexOf(x.id) >= 0;
          });
        }
      }

I made a new stackblitz with the changes

A: you can use angular2-tree-diagram package
angular2-tree-diagram


text:
Q: Given $K(\alpha)/K$ and $K(\beta)/K$ abelian extensions, prove that $K(\alpha + \beta)/K$ is an abelian extension.
Problem:
Let $K(\alpha)/K$ and $K(\beta)/K$ algebraic field extensions so that their respective Galois groups are abelian.
Prove that the Galois group of the field extension $K(\alpha + \beta)/K$ is also abelian.

My attempt:
I've tried considering the towers
$$K(\alpha,\beta)/K(\alpha)/K \qquad K(\alpha,\beta)/K(\beta)/K$$
Are somehow related to
$$K(\alpha,\beta)/K(\alpha+\beta)/K \qquad K(\alpha,\beta)/K(\alpha - \beta)/K$$
But I don't know how to relate this to the fact that the quotient is abelian or whether this statement is true or not.

A: $K(\alpha, \beta)$ is Galois over $K$ and the corresponding Galois group is a subgroup of $\text{Gal}(K(\alpha)/K)\times \text{Gal}(K(\beta)/K)$. So $K(\alpha, \beta)/K$ is abelian. Thus, any intermediate Galois extension must be abelian since the corresponding Galois group would be a quotient of $\text{Gal}(K(\alpha,\beta)/K)$


text:
Q: How to tell what co-ordinate system a WFS server is giving? I got a GML file from an ArcGIS-based WFS server and converted it to GeoJSON using Ogre (online ogr2ogr), but then got very strange results from that GeoJSON file.
Here's the link to the getCapabilities page of the WFS server:

http://sedsh127.sedsh.gov.uk/arcgis/services/ScotGov/HumanHealthSafety/MapServer/WFSServer?request=GetCapabilities&service=WFS

...which seems to be saying that it's latitue / longitude unless I'm reading it wrong:
<ows:ExtendedCapabilities>
 <ows:Constraint name="serviceAxisOrderForSwappableSRS">
  <ows:Value>latitude,longitude</ows:Value>
 </ows:Constraint>
</ows:ExtendedCapabilities>

...but the actual data doesn't look like latitude and longitude. Here's a sample from the start of the GML/XML file, the six-figure numbers aren't what I was expecting, and there's something I don't understand about an envelope:
<wfs:FeatureCollection previous='-1' next='-1' numberMatched='-1' numberReturned='-1' xsi:schemaLocation='http://sedsh127.sedsh.gov.uk/arcgis/services/ScotGov/ScotGov_HumanHealthSafety/MapServer/WFSServer http://sedsh127.sedsh.gov.uk/arcgis/services/ScotGov/HumanHealthSafety/MapServer/WFSServer?request=DescribeFeatureType%26version=2.0.0%26typename=NHS_Health_Boards__2014_ http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd http://www.opengis.net/gml/3.2 http://schemas.opengis.net/gml/3.2.1/gml.xsd' xmlns:HHS='http://sedsh127.sedsh.gov.uk/arcgis/services/ScotGov/ScotGov_HumanHealthSafety/MapServer/WFSServer' xmlns:gml='http://www.opengis.net/gml/3.2' xmlns:wfs='http://www.opengis.net/wfs/2.0' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><gml:boundedBy><gml:Envelope srsName='urn:ogc:def:crs:EPSG:6.9:27700'><gml:lowerCorner>5513 530249</gml:lowerCorner><gml:upperCorner>470332 1220301.5</gml:upperCorner></gml:Envelope></gml:boundedBy><gml:member><HHS:NHS_Health_Boards__2014_ gml:id='F1378__1'><HHS:OBJECTID>1</HHS:OBJECTID><HHS:HBCode>S08000015</HHS:HBCode><HHS:HBName>Ayrshire and Arran</HHS:HBName><HHS:Shape><gml:MultiSurface srsName="urn:ogc:def:crs:EPSG:6.9:27700"><gml:surfaceMember><gml:Polygon><gml:exterior><gml:LinearRing><gml:posList> 225054.5 669796 225053.5 669806.5 225041.5 669820.5 225036 669831 225037 669835 225049 669845.5 225052 669856 225052 669859.5 225045.5 669875.5 225042 669897.5 225037.5 669912 225036 669930 225048 669961 225048.70000000019 670000 225048.79999999981 670000.09999999963 225048 670008.5 225039 670027 225017.5 670036.5 225016 670040.5 225016 670047 225019.5 670056 225023 670076 225036 670120 225033.5 670131.5 225023 670152.5 225000 670148.5 224975 670139.5 224835.5 670136.5 224517 670000.09999999963 224516.90000000037 670000 224205 669872.5 224098.5 669645 224095 669634 224091.5 669631 224080 669626 224076 669619.5 224076.5 669614 224074.5 669607.5 224069.5 669602.5 224055.5 669595.5 224052.5 669584.5 224042 669576.5 224034.5 669575 224024.5 669578.5 224019.5 669578.5 224009.5 669576 223998.5 669560.5 223990.5 669554 223975.5 669546.5 223964.5 669543.5 223949 669545

Here's what it says about projections, and I didn't define any projections when extracting or converting the data. I may have misunderstood this, but my understanding is that if co-ordinates are lat/long they'd be independent of projections and projections would only matter when they're rendered?
<DefaultCRS>urn:ogc:def:crs:EPSG:6.9:27700</DefaultCRS>
<OtherSRS>urn:ogc:def:crs:EPSG:6.9:4326</OtherSRS>

I also don't recognise EPSG:6.9:27700, searching on it suggests it's something only the UK government uses.

Whatever this is, mapshaper.org is capable of reading it as a map of Scotland (left) but D3 doesn't know what's going on (right):

I think what I need to do is work out what co-ordinate system I'm being given, then work out how to convert it, but I can't see how to find out. The publisher (Scottish govt) give very little data around this and I don't think there's anyone I can ask.
Is there some way of "reading" the co-ordinate system from the WFS server, from the GML file, or from the GeoJSON? (or even better a converter that can figure it out and fix as it goes?)

Update: I think I might have figured out the specific cause of my problems, but I'd still like a general answer on what the 'correct' method to figure this out it is as opposed to my bumbling:
Truncating the projection code to EPSG:27700 losing the 6.9 turns up the Ordnance Survey National Grid, which is:

a system of geographic grid references used in Great Britain, different from using Latitude and Longitude. It is often called British National Grid (BNG).

...so it's clearly not just a projection, it's actually a whole different grid system as well. This would seem to explain why D3 is so confused. I'm not sure how someone would normally know this though, beyond knowing to recognise 27700 as a projection that also comes with a non-standard co-ordinate system?

A: The data's bounding box is defined with geographic coordinates. I guess this is what caused the confusion.
The data itself, however has the EPSG code 27700, hence the element <DefaultCRS>urn:ogc:def:crs:EPSG:6.9:27700</DefaultCRS>.
This means, that the data will be in EPSG 27700 unless otherwise specified. In this case, EPSG 4326 would be a possible alternative. You can look up the SRS characteristics on sites like spatialreference.org.
If you need your WFS result to be in 4326, simply add &srsName=EPSG:4326 to your WFS request.
The identifiers written before the EPSG code are used to unambiguously define WFS elements. The exact definition can be looked up at the EPSG home page.
In this specific case its

*

*urn: Universal Resource Name

*ogc: Open Geospatical Consortium

*def: Definition

*crs: Coordinate Reverence System

*EPSG: European Petroleum Survey Group

The 6.9 means that the SRS 4326 specified in version 6.9 of the EPSG database, which you can find here.


text:
Q: How to add R^2 and regression values to multi-factorial design in ggplot2 I have a two x two design. I need to add the R2 and regression values for each factor -- color coded on to the graph. I used partially used this answer to modify the code for this problem, but I still obtain only one regression line. Also, the regression equations are not printing clearly. I need four regression equations color-coded.
fertilizer <- c("N","N","N","N","N","N","N","N","N","N","N","N","P","P","P","P","P","P","P","P","P","P","P","P","N","N","N","N","N","N","N","N","N","N","N","N","P","P","P","P","P","P","P","P","P","P","P","P")

    level <- c("low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","low")

    growth <- c(0,0,1,2,90,5,2,5,8,55,1,90,2,4,66,80,1,90,2,33,56,70,99,100,66,80,1,90,2,33,0,0,1,2,90,5,2,2,5,8,55,1,90,2,4,66,0,0)

    repro <- c(1,90,2,4,66,80,1,90,2,33,56,70,99,100,66,80,1,90,2,33,0,0,1,2,90,5,2,2,5,8,55,1,90,2,4,66,0,0,0,0,1,2,90,5,2,5,8,55)

    df <- data.frame(fertilizer, level, growth, repro)

    lm_eqn = function(df){
      m = lm(growth ~ repro, df);
      eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
                       list(a = format(coef(m)[1], digits = 2),
                            b = format(coef(m)[2], digits = 2),
                            r2 = format(summary(m)$r.squared, digits = 3)))
      as.character(as.expression(eq));
    }

    eq <- ddply(df,.(fertlizer + level),lm_eqn)

ggplot(df, aes(x=growth, y=repro, color = fertilizer)) +  theme_bw() + geom_point(aes(colour = factor(fertilizer)), size = 0.1,alpha = 0.3) +
  geom_smooth(method='lm',se=FALSE, aes(colour = factor(fertilizer)), formula = y ~ x)+ scale_color_manual(values=c("#E69F00", "#1B9E77")) +
  facet_wrap(.~level, scales = "free") + theme(legend.position = "none") + theme(aspect.ratio = 1.75/1) + geom_text(data=eq,aes(x = 50, y = 25,label=V1), parse = TRUE, inherit.aes=FALSE, size = 2)

A: There are a lot of ways to get to non-overlapping, this is very basic and very much manual.
Add a new column to eq for mapping with geom_text(aes(y = y_pos)), instead of the constant used currently.
eq$y_pos <- c(24, 36, 8, 24)

ggplot(df, aes(x=growth, y=repro, color = fertilizer)) +
  geom_smooth(method='lm',se=FALSE, aes(colour = factor(fertilizer)), formula = y ~ x) +
  geom_point(aes(colour = factor(fertilizer)), size = 0.1,alpha = 0.3) +
# change here
  geom_text(data=eq,aes(x = 50, y = y_pos, label=V1), parse = TRUE, inherit.aes=FALSE, size = 2) +
# ----
  scale_color_manual(values=c("#E69F00", "#1B9E77")) +
  facet_wrap(.~level, scales = "free") +
  theme_bw() +
  theme(legend.position = "none",
        aspect.ratio = 1.75/1)

Maybe a more elegant and flexible solution is to extract the model's intercept and set that value as the y-position for each equation. Or you could extract the model value at a given x-value and use that.
Happy to share one of those if it helps, but lots of time for publication plots I fall back to manual text placement, just like this.


text:
Q: bubble sort ArrayIndexOutOfBoundsException public static void sort(int[] array){
    int[] newArray = new int[array.length];
    for (int i = 0; i < (array.length); i++){
        for(int j = i+1; j < (array.length); i++){
            if(array[i]>array[j]){
                array[j] = newArray[j-1];
                array[i] = newArray[i+1];
            }
        }
    }
    for (int idx = 0; idx < array.length; idx++){
        System.out.println(newArray[idx] + " ");
    }
}

Im trying to bubble sort but with this code i keep getting ArrayIndexOutOfBoundsException. What should i change to solve this problem? thank you in advance!

A: In the second for-loop:
for(int j = i+1; j < (array.length); i++){

you increment i++ instead of j++.


text:
Q: add multiple headers to http response in flutter i am beginner in flutter , i started to call an api from rapid api for soccer results , it's required to add many headers to call this api , when i put these headers , i had an error in syntax
here what i have tried , nothing worked
getResults() async {
    http.Response response = await http.get(
        'https://api-football-v1.p.rapidapi.com/v2/fixtures/league/2',
        headers: ({'x-rapidapi-key': 'e8ece1dbcdmshd1d6f778c1397c5p113b22jsn8361690f93a2'},
        {'x-rapidapi-host': 'api-football-v1.p.rapidapi.com'},
        {'useQueryString': true}));

I am trying to find the right syntax to make these headers works with my request

A: Put them in a single map:
headers: (
{'x-rapidapi-key': 'e8ece1dbcdmshd1d6f778c1397c5p113b22jsn8361690f93a2',
'x-rapidapi-host': 'api-football-v1.p.rapidapi.com',
'useQueryString': true}
)

A: import 'package:wnetworking/wnetworking.dart';

class RapidAPI {
  static const _base = 'https://api-football-v1.p.rapidapi.com/v2';
  static const _apiKey = 'e8ece1dbcdmshd1d6f778c1397c5p113b22jsn8361690f93a2';

  static Future<void> fetchFixturesLeague2() async {
    final url = '$_base/fixtures/league/2';

    print('Start fetching...');
    await HttpReqService.getJson<Map<String, dynamic>>(url, headers: {
      'x-rapidapi-host': 'api-football-v1.p.rapidapi.com',
      'x-rapidapi-key': _apiKey,
    })
      .then((response) {
        if (response != null) {
          print('${response['api']['fixtures'].length} items');
        }
      })
      .whenComplete(() => print('Fetching done.'));
  }
}

void main(List<String> args) async {
  await RapidAPI.fetchFixturesLeague2();
  print('Job done!');
}

Result:
Start fetching...
380 items
Fetching done.
Job done!


text:
Q: reading plist file crashes read in did load:
 NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path]) //4
{
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; //5

    [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}

//load in text fields.
NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

nameField.text = [[savedData objectForKey:@"name"] stringValue];
locationTextField.text = [[savedData objectForKey:@"location"] stringValue];
sectorTextField.text = [[savedData objectForKey:@"sector"] stringValue];

Write on button click:
    - (IBAction)writingButton:(id)sender
{
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

    //[data setObject:[NSNumber numberWithInt:value] forKey:@"value"];
    [data setObject:[NSString stringWithString:nameField.text] forKey:@"name"];
    [data setObject:[NSString stringWithString:locationTextField.text] forKey:@"location"];
    [data setObject:[NSString stringWithString:sectorTextField.text] forKey:@"sector"];
}

the plist file:

The error:

2012-09-04 17:03:40.360 app[4849:c07] -[__NSCFString stringValue]:
  unrecognized selector sent to instance 0x6aa38f0 2012-09-04
  17:03:40.362 app[4849:c07] *** Terminating app due to uncaught
  exception 'NSInvalidArgumentException', reason: '-[__NSCFString
  stringValue]: unrecognized selector sent to instance 0x6aa38f0'

Any ideas? cheers.

A: The dictionary stores NSString objects directly - there's no need to call a (nonexistent) method called - stringValue. Simply write
nameField.text = [savedData objectForKey:@"name"];

and so on.
(Why do you think this method call would have been necessary?)


text:
Q: NetLogo, HubNet and allocating Who-numbers So in my current HubNet application turtles are organized in various graph-structures. Whether or not two clients can see each other depends on whether the corresponding turtles are connected in the graph.
I currently build the graphs based on the turtles who-numbers and have thus built in the assumption that if there are n turtles at any given point these are numbered from 0 to n-1. I expect that this might cause problems if, for instance, a client connects, then drops and then re-connects since this (if I'm not mistaken) will give that client a new who-number (and the old number is not reused). So I'm wondering if there is a way to make sure that the turtles are numbered in the way I want?
Dropping everyone and then resetting who-numbers would be one (bad) solution. Can you help me either by suggesting a better solution or how to implement the bad solution?

A: If you want to use who numbers, you'll need to hide the turtles instead of killing them. If that makes things awkward because you find yourself needing to refer to e.g. turtles with [not hidden?], then consider making two breeds, call them actives and inactives or something like that, and then when hiding a turtle do hide-turtle set breed inactives. Then you can always refer to the set of active turtles just as actives. When someone joins the simulation, give them an inactive turtle if there is one, and have it do show-turtle set breed actives.
Or, if you decide not to use who numbers, you'll need a new turtle variable, say you call it id. When you make a new turtle, do set id count turtles - 1. When a turtle dies, you'll need to reassign new id numbers so there aren't gaps anymore. Does it matter exactly what scheme you use for that? Do you need there to be any particular relationship between a turtle's old number and its new number?  I can think of several possible different approaches to this.  Here's one that assigns the id numbers in ascending order by who number:
let whos sort [who] of turtles
ask turtles [ set id position who whos ]

P.S. But I have to wonder, is all this numbering really necessary? In a normal NetLogo model, it's almost never necessary to use who numbers for anything. There's almost always a simpler way. Why do you feel you need to use numbering in this model? Perhaps you do need it, but I'm at least a little skeptical.


text:
Q: OpenJDK 64-Bit Server VM warning:Options -Xverify:none and -noverify were deprecated in JDK 13 i tried to install sqldev tools in ubuntu and i got many problem even i have the jdk java-17-openjdk-amd64
also java is installed well
the error message showed in terminal :
Oracle SQL Developer
Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved.

OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: /usr/lib/jvm/java-17-openjdk-amd64/lib/libawt_xawt.so
    at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2393)
    at java.base/java.lang.Runtime.load0(Runtime.java:755)
    at java.base/java.lang.System.load(System.java:1953)
    at java.base/jdk.internal.loader.NativeLibraries.load(Native Method)
    at java.base/jdk.internal.loader.NativeLibraries$NativeLibraryImpl.open(NativeLibraries.java:384)
    at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:228)
    at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:170)
    at java.base/jdk.internal.loader.NativeLibraries.findFromPaths(NativeLibraries.java:311)
    at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:281)
    at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2398)
    at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:818)
    at java.base/java.lang.System.loadLibrary(System.java:1989)
    at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:1392)
    at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:1390)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:318)
    at java.desktop/java.awt.Toolkit.loadLibraries(Toolkit.java:1389)
    at java.desktop/java.awt.Toolkit.initStatic(Toolkit.java:1427)
    at java.desktop/java.awt.Toolkit.<clinit>(Toolkit.java:1401)
    at java.desktop/java.awt.Component.<clinit>(Component.java:624)
    at oracle.ide.osgi.boot.LauncherUtil.verifyJdkVersion(LauncherUtil.java:173)
    at oracle.ide.osgi.boot.LauncherUtil.checkLaunchPrerequisites(LauncherUtil.java:129)
    at oracle.ide.osgi.boot.LauncherUtil.initialize(LauncherUtil.java:101)
    at oracle.ide.osgi.boot.OracleIdeLauncher.main(OracleIdeLauncher.java:80)

A: Seems you have to install and use the previous version of the java like JDK 11
sudo apt install openjdk-11-jdk


text:
Q: @Remote JNDI Communication: Wildfly to JBoss AS 5.1.0.GA Architecture:
Windows Client -> Wildfly JAX-RS Services -> JBoss 5.1.0.GA legacy system.
I am getting a java.lang.ClassCastException: javax.naming.Reference cannot be cast to com.interfaces.GroupBookingManagerRemote when communicating here  between Wildfly JAX-RS Services and JBoss 5.1.0.GA legacy system.
As I am communicating from Wildfly to JBoss AS 5.1.0.GA I am attempting to connect using JNDI.
In my Wildfly Server Maven pom I include:
<dependency>
    <groupId>jboss</groupId>
    <artifactId>jnp-client</artifactId>
    <version>4.2.2.GA</version>
</dependency>

This gives me access to the required org.jnp.* classes and interfaces.
I simply use the following code to connect to my remote machine and retrieve back a GroupBookingManager. However the issue appears when I attempt to cast the class to the interface GroupBookingManagerRemote.
Properties env = new Properties();
env.setProperty(Context.PROVIDER_URL, "jnp://myremoteserver:1099");
env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
env.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
InitialContext initialContext = new InitialContext(env);

Object ref = initialContext.lookup("MyEARFile/GroupBookingManager/remote");
if (ref != null) {
    bookingManager = (GroupBookingManagerRemote) ref; // java.lang.ClassCastException: javax.naming.Reference cannot be cast
}

I have a myclient.jar file which I have added to my Wildfly application that contains the remote interface GroupBookingManagerRemote.
Does anyone see any issue with what I have done?
Thanks,
Darren

A: Thanks for your help Gimby,
I found the answer myself after a bit more messing about.
From Wildfly 8.1.0 (client) -> JBoss AS 5
You do not require any JBoss 5 jars
Firstly you need a reference to the interface that you wish to use on the client side. This can be in a your-project-client.jar. If using Maven you can create a repository and build the Maven directory structure using mvn
mvn install:install-file -DlocalRepositoryPath=DirectoryName -DcreateChecksum=true -Dpackaging=jar -Dfile=Path-to-you-project-client.jar -DgroupId=YourGroupId -DartifactId=YourartifactId -Dversion=1.0

Then in order to connect to the remote machine and cast the interface back to your-interface, you use:
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
env.put(Context.PROVIDER_URL, "remote://remoteserver:4447");
InitialContext initialContext = new InitialContext(env);

This uses Wildfly remote:// which is in remote naming and ejb in wildfly-ejb-client-bom
<dependency>
    <groupId>org.wildfly</groupId>
    <artifactId>wildfly-ejb-client-bom</artifactId>
    <version>8.1.0.Final</version>
    <scope>compile</scope>
    <type>pom</type>
</dependency>

And I also required this dependency for communication
<dependency>
    <groupId>org.jboss.xnio</groupId>
    <artifactId>xnio-nio</artifactId>
    <version>3.2.2.Final</version>
    <scope>compile</scope>
</dependency>

and this one for the remote naming.
<dependency>
    <groupId>org.jboss</groupId>
    <artifactId>jboss-remote-naming</artifactId>
    <version>2.0.1.Final</version>
</dependency>

Also note the port is not the ususal port for JBoss 5 JNDI:1099 this is the Default Remoting Port : 4447
Object ref = initialContext.lookup("ejb:Your-EAR/YourClass/remote!" + YouClass.class.getName());

You can then cast your reference to your interface and use it as normal.
Hope this makes sense.


text:
Q: In BMS if I connect li ion batteries of different capacities, how much mA will it provide in the output? If I connect one 1200mah, one 2600 mah and one 800mah li ion battery with a 3S BMS board. How much mA will it provide at the output? And when the BMS will stop giving output?
Thanks in advance for your reply.


text:
Q: Node js getting name of the file being uploaded  var express =   require("express");
    var multer  =   require('multer');
    const exec = require('child_process').exec;
    var app =   express();
    var storage =   multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, './uploads');
      },
      filename: function (req, file, callback) {
        callback(null, file.originalname);
      }
    });
    var upload = multer({ storage : storage}).single('myfile');
    debugger;
    app.get('/',function(req,res){
          res.sendFile(__dirname + "/index.html");
    });

    app.post('/uploadjavatpoint',function(req,res){
        upload(req,res,function(err) {
            if(err) {
                return res.end("Error uploading file.");
            }
            console.log("Uploading "+res.files);
            res.end("File is uploaded successfully!");
            console.log("Coverting to PDF");
            debugger;
            exec('"./px-8-5-4-win-x86-64/sdk/demo/pxsample.exe" "./uploads/EM_spectrum.ppt" "./uploads/EM_spectrum.pdf"');
            console.log("Coversion Done");
        });
    });

    app.listen(2000,function(){
        console.log("Server is running on port 2000");
    });

I am sending the file using postman with file(myfile) embedded in the body. I want to get the original name of the file being uploaded. I am new to node js please help me how to get the original name of the file being uploaded.
I tried req.file.filename as well as req.files but they don't seem to work

A: this should help you
>  const _files = req.files;
>  for (const file of _files) {
>       name = file.originalname;
>       size = file.size;
>  }

in postman,
Choose form-data in the body, file in the key and select the file in the value


text:
Q: can't create release app package for store UWP I am creating an application with Ionic / Cordova that must work on Windows 10. The application works well when I build it from Visual Studio in "debug" and "x64" configuration. But when I want to create an app package from "Project" > "Store" > "Create App Package", it fails with error :
Error MSB6006 "ilc.exe" exited with code 1200

Digging deeper, I can find in the output tab the error :
System.InvalidOperationException: Le nom de propriété "MSBuildToolsPath" est réservé

It's in French, I can't get the equivalent in English, it seems to mean "Property name MSBuildToolsPath is reserved"
Complete error message :
Task "LoggerBasedExecTask"
1>    Task Parameter:Application=C:\Program Files (x86)\MSBuild\15.0\.Net\.NetNative\15.0.24211\x86\ilc\ilc.exe
1>    Task Parameter:Parameters=@"build\windows\bld\ilc.CordovaApp.Windows10.rsp"
1>    Task Parameter:MessageLog=C:\QUALIOS\Sources\QualiosMobile_LW\Qualios\platforms\windows\build\windows\bld\ilc\ilclog.csv
1>    Task Parameter:UseCommandProcessor=False
1>    C:\Program Files (x86)\MSBuild\15.0\.Net\.NetNative\15.0.24211\x86\ilc\ilc.exe @"build\windows\bld\ilc.CordovaApp.Windows10.rsp" "/logger:CsvLogger;3472;3460"
1>    System.InvalidOperationException: Le nom de propriété "MSBuildToolsPath" est réservé.
1>       à Microsoft.Build.Shared.ErrorUtilities.ThrowInvalidOperation(String resourceName, Object[] args)
1>       à Microsoft.Build.Shared.ErrorUtilities.VerifyThrowInvalidOperation(Boolean condition, String resourceName, Object arg0)
1>       à Microsoft.Build.Construction.ProjectPropertyElement.CreateDisconnected(String name, ProjectRootElement containingProject)
1>       à Microsoft.Build.Construction.ProjectPropertyGroupElement.AddProperty(String name, String unevaluatedValue)
1>       à Microsoft.Build.Construction.ProjectRootElement.AddProperty(String name, String value)
1>       à ilc.Program.AddPropertiesToBlockEnvironmentVariables(ProjectRootElement rootElement)
1>       à ilc.Program.PrepareAndRunMsbuildTargets(Package package, String intermediatesFolderName, Boolean isAppX)
1>       à ilc.Program.RunIlc(String intermediatesFolderName)
1>       à ilc.Program.InnerMain(String[] args)
1>       à ilc.Program.Main(String[] args)
1>    ILC.exe has experienced an unexpected error. Please visit http://go.microsoft.com/fwlink/?LinkID=613098 for a list of known issues.
1>
1>    C:\Program Files (x86)\MSBuild\15.0\.Net\.NetNative\15.0.24211\Microsoft.NetNative.targets(640,5): error MSB6006: "ilc.exe" exited with code 1200.
1>    Output Property: _IlcExitCode=1200
1>  Done executing task "LoggerBasedExecTask" -- FAILED

A: Most of the time those errors are fixed by updating to the latest .NET Native (Microsoft.NETCore.UniversalWindowsPlatform) package.
Can you try to update to the latest version (6.2.8)? https://github.com/Microsoft/dotnet/blob/master/releases/UWP/net-native2.2/README.md

A: Finally found solution !
I just had to install globally windows-build-tools to get it work. Cordova apparently needs it
npm install -g windows-build-tools


text:
Q: Set an horizontal scroll to my Barchart in swift I am using the Charts framework from Daniel Cohen Gindi which is great but:
I would like my barchart to scroll horizontally to see additional data.
I've tried to add a scroll view but it didn't worked. I also tried different value like
barChart.setVisibleXRangeMaximum(10)
barChart.moveViewToX(90)

but it didn't work.
Is anyone managed it ?
Fingers crossed

A: First set bar chart data and then call 'barChart.setVisibleXRangeMaximum(10)'

A: the scroll will only happen if you zoomed in. By default, all data are plotted on the canvas, so nothing to scroll.
You can try increase scaleX by code, to see if your code works.

A: I just found out, ordering matters for this to work. You need to call setVisibleXRangeMaximum after chartView.data = data and all kinds of attributes assigned for barChartView


text:
Q: OpenStreetMap Python API Bounding Box Request I am new to OSM.
When I make an API bounding box call like below:
import overpass

# bounding box coordinates
min_long = min(longs)
min_lat = min(lats)
max_long = max(longs)
max_lat = max(lats)

# query overpass within OpenStreetMap
api = overpass.API()
map_query = overpass.MapQuery(min_lat,min_long,max_lat,max_long)
response = api.Get(map_query)

The output is not wrapped.  Here is a sample when I print response:
<member type="way" ref="50345468" role=""/>
<member type="way" ref="119882166" role=""/>
<member type="way" ref="7664653" role=""/>
<member type="way" ref="7661912" role=""/>
<member type="way" ref="7662660" role=""/>
<member type="way" ref="6983960" role=""/>
<member type="way" ref="6975837" role=""/>
<member type="way" ref="6982355" role=""/>
<member type="way" ref="6983849" role=""/>

Anybody have an idea of what is going on here?

A: Turns out the pip installation of the Python Overpass API is different than the current version on github.  If anyone else encounters this problem, just install the github version instead.

A: this is pretty weird. according to the docs, the default response is already in that form, hence this example:
print [(feature['tags']['name'], feature['id']) for feature in response['elements']]
[(u'Salt Lake City', 150935219), (u'Salt Lake City', 585370637), (u'Salt Lake City', 1615721573)]

what are the versions that you are using? any chance that you might be using an older version of overpass python API and they changed the default response?
There is an argument, when making the request, which can control the type of response (xml or geojson).
Check the version using

pip freeze

or if you're not using a virtualenv, check the folder where overpass is installed and poke around.

A: Overpass API supports different file formats (currently XML, JSON and CSV). According to a quick search you seem to be using Overpass API python wrapper. The README explains that you can call Get() with a responseformat parameter for choosing the file format. So try calling api.Get(map_query, responseformat="json").


text:
Q: Use infinite series to evaluate $\lim_{x \rightarrow \infty} (x^3 - 5x^2 + 1)^{\frac{1}{3}} - x$ Use infinite series to evaluate $\displaystyle\lim_{x \rightarrow \infty} (x^3 - 5x^2 + 1)^{\frac{1}{3}} - x$
I know the limit is $-\dfrac{5}{3}$ after rationalizing the expression, but I don't know how to prove it using Taylor series. Could someone give me any hints? I prefer hints to complete solutions.

A: Let $1/x=h$ to find
$$\lim_{h\to0^+}\dfrac{(1-5h+h^3)^{1/3}-1^{1/3}}h$$
Now rationalize the numerator using $$a^3-b^3=(a-b)(a^2+ab+b^2)$$

A: Taylor series ... Take
$$
(x^3-5x^2+1)^{1/3} = x\left(1-\frac{5}{x} + \frac{1}{x^3}\right)^{1/3}
$$
Taylor series for $1-5z+z^3$ near $z=0$ is $1 - \frac{5}{3}z + o(z)$ as $z \to 0$. So as $x \to \infty$,
\begin{align}
(x^3-5x^2+1)^{1/3} - x &= x\left(1-\frac{5}{x} + \frac{1}{x^3}\right)^{1/3} - x
\\ &= x\left(1 - \frac{5}{3x} + o(1/x)\right) - x
= -\frac{5}{3} + o(1) \to -\frac{5}{3} .
\end{align}

A: Perhaps I'm missing something, but it seems to me that the problem can be solved using intuition alone.  As $x \to \infty$, I would expect $(x^3 - 5x^2 + 1)^{(1/3)}$ to go towards $[(x - 5/3)^3]^{(1/3)}$.
Assuming that my intuition is correct, the overall limit would be
$(x - 5/3) - x = -5/3.$
Addendum
My intuition is based on the following idea.
If $(x^3 - 5x^2 + 1)^{(1/3)}$ goes toward $(x - k)$ then
two things are true:
(1) The overall limit is $(-k)$.
(2) Letting $D = (x^3 - 5x^2 + 1) - (x - k)^3$
then $D$ will represent a 2nd degree polynomial.
It seems clear to me that $k$ must be chosen so that the $x^2$ coefficient of $D$ is 0.
This is because as $x \to \infty$, the dominant term that affects the magnitude of $D$ will be its $x^2$ coefficient.


text:
Q: Are SQL unit tests supposed to be so long? I am writing stored procedures with some non-trivial business logic. I am trying to unit test them, but the actual tests end up being quite long (shorter ones starting at 40-50 LoCs, using commonly 4 different tables), which doesn't seem very "unit". (Admittedly, I format my code in a way where it takes a lot of space.)
In context of "normal" programming languages I've heard the advice to refactor the complex procedure into smaller chunks. But I don't want to do that here because:

*

*I don't want to pollute  "global namespace" by small routines called from one place only.

*Passing around tables from and to stored procedures is cumbersome.

*Custom functions can have negative effects on performance.

Am I wrong about this reasoning?
I am new to unit testing, so perhaps I am just writing my tests wrong?
Is SQL longwinded language and thus it's unit tests are longer as well?

(I am using SQL Server with tSQLt framework, but I believe the question is system-agnostic.)

A:
Am I wrong about this reasoning? I am new to unit testing, so perhaps I am just writing my tests wrong? Is SQL longwinded language and thus it's unit tests are longer as well?

I think this is a great (though somewhat opinion-based) question. The past few years I've attempted to implement tSQLt unit testing in a personal OSS project (https://dba-multitool.org/) to attempt to answer it via real world application. Unit testing for any type of SQL definitely breaks from classic norms and patterns. My tests definitely don't feel like unit tests and are usually more complex/longer than I'd prefer, but they have saved me a bunch of times from introducing breaking changes.
The stored procedures in my example are quite complex and long, so I came to a similar impasse as you: should I suck it up and deal with very complex "unit" tests, or fundamentally modify how the stored procedure works so that it is more amicable to unit testing in general? As with many database questions, the ultimate answer, I believe, is it depends. Performance and maintainability take a front seat here, in my experience.
I found that I wasn't able to justify largely changing the complex stored procedures to benefit from unit testing - adding more objects, as you noted, can increase complexity and in this case I was wary of asking end users to house a bunch of single-use objects in their database instead of offering an all-in-one utility stored procedure.
One technique that I did come up with was using optional parameters to induce test cases better. For example, I have parameters @IsExpress, @SqlMajorVersion, and @SqlMinorVersion that end users should not use (they are fetched at runtime if not passed) but that my tests utilize to make sure I'm catching errors I want around unsupported versions. Adding a lot of errors will increase the overall reliability of the code without having to necessarily explicitly test the more complex logic areas that may be hard/not reasonable to do. This marginally affects the stored procedure's length and complexity, but lets me easily isolate functionality and reliably test for it. You could take this further and use parameters to trigger select portions of the stored procedure that need testing the most, or to achieve better code coverage percentages by avoiding a messy area that isn't worth covering or is out of scope.
With this approach I was able to get a fairly high code coverage percentage (98%+) and while I definitely don't test all functionality, I know that almost all of the code gets executed, errors when I need it to, and will parse on execution.
To close with a quote, Wikipedia has unit testing defined as (emphasis mine):

In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures—are tested to determine whether they are fit for use.

I won't say that Wikipedia (or the book being quoted by Wikipedia) is the end-all for technical definitions, but I do like this definition since it focuses on the end goal of unit testing, which I think tSQLt can reasonably achieve.
Besides, some unit tests are better than none and having lines of code that aren't covered by unit testing defined may be very valuable in the future. To expand on the latter:
In 3 years, you've left the company and Employee #948 is trying to address a bug in the stored procedure. They look and see that only lines 50-65 out of 300 aren't covered by a unit test, otherwise all other functionality has been tested. They now have a pretty good shot at spending time on a likely problematic area rather than reverse engineering the entire 300 lines. Or, the next intern/new hire can be asked to fill in missing unit test coverage gaps as a learning exercise. Knowing what you aren't testing yet can help prioritize future work and diagnose problems faster.

A: Unit testing is not a simple thing.  If an application will need maintenance, it will benefit the quality of the product by filtering out most errors before being handed over to the end user.  The advantage of automatic testing, and testing tout court, is very often ignored.
"In context of "normal" programming languages I've heard the advice to refactor the complex procedure into smaller chunks."
This advice is almost as old as programming.  If you don't follow it, you can as well shoot yourself in the foot using your preferred programming language
shoot-self-in-foot.  But, and I quote: "you can't do foot_shooting in SQL."


text:
Q: Getting Windows 8 to go back to Metro Start Screen after closing a program started from desktop I would like to have Windows 8 automatically go back to the Metro Start Screen when I close a program or file as opposed to going back to desktop.
How can this be done?

A: You can achieve it using AutoHotKey. Install it, and create following 2 files:
switcher.ahk
#SingleInstance force

WinGet, id_ini, list,,, Program Manager
prev = %id_ini%

loop
{
sleep 3000     ; Milliseconds for which the loop waits before another iteration
WinGet, id, list,,, Program Manager
current = %id%
if(current < prev)
{
  ;somethin closed - press windows key here
  Run, "C:\press_windows.vbs"
}
prev = %id%
sleep 500
}

press_windows.vbs
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "^{ESCAPE}"

After creating both files and adjusting the Path in the switcher.ahk file to the location of vbs you created. You just need to Run the Autohotkey file (i.e. switcher.ahk) and you are done.
This will count all windows (Excluding the Background Services and Processes)
And If number of Windows Reduces it sends a Windows key press and switches to Modern-UI.
I'm using a VBS because for some reason Windows-8 doesn't take a Windows Key press from AHK.
Note: This script needs to be refined, sometimes it may behave unexpectedly, because it also counts the Context Menu and Notifications as new window. So when they are closed it sends a keypress.
To avoid such behavior we need to exclude such things, which can be done easily.

A: If you create a VBS script file and use it to launch your target application, the following instructions will do as you require:
'// File:  app2metro.vbs
'// Desc:  launch notepad then return to the metro interface

'//create shell object
Set WshShell = WScript.CreateObject("WScript.Shell")

'// run and wait for it to return
intReturn = WshShell.Run("notepad " & WScript.ScriptFullName, 1, TRUE)

'//switch to metro
WshShell.SendKeys "^{ESCAPE}"

A: While it is not hard at all to press the "Windows" key after closing a program, it would make sense that if you start a program from the Metro Start Screen, you return to it afterwards. Especially if that is what you want to promote.


text:
Q: csv file not downloading upon http response I am trying to convert a dictionary to csv and then download the csv file on the fly. When i return the response, I see the rows in the httpresponse. But I want it to download the content into a csv file in my local machine.
def export_csv_from_dict(data):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="accounts.csv"'

    keys = data[0].keys()
    dict_writer = csv.DictWriter(response, keys)
    dict_writer.writeheader()
    dict_writer.writerows(data)

    return response

def accounts_function(request):
    # rows is a list of dictionary [{'name': 'a'}, {'name': 'b'}]
    rows = get_rows_data(matched_accounts)
    return data.export_csv_from_dict(rows)

I have tried many different method I saw on stackoverflow, such as filewrapper, using FileResponse, using writing to a temp file and returning it with filewrapper. Also tried using StringIO. None seems to be doing what I want to happen. Can someone explain what I am doing wrong, please. Thanks.
In chrome debugger, I see the proper content in the desired csv format. It won't pop up the download to computer window/action.
Here is now I am triggering it. Don't think this
    $('#exp_csv').click(function(){
        $.ajax({
            'url': '/targeturl/',
            'type': 'get',
            data: {
                'exp_csv': true,
                'search_string': search
            },
            success: function(response){
                // do something
            },
            error: function(){
                // do something else
            }
        })
    });

A: Have you tried using simple hard coded rows data? Following code based on your example should work fine. If it works, then there must be problem in populating rows data on the fly, which would need some extra information from you on how your get_rows_data function is working.
def export_csv_from_dict(self, data):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    fieldnames = data[0].keys()
    writer = csv.DictWriter(response, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerows(data)
    return response

def accounts_function(self, request):
    rows = [{'first_name': 'Baked', 'last_name': 'Beans'},
            {'first_name': 'Lovely', 'last_name': 'Spam'},
            {'first_name': 'Wonderful', 'last_name': 'Spam'}]
    return self.export_csv_from_dict(rows)

A: There is a sloppy error I have spotted in the base your code:

# rows is a list of dictionary [{'name': 'a'}, {'name': 'b'}]

This seems to be a fatal construction.

*

*If you have many dictionaries with the same key, why don't you use a list which will include only the values and iterate through that list for each row?
rows = ['a', 'b',]

*If the keys are different:

keys = data[0].keys()

The above code will not give you the result you expect. It will only return the key of the first dictionary in the list. You should either iterate through that list and collect the key from each dictionary separately, or construct rows as follows:
rows = [{'name1': 'a', 'name2': 'b'},]


text:
Q: make 11 distinct necklaces from 3 different types of beads - without polya this is a home work question.
how many distinct necklaces can be made with 11 beads, each can be either circle, square or triangle?
necklaces are the same under rotation but not the same under mirror (turnover).
the thing is - i need to solve this without Pólya enumeration theorem or Burnside's lemma.
thanks in advance,
Yaron.

A: Let there be $N=3^{11}$ ways of arranging 11 beads of 3 different type in a string (not formed a necklace yet).
The question is, when we connect them up to form a necklace, how many of these necklaces are repeats of each other?
Given an arbitrary necklace, we could rotate it $k$ spaces, and get another necklace. It likely is a different necklace, but could be the same.
Lemma: If a necklace rotated by $1\leq k \leq 10$ places yields the same necklace, then all beads are of the same type. The converse is trivially true.
Hint: Let's consider what it means, if the rotated necklace is the same. This means that the bead in the 1st place, is the same as the bead in the $1+k$ place, is the same as the bead in the $1+2k$ place, etc.
As such, this tells us, given any string, it will (very likely) form the same necklace as 10 other strings (for a total of 11).
The only exception are the 3 necklaces, which are beads all of the same type. Hence, for each of these $N-3$ strings correspond to a set of 11 strings which yield the same necklace, thus there are $\frac{N-3} {11} $ distinct necklaces. Adding on the 3 strings whose beads are of the same type (which clearly give us distinct necklaces), we get $\frac{N-3}{11} + 3$ distinct necklaces.
Note: Burnside is the best way to solve this; you can see how the ideas above are expressed in Burnside.


text:
Q: Feature request? Ability to create an object via an array of key names in jq I'm an intermediate-to-advanced user of jq 1.5 and 1.6.  I'm iterating over an array of objects (let's say, keyed by the names of the first ten digits).  I have an array of strings stored in variable $odd_fields (["one","three",...,"nine"]).  Without using a convoluted iterative process (since I can do this statically with only map({one,three,...,nine}), I'd like to be able to re-cast my array of objects into an array of objects with reference to my array of keys, and in that order, like map({$odd_fields[]}).
After hundreds of attempts, I can't seem to do it in one throw without a static list of members.  I have been able to approximate this by creating an array of UNwanted keys and mapping del($unwanted_keys[]), but I don't care what keys I'm throwing away (and I have no confidence that the 50th object doesn't have one extra key that I don't want), only what keys I want to keep (or create, if missing), so that every object in the array has the same arbitrary keys (my keys) in the same order (suitable for @csv).
This is a general need not directly related to a specific JSON glob or specific set of keys, hence no sample JSON.
Most attempts that don't generate syntax or reference errors give me an array of objects [{"odd_fields":["one","three",...,"nine"]},...], or, some iterative processes give me just the values of the keys I want.  I want whole consistent subset objects as if any key not in my list was never present.
Additionally, any wizard out there who can tell me -- while iterating through an object, is there any way to determine what is/was the key to "."?  Similar to:  {"one":1,"two":2,"three":3}|map(.|my_key)  (where function my_key reveals what .'s key is).  I realize there's an easier way to do the above example, but I would like to be able to determine .'s key in other, less direct, code.  I don't need to use it to rip all keys from an object, just one key from an arbitrary ".".

A: To recast an object using the keys and key ordering in an array, $array:
def recast($array):
  . as $in
  | reduce $array[] as $k ({}; .[$k] = $in[$k]);

You could use this with your array as input as follows:
map(recast($odd_fields))

You may wish to tweak this with respect to missing and/or extra keys.
As a one-liner
A compact, reduce-free version:
map([$array[] as $p|{($p):.[$p]}]|add)


text:
Q: position fixed div overlap I have a two divs like this:

   // some fixed content here...

    // some other content here...

As you can see, the first div has position fixed. The problem I have is that the second div is overlapping with the first div. Any idea how I can fix this while keeping my first div fixed please without putting some kind of padding top to the second div or something?
Thank you

A: Set the margin-top of the second div to something greater than 100px. This way it will appear right below the first div


text:
Q: c# - Access running object reference from another class I am new to c#. I have one c# application already running.It is a mutex class which not allows to create multiple instances. so i need get access to some methods inside that class. in order to do that i need to get the running object reference in second class. how can i solve this in c#. plz help me.
Is there any way to retrieve reference objects using ROT?

A: I think its not that easy to retrieve information from a running application.
I do not know your requirement but if you want to retrieve or store information from application you may use a configuration file which essentially a xml file or you may store required information in some file and then retrieve that in other one.
This link can help you in that case.
Let me know if it helps.


text:
Q: High power voltage controlled bidirectional current source circuit I have tested various amplifiers and motor drivers and none of them are capable of driving my 20Ohm 100mH load at 0-> +/-2Adc (max 0 -> +/-100Vdc) in function of a control voltage (from a 16 bits DAC) with a closed-loop bandwidth of 5kHz. The bias and noise must be <= 1mA. I can give away 10V on the output for sensing.
Honestly I can't see any particular challenge for manufacturers of such equipment to make a product with these sorts of specs and yet I have found nothing suitable - so I am trying to make my own.
I'm looking for a very simple circuit topology that I can design in details - again, I was not able to find anything online after much research other than an application in the LT1990 datasheet that unfortunately can't go beyond 36V. I have two 4-quadrant +/- 100Vdc 2Adc lab supplies with voltage+current limiters so I thought about a simple opamp controlling the gate voltage of a MOSFET push pull based on the readings of a low-side sense resistor, but maybe there is something better?
Space, cost, dissipation are not an issue - I am solely interested in the high-speed performance.

A: It sounds to me like a job for a H bridge made from MOSFETs so that motor current reversal is easily achieved and, with the the main power being current limited with fairly standard circuits. The current limiting could also be done using PWM (and filtered).


text:
Q: Проблема после перевода в UTF-8 кодировку. Всем привет. Перевел сайт с CP-1251 на UTF-8, но как всегда без проблем не обошлось. Кодировка отображается правильно и в базу заносится кириллица отлично, но регулярные выражения подводят. Во-первых, придется переписывать все регулярные выражения, так как они отличаются от CP-1251 и работают по-другому. А проблема в следующем:
<? print preg_replace('/#([а-яА-Яa-zA-Z]+)/','#$1',  $msg);?>

С CP-1251 работало нормально, но после перевода появилась проблема. Смысл php строки заключается в том, что если в комментарии присутствует @имя, то преобразовывать в ссылку. Но теперь если ввести:
#тестовый

то появится:
#��естовый

И как ссылка считается до первого символа вопроса.
Если ввести так:
#Окей

То выводится нормально и полностью как ссылка.
Так же пробовал вот такие слова и выводится так: #Коне��но, #Н��жно, #Да, #Так, #Пойде��
Изменено:
   Заметил, что если убрать теги ссылки из шаблона, то отображается правильно:
<? print preg_replace('/#([а-яА-Яa-zA-Z]+)/','#$1',  $msg);?>

Как решить данную проблему. Заранее спасибо.
P.S. Проверил в базе слова. Они отображаются в нормальной кириллице.
A: Модификатор u, может быть?
<? print preg_replace('/#([а-яА-Яa-zA-Z]+)/u','#$1',  $msg);?>

A: После соединения с базой выполнить
 mysql_query("SET NAMES 'utf8'");

+сами страницы сохранить в UTF-8 без BOM. Должно сработать.
P.S. Не забыть прописать это
header('Content-type: text/html; charset=utf-8');

В начале каждой страницы.