text:
Q: Weblogic Error Comments may not contain '--' I am new to Weblogic. I have tried deploying the application and I got this error (with stacktrace). Has anyone come across this issue?
I have also created fresh domain to rule out the possibility of the domain being screwed up, but in vain.
<Oct 12, 2015 5:39:50 PM IST> <Error> <HTTP> <BEA-101064> <[WebAppModule(myApp-ear:/)] Error parsing descriptor in Web appplication "C:\Projects\myApp1\test\com.myOrg.myApp.app\trunk\myApp-ear\target\myApp-ear-1.10-SNAPSHOT\myApp-war-SNAPSHOT.war"
javax.xml.stream.XMLStreamException: Error at line:223 col:10 Comments may not contain '--'
    at weblogic.xml.stax.XMLStreamReaderBase.advance(XMLStreamReaderBase.java:206)
    at weblogic.xml.stax.XMLStreamReaderBase.next(XMLStreamReaderBase.java:237)
    at javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:60)
    at weblogic.application.descriptor.DebugStreamReaderDelegate.next(DebugStreamReaderDelegate.java:89)
    at weblogic.application.descriptor.BasicMunger2.next(BasicMunger2.java:425)
    Truncated. see log file for complete stacktrace
Caused By: Error at line:223 col:10 Comments may not contain '--'
    at weblogic.xml.babel.scanner.Comment.bufferData(Comment.java:60)
    at weblogic.xml.babel.scanner.Comment.read(Comment.java:79)
    at weblogic.xml.babel.scanner.Scanner.startState(Scanner.java:264)
    at weblogic.xml.babel.scanner.Scanner.scan(Scanner.java:178)
    at weblogic.xml.babel.baseparser.BaseParser.accept(BaseParser.java:533)
    Truncated. see log file for complete stacktrace
>
<Oct 12, 2015 5:39:50 PM IST> <Error> <Deployer> <BEA-149205> <Failed to initialize the application "myApp-ear" due to error weblogic.application.ModuleException: [HTTP:101064][WebAppModule(myApp-ear:/)] Error parsing descriptor in Web appplication "C:\Projects\myApp1\test\com.myOrg.myApp.app\trunk\myApp-ear\target\myApp-ear-1.10-SNAPSHOT\myApp-war-SNAPSHOT.war"
javax.xml.stream.XMLStreamException: Error at line:223 col:10 Comments may not contain '--'
    at weblogic.xml.stax.XMLStreamReaderBase.advance(XMLStreamReaderBase.java:206)
    at weblogic.xml.stax.XMLStreamReaderBase.next(XMLStreamReaderBase.java:237)
    at javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:60)
    at weblogic.application.descriptor.DebugStreamReaderDelegate.next(DebugStreamReaderDelegate.java:89)
    at weblogic.application.descriptor.BasicMunger2.next(BasicMunger2.java:425)
    at weblogic.application.descriptor.VersionMunger._next(VersionMunger.java:342)
    at weblogic.application.descriptor.VersionMunger.next(VersionMunger.java:230)
    at weblogic.application.descriptor.VersionMunger.consumeInputStream(VersionMunger.java:595)
    at weblogic.application.descriptor.VersionMunger.init(VersionMunger.java:485)
    at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:86)
    at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:62)
    at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:50)
    at weblogic.servlet.internal.WebAppReader2.<init>(WebAppReader2.java:47)
    at weblogic.servlet.internal.WebAppDescriptor$MyWebAppDescriptor.createXMLStreamReader(WebAppDescriptor.java:274)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:401)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:774)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:783)
    at weblogic.servlet.internal.WebAppDescriptor.getWebAppBean(WebAppDescriptor.java:141)
    at weblogic.servlet.internal.WebAppModule.loadDescriptor(WebAppModule.java:1482)
    at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:253)
    at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:636)
    at weblogic.application.internal.flow.ScopedModuleDriver.init(ScopedModuleDriver.java:162)
    at weblogic.application.internal.ExtensibleModuleWrapper.init(ExtensibleModuleWrapper.java:74)
    at weblogic.application.internal.flow.ModuleListenerInvoker.init(ModuleListenerInvoker.java:84)
    at weblogic.application.internal.flow.InitModulesFlow.initModule(InitModulesFlow.java:312)
    at weblogic.application.internal.flow.InitModulesFlow.initModules(InitModulesFlow.java:325)
    at weblogic.application.internal.flow.InitModulesFlow.prepare(InitModulesFlow.java:378)
    at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:706)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
    at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:237)
    at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:61)
    at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:158)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
    at weblogic.deploy.internal.targetserver.AppDeployment.prepare(AppDeployment.java:155)
    at weblogic.management.deploy.internal.DeploymentAdapter$1.doPrepare(DeploymentAdapter.java:39)
    at weblogic.management.deploy.internal.DeploymentAdapter.prepare(DeploymentAdapter.java:191)
    at weblogic.management.deploy.internal.AppTransition$1.transitionApp(AppTransition.java:21)
    at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:240)
    at weblogic.management.deploy.internal.ConfiguredDeployments.prepare(ConfiguredDeployments.java:165)
    at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:122)
    at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:186)
    at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:94)
    at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
Caused by: Error at line:223 col:10 Comments may not contain '--'
    at weblogic.xml.babel.scanner.Comment.bufferData(Comment.java:60)
    at weblogic.xml.babel.scanner.Comment.read(Comment.java:79)
    at weblogic.xml.babel.scanner.Scanner.startState(Scanner.java:264)
    at weblogic.xml.babel.scanner.Scanner.scan(Scanner.java:178)
    at weblogic.xml.babel.baseparser.BaseParser.accept(BaseParser.java:533)
    at weblogic.xml.babel.baseparser.StartElement.parse(StartElement.java:77)
    at weblogic.xml.babel.baseparser.BaseParser.parseElement(BaseParser.java:453)
    at weblogic.xml.babel.baseparser.BaseParser.parseSome(BaseParser.java:326)
    at weblogic.xml.stax.XMLStreamReaderBase.advance(XMLStreamReaderBase.java:195)
    ... 44 more

Error at line:223 col:10 Comments may not contain '--'
weblogic.application.ModuleException: [HTTP:101064][WebAppModule(myApp-ear:/)] Error parsing descriptor in Web appplication "C:\Projects\myApp1\test\com.myOrg.myApp.app\trunk\myApp-ear\target\myApp-ear-1.10-SNAPSHOT\myApp-war-SNAPSHOT.war"
javax.xml.stream.XMLStreamException: Error at line:223 col:10 Comments may not contain '--'
    at weblogic.xml.stax.XMLStreamReaderBase.advance(XMLStreamReaderBase.java:206)
    at weblogic.xml.stax.XMLStreamReaderBase.next(XMLStreamReaderBase.java:237)
    at javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:60)
    at weblogic.application.descriptor.DebugStreamReaderDelegate.next(DebugStreamReaderDelegate.java:89)
    at weblogic.application.descriptor.BasicMunger2.next(BasicMunger2.java:425)
    at weblogic.application.descriptor.VersionMunger._next(VersionMunger.java:342)
    at weblogic.application.descriptor.VersionMunger.next(VersionMunger.java:230)
    at weblogic.application.descriptor.VersionMunger.consumeInputStream(VersionMunger.java:595)
    at weblogic.application.descriptor.VersionMunger.init(VersionMunger.java:485)
    at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:86)
    at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:62)
    at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:50)
    at weblogic.servlet.internal.WebAppReader2.<init>(WebAppReader2.java:47)
    at weblogic.servlet.internal.WebAppDescriptor$MyWebAppDescriptor.createXMLStreamReader(WebAppDescriptor.java:274)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:401)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:774)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:783)
    at weblogic.servlet.internal.WebAppDescriptor.getWebAppBean(WebAppDescriptor.java:141)
    at weblogic.servlet.internal.WebAppModule.loadDescriptor(WebAppModule.java:1482)
    at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:253)
    at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:636)
    at weblogic.application.internal.flow.ScopedModuleDriver.init(ScopedModuleDriver.java:162)
    at weblogic.application.internal.ExtensibleModuleWrapper.init(ExtensibleModuleWrapper.java:74)
    at weblogic.application.internal.flow.ModuleListenerInvoker.init(ModuleListenerInvoker.java:84)
    at weblogic.application.internal.flow.InitModulesFlow.initModule(InitModulesFlow.java:312)
    at weblogic.application.internal.flow.InitModulesFlow.initModules(InitModulesFlow.java:325)
    at weblogic.application.internal.flow.InitModulesFlow.prepare(InitModulesFlow.java:378)
    at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:706)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
    at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:237)
    at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:61)
    at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:158)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
    at weblogic.deploy.internal.targetserver.AppDeployment.prepare(AppDeployment.java:155)
    at weblogic.management.deploy.internal.DeploymentAdapter$1.doPrepare(DeploymentAdapter.java:39)
    at weblogic.management.deploy.internal.DeploymentAdapter.prepare(DeploymentAdapter.java:191)
    at weblogic.management.deploy.internal.AppTransition$1.transitionApp(AppTransition.java:21)
    at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:240)
    at weblogic.management.deploy.internal.ConfiguredDeployments.prepare(ConfiguredDeployments.java:165)
    at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:122)
    at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:186)
    at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:94)
    at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
Caused by: Error at line:223 col:10 Comments may not contain '--'
    at weblogic.xml.babel.scanner.Comment.bufferData(Comment.java:60)
    at weblogic.xml.babel.scanner.Comment.read(Comment.java:79)
    at weblogic.xml.babel.scanner.Scanner.startState(Scanner.java:264)
    at weblogic.xml.babel.scanner.Scanner.scan(Scanner.java:178)
    at weblogic.xml.babel.baseparser.BaseParser.accept(BaseParser.java:533)
    at weblogic.xml.babel.baseparser.StartElement.parse(StartElement.java:77)
    at weblogic.xml.babel.baseparser.BaseParser.parseElement(BaseParser.java:453)
    at weblogic.xml.babel.baseparser.BaseParser.parseSome(BaseParser.java:326)
    at weblogic.xml.stax.XMLStreamReaderBase.advance(XMLStreamReaderBase.java:195)
    ... 44 more

Error at line:223 col:10 Comments may not contain '--'
    at weblogic.servlet.internal.WebAppModule.createModuleException(WebAppModule.java:1848)
    at weblogic.servlet.internal.WebAppModule.loadDescriptor(WebAppModule.java:1516)
    at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:253)
    at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:636)
    at weblogic.application.internal.flow.ScopedModuleDriver.init(ScopedModuleDriver.java:162)
    Truncated. see log file for complete stacktrace
Caused By: Error at line:223 col:10 Comments may not contain '--'
    at weblogic.xml.babel.scanner.Comment.bufferData(Comment.java:60)
    at weblogic.xml.babel.scanner.Comment.read(Comment.java:79)
    at weblogic.xml.babel.scanner.Scanner.startState(Scanner.java:264)
    at weblogic.xml.babel.scanner.Scanner.scan(Scanner.java:178)
    at weblogic.xml.babel.baseparser.BaseParser.accept(BaseParser.java:533)
    Truncated. see log file for complete stacktrace
>

A: Weblogic server failed to parse some of the comments used "" in struts-config.xml. Removing comments resolved the issue.But interestingly only few specific comments were causing the issue.


text:
Q: CS32F103C8T6 blue-pill clone - cannot flash from AC6 SystemWorkbench I am trying to flash a blue-pill clone with a CS32F103C8T6 chip using the AC6 SystemWorkBench and a ST-LINK v2 device. It is a project built from STM32CubeMX - I am using a MacOS Mojave machine. Here is the output when trying to flash the device.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 8000 kHz
adapter_nsrst_delay: 100
Info : clock speed 8000 kHz
Info : STLINK v2 JTAG v31 API v2 SWIM v7 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 3.162004
Info : Unable to match requested speed 8000 kHz, using 4000 kHz
Info : Stlink adapter speed set to 4000 kHz
Warn : UNEXPECTED idcode: 0x2ba01477
Error: expected 1 of 1: 0x1ba01477
in procedure 'program'
in procedure 'init' called at file "embedded:startup.tcl", line 495
in procedure 'ocd_bouncer'
** OpenOCD init failed **
shutdown command invoked

I have googled and found some similar posts about it, but have no luck solving it.
Does anyone have an idea ?
mvh
Ole K Hornnes

A: In the OpenOCD config file, you need to add:
set CPUTAPID 0x2ba01477

I've never used AC6 SystemWorkbench and I don't now how you configure the board and the debug adapter in it. So I can't really tell where to look for the config file.
OpenOCD comes with an entire directory of board configurations, usually in a directory OpenOCD / scripts / board. It contains a script called stm32f103c8_blue_pill.cfg, which might be used in your case. Start there...

A: set CPUTAPID 0x2ba01477 ; Will work for the clone but not for the genuine STM32…
Instead use: set CPUTAPID 0
The zero tells OpenOCD to ignore the id number, so any MCU will then work…
Information Source: OpenOCD TAPs

A: C:\Ac6\SystemWorkbench\plugins\fr.ac6.mcu.debug_2.5.0.201904120827\resources\openocd\st_scripts\target\stm32f1x.cfg
add this line before first if statement
set CPUTAPID 0
it solves all openocd stlink id errors

redpajama_set_name: RedPajamaStackExchange


text:
Q: TCP ACK of packets in wireshark I've noticed in wireshark that I'm able to send 4096 bytes of data to a HTTP webserver (from uploading a file) however the server only seems to be acknowledging data 1460 bytes at a time. Why is this the case?

A: The size of TCP segments is restricted to the MSS (Maximum Segment Size), which is basically the MTU (Maximum Transmission Unit) less the bytes comprising the IP and TCP overhead.  On a typical Ethernet link, the MTU is 1500 bytes and basic IP and TCP headers comprise 20 bytes each, so the MSS is 1460 (1500 - 20 - 20).
If you're seeing packets indicated with a length field of 4096 bytes, then it almost certainly means that you're capturing on the transmitting host and Wireshark is being handed the large packet before it's segmented into 1460 byte chunks.  If you were to capture at the receiving side, you would see the individual 1460 byte segments arriving and not a single, large 4096 byte packet.
For further reading, I would encourage you to read Jasper Bongertz's blog titled, "The drawbacks of local packet captures".

A: TCP by default uses path MTU discovery:

*

*When system send packet to the network it set don't fragment flag (DF) in IP header

*When IP router or you local machine see DF packet that should be fragmented to match MTU of the next hop link it sends feedback (RTCP fragmentation need) that contains new MTU

*When system receives fragmentation needed ICMP it adjusts MSS and send data again.

This procedure is performed to reduce overall load on the network and increase probability of each packet delivery.
This is why you see 1460 packets.
Regarding to you question: the server only seems to be acknowledging data 1460 bytes at a time. Why is this the case?
TCP keep track window that defines "how many bytes of data you can send without acknowledge". Its purpose is to provide flow control mechanisms (sender can't send too much data that can't be processed) and congestion control mechanisms (sender can't send too much data to overload network). Window is defined by receiver side and may be increased during connection when TCP will estimate real channel bandwidth. So you may see one ACK that acknowledges several packets.


text:
Q: How to request products with ebay api? How can I call eBay and request it to return search results array?
This is what I came up with so far:
string endpoint = "https://api.ebay.com/wsapi";
string siteId = "0";
string appId = "*";     // use your app ID
string devId = "*";     // use your dev ID
string certId = "*";   // use your cert ID
string version = "405";

string requestURL = endpoint
+ "?callname=FindProducts"
+ "&siteid=" + siteId
+ "&appid=" + appId
+ "&version=" + version
+ "&routing=default"
+ "&AvailableItemsOnly=true"
+ "&QueryKeywords=nvidia"
+ "&itemFilter(0).name=ListingType"
+ "&itemFilter(0).value(0)=FixedPrice"
+ "&itemFilter(0).value(1)=Auction"
+ "&CategoryID=27386";

How can I wrap it into request and get a response in some-sort of data-structure? I have gotten the SDK.

A: I needed to use the eBay finding API;
    public GetItemCall getItemDataFromEbay(String itemId)
    {
        ApiContext oContext = new ApiContext();
        oContext.ApiCredential.ApiAccount.Developer = ""; // use your dev ID
        oContext.ApiCredential.ApiAccount.Application = ""; // use your app ID
        oContext.ApiCredential.ApiAccount.Certificate = ""; // use your cert ID
        oContext.ApiCredential.eBayToken = "";            //set the AuthToken

        //set the endpoint (sandbox) use https://api.ebay.com/wsapi for production
        oContext.SoapApiServerUrl = "https://api.ebay.com/wsapi";

        //set the Site of the Context
        oContext.Site = eBay.Service.Core.Soap.SiteCodeType.US;

        //the WSDL Version used for this SDK build
        oContext.Version = "735";

        //very important, let's setup the logging
        ApiLogManager oLogManager = new ApiLogManager();
        oLogManager.ApiLoggerList.Add(new eBay.Service.Util.FileLogger("GetItem.log", true, true, true));
        oLogManager.EnableLogging = true;
        oContext.ApiLogManager = oLogManager;

        GetItemCall oGetItemCall = new GetItemCall(oContext);

        //' set the Version used in the call
        oGetItemCall.Version = oContext.Version;

        //' set the Site of the call
        oGetItemCall.Site = oContext.Site;

        //' enable the compression feature
        oGetItemCall.EnableCompression = true;
        oGetItemCall.DetailLevelList.Add(eBay.Service.Core.Soap.DetailLevelCodeType.ReturnAll);
        oGetItemCall.ItemID = itemId;
        try
        {
            oGetItemCall.GetItem(oGetItemCall.ItemID);
        }
        catch (Exception E)
        {
            Console.Write(E.ToString());
            oGetItemCall.GetItem(itemId);
        }
        GC.Collect();
        return oGetItemCall;
    }


text:
Q: Ajax send image within data I'm trying to send some data by Ajax and this data may contain an image.
I don't have any forms, so I can't submit by the traditional way.
This is my HTML:
<input type="file" accept="image/png,image/jpg,image/jpeg,image/bmp" id="addProduct_image">

Whenever the user changes the file I get that value.
var files;

$(document).on('change', '#addProduct_image', function(e){
    prepareUpload(e);
});

function prepareUpload(event){
  files = event.target.files;
}

When the OK button is pressed I call an ajax function.
$(document).on('click', '#addProduct_OK', function(e){
    var img = new FormData();
    $.each(files, function(key, value)
    {
        img.append(key, value);
    });

    $.ajax({
        url: 'responses/product.php?type=productAdd',
        type: 'POST',
        data: {title: $("#addProduct_title").val(), description: $("#addProduct_description").val(),
               image: img, status: $("#addProduct_status").val()
              },
        success: function(data){
            console.log(data);
        }
    });
});

I'm currently receiving the error on chrome console

Uncaught TypeError: Illegal invocation

in the ajax line. I'm to far away from how to send an image by ajax with other data also?

A: You need to sent the FormData as the data for the ajax request, so the additional params also has to be appended to the fomdata
$(document).on('click', '#addProduct_OK', function (e) {
    var img = new FormData();
    $.each(files, function (key, value) {
        img.append(key, value);
    });
    img.append('title', $("#addProduct_title").val());
    img.append('description', $("#addProduct_description").val());
    img.append('status', $("#addProduct_status").val());

    $.ajax({
        url: 'responses/product.php?type=productAdd',
        type: 'POST',
        data: img,
        processData: false,
        contentType: false,
        success: function (data) {
            console.log(data);
        }
    });
});


text:
Q: From address going into junk mail folder in hotmail I have a certain email address that hotmail is sending all emails from to the junk folder. If I send the same email, from the same server, with the same content, but from a different email address it goes to the inbox.
Any ideas? The address is donotreply@ and I use this on other sites of mine and don't have any problems with the junk folder.
David

A: You will never find a confirmed answer for this question for a number of reasons.

*

*Microsoft are a law unto themselves.

*There is no way for you to confirm why. The actual reason for filtering is never released and therefore testing is pretty much useless. Microsoft just give a score and no individual reasons (like spamassassin)

However, it is likely that someone has previously flagged this email address as spam, probably not releasing that they actually signed up for it (and I hope they did). If the content is identical and the only thing that changes is the address, I can think of no other reason.
If it was a content issue, then in theory all emails from any address would get flagged.
If it was an IP reputation, same as above.
This leaves sender address.


text:
Q: Google Maps API error: MissingKeyMapError - I do have it but it is not recognize I have the google API key but the browser doesn't recognize that. You can go my site: rodcurvelo.com, click contact and you will see the error.
The browser says also:

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

Here is my code:

Iam Here

 Address: 8723 Bogor, West Java

 Phone: 87-3898-221

 Email: someone@company.com

      //theme.js
      //Run function When Document Ready
      $(document).ready(function() {
         initMap();

      });

          //Map
          function initMap() {
          $('#map-contact').gmap({
          'center': '27.867473, -82.637582',
          'zoom': 15,
           scrollwheel: false,
          'disableDefaultUI': false,
          'callback': function() {
          var self = this;
          self.addMarker({
           'position': this.get('map').getCenter(),
            icon: 'assets/theme/images/marker.png'
            }).click(function() {
            self.openInfoWindow({
            'content': $('.map-contact-body').html()
          }, this);
        });
       }
     });
    }

A: You're requiring Google Maps API twice;

And:

Try joining them together (see this: Fixing "You have included the Google Maps API multiple times on this page. This may cause unexpected errors.")
Also, I'm not entirely sure about you're usage of async defer, as far as I know it's either script async or script defer, not both :)


text:
Q: How do I obtain related entities after a concurrency exception in Asp.net MVC? I am following the asp.net contoso university example from concurrency exceptions. Everything works great for a single entity. But when I want to retrieve related entities database values they are null. Below is my exception set up.
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
catch(DbUpdateConcurrencyException ex)
{
    var entry = ex.Entries.Single();
    var clientValues = (Car)entry.Entity;
    var databaseValues = (Car)entry.GetDatabaseValues().ToObject;

I was wondering why this is done the way it is.?
Why not not use find and include to get the car object and its related tables?
Is their a way to get the related tables with the current example code?
I'm using Asp.net MVC5, c#, Entity Framework 6
I tried using
 var databaseValues = unitofworkcar.carRepository.FindIncluding(id);

which is basically just a function that calls include on all connected tables.
But what I get back is what my client typed in and not the current entries in the database?
How do I correct this?


text:
Q: ajax not activating, taking me to a different page the code works as I want but it takes me to a different page and have something like {"success": 1, "voteobj": 57}. I was informed ajax is the one for this but I'm not good at it. here's what I have. can someone check where I made an error and what I should do to fix it/?

<form method="post" action="{% url 'vote' %}" class="vote_form">

 [{{ post.votes }}]
        {{post}}
        {% csrf_token %}
        <input type="hidden" id="id_post" name="post" class="hidden_id" value="{{ post.pk }}" />
        <input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" />
        {% if not user.is_authenticated %}

login to vote

        {% elif post.pk not in voted %}
            <button class="btn btn-primary">like</button>
        {% else %}
        <button class="btn btn-primary">dislike</button>
        {% endif %}
            </form>

And following is my python code
class JSONFormMixin(object):
    def create_response(self, vdict=dict(), valid_form=True):
        response = HttpResponse(json.dumps(vdict), content_type='application/json')
        response.status = 200 if valid_form else 500
        return response

class VoteFormBaseView(FormView):
    form_class = VoteForm

    def create_response(self, vdict=dict(), valid_form=True):
        response = HttpResponse(json.dumps(vdict))
        response.status = 200 if valid_form else 500
        return response

    def form_valid(self, form):
        post = get_object_or_404(Post, pk=form.data["post"])
        user = self.request.user
        prev_votes = Vote.objects.filter(voter=user, post=post)
        has_voted = (len(prev_votes) > 0)

        ret = {"success": 1}
        if not has_voted:
            # add vote
            v = Vote.objects.create(voter=user, post=post)
            ret["voteobj"] = v.id
        else:
            # delete vote
            prev_votes[0].delete()
            ret["unvoted"] = 1
        return self.create_response(ret, True)

    def form_invalid(self, form):
        ret = {"success": 0, "form_errors": form.errors }
        return self.create_response(ret, False)

urls.py

urlpatterns = [
    path('vote/', auth(VoteFormView.as_view()), name='vote'),

Edit: I followed the instruction on the following web: https://arunrocks.com/building-a-hacker-news-clone-in-django-part-4/
Everything works good but ajax on my side
Edit: So without ajax the url is http://127.0.0.1:8000/community/vote/
With ajax the url is
/community/post/3/vote/
but it says Not Found: on terminal

A:  return self.create_response(ret, True)

should be
return JsonResponse(safe=False, ret)

Sorry, I didn't take my time and answered lazily. Don't change response. Keep that as you have it and do what I just did above.
Should work.

A:     <button class="btn btn-primary" onclick="runthis({{post.pk}})">like</button>

function runthis(n){

var patch = '{% url "vote2" %}'

comment = document.getElementById('id_post').value
comment2 = document.getElementById('id_voter').value
info = {"comment":comment, "comment2":"comment2", 'csrfmiddlewaretoken':"{{ csrf_token }}", 'query':n}

$.ajax({
  type: "POST",
  url: patch,
  data:info,
    datatype:'json',
   headers: { "X-CSRFToken": '{{csrf_token}}' },

success: function(data){

console.log('success')
return

}

})

add to urls.py
urlpatterns = [
    path('vote/', auth(VoteFormView.as_view()), name='vote'),
    path('vote2/', view.vote2, name='vote2')]

then add to  views.
def vote2(request):
    if request.method == 'POST':
        response_json = request.POST
        response_json = json.dumps(response_json)
        data = json.loads(response_json)
        this_is_the_pk = data['query']
        this_is_the_comment = data['comment']
        this_is_the_comment2 = data['comment2']
return JsonResponse(safe=false)

A: You are probably getting an error that JQuery is not defined, so e.preventDefaults() never runs and you get the standard form submit action. Try including the script tag for pulling in JQuery before this script. Here is how that might look:

<form method="post" action="{% url 'vote' %}" class="vote_form">

 [{{ post.votes }}]
        {{post}}
        {% csrf_token %}
        <input type="hidden" id="id_post" name="post" class="hidden_id" value="{{ post.pk }}" />
        <input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" />
        {% if not user.is_authenticated %}

login to vote

        {% elif post.pk not in voted %}
            <button class="btn btn-primary">like</button>
        {% else %}
        <button class="btn btn-primary">dislike</button>
        {% endif %}
            </form>

Also, your HTML seems to be missing a closing
 tag.


text:
Q: Print Pattern Using Iterative Approach I am an absolute beginner to C.
Can you please explain me this problem correctly.
I am trying to print this pattern in C language using Iterative Approach
*
***
*****

So, I have to print this pattern but my code dont work.
And my code is printing this:
*****
*****
*****

My code:

#include <stdio.h>

int stars(int n) {

    if(n==1){
       printf("*");
       return;
     }
    // i = 0 ; i<3; i++//
    // 2*3-1 = 5
    for(int i=0; i<n; i++){

    for(int z=0; z<((2*n)-1) ; z++){

    printf("*");

    }

    printf("\n");

    }

}

int main() {

    stars(3);

    return 0;
}

Can you please explain me, why this is happening and what is the correct code for this pattern?
*
***
*****

A: Your problem is that in the second loop you always iterate for 2*n-1 you should iterate based on the iteration variable i
for(int z=0; z<((2*i)+1) ; z++)

The first loop that you wrote iterate on the number of lines, for each line you want a different amount of printf("*") but if the number of iterations is constant (because n Doesn't change) the amount of printing will also be constant. This is the reason you printed the same amount of "*" for each line.


text:
Q: Como criar serviço de streaming com python e django Tenho o propósito de criar um serviço de Streaming de vídeos, o projeto é em python e django.
Como faço para disponibilizar tal serviço?
Uso python 2.7 e django 1.10.
Só encontrei material antigo!
Grato pela atenção !


text:
Q: Command linux "Date" into perl script I must to implement a Perl script that makes use inside the Linux command 'date' to use the current date as the reference date for the identification of any events stored in a file. Help please.
I know the function Localtime() but i don't need that but explicitly linux command DATE.

A: This is not a good way to get the current time in Perl, but it does answer the narrowly defined question above.  Here it is working:
$ perl date-test
<<Mon Aug 31 06:52:08 PDT 2015>>

Here is the code:
$ cat date-test
#!/usr/bin/perl

use strict;
use warnings;

my $static_date = `date`;
chomp($static_date);

print "<<$static_date>>\n";

A: use strict;
my $sysdate = system ( date);
print $sysdate;


text:
Q: I used a char variable as Array Index to a Boolean array in Java? How does the conversion of character to its ASCII value happen? The below code checks if there is a duplicate character
String s = "Bengaluru";
boolean[] characters = new boolean[128];

    for(int i=0; i<s.length();i++){
        char ch = s.charAt(i);
        if(characters[ch] == true){
            return;
        }
        else
            characters[ch] = true;//Here true is getting stored in the ASCII value of the character.
    }

A: The full answer is much more complicated than what dasblinkenlight is suggesting.
Since Java 5, the data type char does not represent a character or Unicode codepoint anymore, but a UTF-16 encoded value, which might be a complete character or a fraction of a character. This UTF-16 value is in reality just a 16-bit unsigned integer in the range 0 to 65535 and will be casted automatically to an int when used as an array index, just as the other numeric datatypes like short or byte. If you really want a Unicode codepoint as a character, you should use the method codePointAt(int index) instead of charAt(int index). The Unicode code point can be in the range 0 to 1114111 (0x10ffff).
How the methods charAt and codePointAt methods work internally is implementation specific. It is often incorrectly claimed that a String is just a wrapper around an array of chars, but the internal implementation of the String class is not mandated by the language or API specification. Since Java 6, the Oracle VM has been using different optimization strategies to save memory and is not always using a plain char array.

A: Java represents chars using 16-bit UNICODE code points*. There is no conversion to ASCII happening - it's just that the initial 128 code points happen to represent the same characters as the corresponding ASCII values.
Java does perform a conversion of char to int in order to make the indexing possible. This is a built-in conversion that happens implicitly, because it is widening. In other words, any value that can be stored in a char can be represented in an int without a loss.
* Java-5 switched to UTF-16 representation, changing interpretation of some numbers as "partial characters". chars remained 16-bit unsigned numbers, though.

A: Java Supports Automatic widening primitive conversions
https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.2
How to stop Java from automatically casting a char value to an int?
char to int, long, float, or double


text:
Q: Exclude word and quotes from regexp I have the following phrases:

*

*Mr "Smith"

*MrS "Smith"

I need to retrieve only Smith from this phrases. I tried thousands of variants. I stoped on
(?!Mr|MrS)([^"]+).
Help, please.

A: The pattern (?!Mr|MrS)([^"]+) asserts from the current position that what is directly to the right is not Mr or MrS and then captures 1+ occurrences of any char except "
So it will not start the match at Mr  but it will at r  because at the position before the r the lookahead assertion it true.

Instead of using a lookaround, you could match either Mr or MrS and capture what is in between double quotes.
\mMrS? "([^"]+)"

*

*\m A word boundary

*MrS? Match Mr with an optional S

* " Match a space and "

*([^"]+) capture in group 1 what is between the "

*" Match  "
See a postgresql demo
For example
select REGEXP_MATCHES('Mr "Smith"', '\mMrS? "([^"]+)"');
select REGEXP_MATCHES('MrS "Smith"', '\mMrS? "([^"]+)"');

Output
    regexp_matches
1   Smith

    regexp_matches
1   Smith


text:
Q: methods to analyze zero-inflated data type    intact  bury
B          0     0
B          0     0
B          0     0
B          0     0
B          0     0
B          0     0
M        0.375   0
M        0.05    0
M          0     0
M          0     0
M          0    0.025
M      0.033333333  0
M          0    0.025
M          0    0.025
S        0.025   0
S          0     0
S          0    0.011111111
S      0.166666667  0
S          0    0.033333333
S      0.188888889  0.044444444
S          0        0
S          0      0.02
S          0        0
S          0        0

My question is that if I want to use type as factor to estimate its effects on variable intact and bury, which methods do I use? In first, I used generalized linear mixed model, but it didn't work well. So how about zero-inflated model? if does, which package do i need? I have no idea about it. Could you help me and give me some suggestions? Very thanks~

A: Have you looked at the pscl package http://cran.r-project.org/web/packages/pscl/pscl.pdf. This includes methods for Hurdle and zero inflated Poisson methods.
Look at examples from UCLA stats: http://www.ats.ucla.edu/stat/r/dae/zipoisson.htm. for example

A: Some standard strategies include censored regression models such as the tobit (zero-censored Gaussian) or continuous hurdle models (combining a binary and a zero-truncated model). Especially if the number of non-zeros is not so large then using only the binary model (0 vs. greater) might also be a good first step.
In your case the question is whether your data set is actually larger than the one reported here. If this is the complete data, then there is not much point in analyzing type B because both response variables are only zero and do not vary at all.
d <- read.table(textConnection("type    intact  bury
B          0     0
B          0     0
B          0     0
B          0     0
B          0     0
B          0     0
M        0.375   0
M        0.05    0
M          0     0
M          0     0
M          0    0.025
M      0.033333333  0
M          0    0.025
M          0    0.025
S        0.025   0
S          0     0
S          0    0.011111111
S      0.166666667  0
S          0    0.033333333
S      0.188888889  0.044444444
S          0        0
S          0      0.02
S          0        0
S          0        0"), header = TRUE)

As a first step one could look at the proportion of non-zeros and zeros across the three types:
plot(factor(intact == 0) ~ type, data = d)
plot(factor(bury == 0) ~ type, data = d)

This pretty much sums up the story: B is only zero and for M and S the proportion of non-zeros is about 30-40%. To analyze the difference between M and S, we can restrict the data and use a simple probit model:
d2 <- subset(d, type != "B")
d2$type <- factor(d2$type)
m1 <- glm(factor(intact > 0) ~ type, data = d2,
  family = binomial(link = "probit"))
summary(m1)
## Call:
## glm(formula = factor(intact > 0) ~ type, family = binomial(link = "probit"),
##     data = d2)
##
## Deviance Residuals:
##     Min       1Q   Median       3Q      Max
## -0.9695  -0.9383  -0.8446   1.4006   1.5518
##
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept)  -0.3186     0.4514  -0.706    0.480
## typeS        -0.2058     0.6144  -0.335    0.738
##
## (Dispersion parameter for binomial family taken to be 1)
##
##     Null deviance: 22.915  on 17  degrees of freedom
## Residual deviance: 22.802  on 16  degrees of freedom
## AIC: 26.802
##
## Number of Fisher Scoring iterations: 4

Using a tobit model (zero-censored Gaussian) instead of the probit model (binary Gaussian) leads essentially to the same non-significant results and almost the same coefficients (modulo scaling):
library("AER")
m2 <- tobit(intact ~ type, data = d2)
coef(m1)
## (Intercept)       typeS
##  -0.3186394  -0.2057611
coef(m2)/m2$scale
## (Intercept)       typeS
##  -0.3144522  -0.2342246


text:
Q: R language: Insert a map into another using ggmap I am trying to insert a map into another. And even when one time it worked, frequently I break R Studio.
First map: Luxemburgo
library(rgdal)
library(ggplot2)
library(ggmap)
library(raster)

 shapefile_lux <- getData('GADM', country='LUX', level=0)
 shapefile_lux <- fortify(shapefile_lux)

 map <- ggplot() +
        geom_path(data = shapefile_lux,
            aes(x = long, y = lat, group = group),
            color = 'red', fill = 'white', size = .2)

 map_projected <- map +
         coord_map()

 print(map_projected)

Second map: Europe
 continent <- qmap('europe', zoom = 3, source="stamen")

Third map: My problem!
 continent +
        geom_polygon(data = shapefile_df, aes(x = long, y = lat, group = group))

I tried with different combinations for
 geom_polygon(data = shapefile_df, aes(x = long, y = lat, group = group))

But, it seems to me that the problem is in way that I am using to make the combination between both maps.
The expected results is the shape of Luxemburg into the map of Europe.

A: ## Luxemburgo
data <- shapefile_lux
qmap('europe', zoom = 4, maptype = 'satellite') +
geom_polygon(aes(x = long, y = lat, group = group), data = data,
              colour = 'white', fill = 'black', alpha = .4, size = .3)


text:
Q: How to stop "aptd" from maxing out my CPU? After running the "top" command in the terminal, I see "aptd" running which causes the cpu to run at 100%. If I'm updating the system, or installing a software, I see it. I only recently noticed it. Is there anyway to stop it or tell me what is its function?

A: aptd is the service that installs software for Ubuntu Software Center and Update Manager.  It runs as a separate, background process so that the installer can have root privileges while the GUI runs under your own user ID.
You should not stop aptd while software is installing: killing it will interrupt the installation, and possibly break the package system.
If you are not installing software and still see aptd using CPU time, then it's likely that you have the system set to automatically check for updates; those automatic update checks also use aptd.

A: In addition to the above information, if you notice that it is running for a long time - say an hour or more, it may be necessary to kill it.  I ran into that when the Synaptic Package Manager appeared to be not responding for an extended period of time.  After force closing it from the GUI, I found a couple instances of aptd and several other related processes running, and eventually I had to kill them.
In my case, I found that it was necessary to run the following commands to recover:
sudo dpkg-reconfigure -phigh -a
sudo dpkg --configure -a


text:
Q: Meaning of "PC" in "PC Engine"? In Japan, the TurboGrafx-16 was known as the "PC Engine".  What did the "PC" stand for?  Presumably it was not Personal Computer?

A: PC literally just means personal computer - a computer owned by a person rather than an organization like a corporation, university, or computing club. The term is roughly synonymous with microcomputer with an additional implication of a price point measured in thousands (or less) rather than tens of thousands of dollars. Contrasting terms are mainframe computer or minicomputer, describing systems physically too large for most individuals to own.
The contraction of IBM PC to just PC took place in the early 90s as the IBM PC (and more importantly, IBM-compatible PCs) came to dominate the personal computer market.
That market shift was not inevitable in 1987 when the PC Engine was released, and the domination didn't happen in Japan until even later (where you saw IBM PCs but also a lot of NEC PCs).

A: Based on these pictures, the PC Engine was meant to sit in the center of a case or housing for a personal computer.

A: Because often Japan likes the look and sound of Western names for things rather than the name actually meaning anything. Also probably to give it connotations of power and expandibility. And because it's a less stupid name than TurboGrafx.


text:
Q: Не работает Loader android Битый час не могу понять почему студия подчеркивает return new ProfessionListLoader(MainActivity.this); и не дает запустить приложение.
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.tanat.english_for_professions.R;
import com.tanat.english_for_professions.loader.ProfessionListLoader;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<String>> {
    private int LOADER_ID = 0;

    @BindView(R.id.professionList)
    ListView professionList;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        loadData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public Loader<ArrayList<String>> onCreateLoader(int id, Bundle args) {
        return new ProfessionListLoader(MainActivity.this);
    }

    @Override
    public void onLoadFinished(Loader<ArrayList<String>> loader, ArrayList<String> data) {

    }

    @Override
    public void onLoaderReset(Loader<ArrayList<String>> loader) {

    }

    private void loadData() {
        ArrayList data = null;
        if (data == null || data.size() == 0) {
            getSupportLoaderManager().initLoader(LOADER_ID, null, this);
        } else {
            createListAdapter(data);
        }
    }

    public void createListAdapter(ArrayList data) {
        ArrayAdapter<String> adapter;
        if (data != null) {
            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
            professionList.setAdapter(adapter);
        }
    }
}

Loader:
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import com.tanat.english_for_professions.R;
import com.tanat.english_for_professions.utils.JsonDisperse;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class ProfessionListLoader extends AsyncTaskLoader<ArrayList<String>> {
    private Context context;

    public ProfessionListLoader(Context context) {
        super(context);
        this.context = context;
    }

    String jsonString = "";
    InputStream inputStream;
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    @Override
    public ArrayList<String> loadInBackground() {
        try {
            URL url = new URL("url-url-url");

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            inputStream = url.openConnection().getInputStream();
            StringBuffer buffer = new StringBuffer();
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            jsonString = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        Log.d("loader", jsonString);
        JsonDisperse jsonDisperse = new JsonDisperse();
        jsonDisperse.saveStaticString(jsonString);

        try {
            return jsonDisperse.getListProfession(Integer.parseInt(context.getString(R.string.language)));
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Если навести простит context, но я же его и даю.

Помогите пожалуйста.

A: В общем проблему решило замена строчки:
public class ProfessionListLoader extends AsyncTaskLoader<ArrayList<String>> {

на:
public class ProfessionListLoader extends android.support.v4.content.AsyncTaskLoader<ArrayList<String>>{

До сих пор не пойму почему так.


text:
Q: Compass not working on some devices We recently released an Android port of an iPhone app.  The app relies on the digital compass for some features.  This has been working well on most devices, but there are a few where the compass is not working. For the description it seems the device is not feeding us any onSensorChanged() messages.
A couple of devices that seem problematic are:
HTC Desire on Android 2.2
Motorola Droid on Android 2.2.3
They claim that other apps that make use of the compass work fine.
We start the compass using:
    if ( magnetometer != null && accelerometer != null )
    {
        if ( compassOn )
        {
            sensorManager.registerListener( this, accelerometer, (int) (1000000 / kSensorUpdateFrequencyFast) );
            sensorManager.registerListener( this, magnetometer, (int) (1000000 / kSensorUpdateFrequencyFast) );
        }
        else
        {
            sensorManager.registerListener( this, accelerometer, (int) (1000000 / kSensorUpdateFrequencySlow) );
            sensorManager.registerListener( this, magnetometer, (int) (1000000 / kSensorUpdateFrequencySlow) );
        }
    }

Where the magnetometer and accelerometer are initialized at program startup using:
    sensorManager = (SensorManager) getSystemService( SENSOR_SERVICE );
    accelerometer = sensorManager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
    magnetometer = sensorManager.getDefaultSensor( Sensor.TYPE_MAGNETIC_FIELD );

Now the above code indicated that registration doesn't happen if either accelerometer == null or magnetometer == null.  I'm pretty sure the magnetometer is not null because if it is we hide the compass feature.  So maybe the accelerometer is null on these phones?
The code in my onSensorChanged() is pretty standard and is based on the countless examples you can find on the web.
So does anyone have any thoughts on why the compass code might not be working on those devices?

A: I did figure this out.  Turns out that in 2.2 you can't use sensor rates other than the standard SENSOR_DELAY_UI, SENSOR_DELAY_NORMAL, etc.  The documentation claims you can also specify the number of microseconds between notifications, but they are lying.
Once I used the standard constants it started working on 2.2

A: You've not explained what it means, that compass is not working.
If you don't get valid data, it may be well known problem with this devices. With mine, I need always roll it in hands (both horizontally and vertically) to unlock compass. Some apps call it calibration but for me it is something absurd... I have HTC Desire.


text:
Q: King James Bible archaic style I am currently reading the King James Version of the Bible and I have noticed some features that I would like to know more about.

*

*Almost every verse of the First Book of Moses starts with "and". Does this style have a specific name? What was the reason that led to its usage? Is it acceptable to use it nowadays when trying to achieve an archaic impression or is this exclusive to the Bible?

1:3 And God said, Let there be light: and there was light.

*Beginning with 2:4, instead of using simply the word "God", "LORD God" is used. What is the reason for capitalisation of every letter in the word "LORD"? Why is the latter form used rather that the previous?

2:7 And the LORD God formed man of the dust of the ground, and breathed into his nostrils the breath of life; and man became a living soul.

A: The answer to your first question probably lies in the fact that the Old Testament is translated from Hebrew. Arabic frequently begins sentences with and. I wouldn't be surprised if the other main Semitic language did the same.
We might need a biblical scholar to answer your second question. It is, I'd hazard, to do with the respect due to the Almighty, just as some people begin pronouns referring to God with a capital letter.
(If you're interested in other linguistic aspects of the King James Bible, I recommend David Crystal's 'Begat'.)

A: *

*As Robert Alter explains in the preface to his translation of Genesis, this is an example of parataxis -- a syntax in which parallel clauses are linked by "and." Alter notes: "...parataxis is the essential literary vehicle of Biblical narrative."

*This reference notes that LORD is the English translation of the Tetragrammaton -- YHWH, the name of God.

A: This example of Hebrew narrative uses the וַ (translated and) conjunction more frequently than does English. Therefore  a faithful translation will include more ands than we would usually use.  This excess is called polysyndeton, especially when it occurs many times in a sentence:

Polysyndeton is the use of several conjunctions in close succession, especially where some might be omitted (as in "he ran and jumped and laughed for joy"). [...]
Polysyndeton is used extensively in the King James Version of the Bible. For example:

*

*And every living substance was destroyed which was upon the face of the ground, both man, and cattle, and the creeping things, and the fowl of the heaven; and they were destroyed from the earth: and Noah only remained alive, and they that were with him in the ark. Genesis 7:22-24

The style of using short sentences is called parataxis:

Parataxis is a literary technique, in writing or speaking, that favors short, simple sentences, with the use of coordinating rather than subordinating conjunctions.

To address your second question: LORD in all caps is used to distinguish lord (as in master) from  יהוה (Yhvh), the Hebrew name for God.  The -יּ (Yah) by itself is translated God.

A: One thing you have to realise is that the Bible was not originally written in English. It sounds silly when said, but you'd be surprised how many people miss this point. So what you have stumbled over isn't really issues with English, but with the underlying base language (Hebrew).
You might consider asking this over on the Hermeneutics SE site, but my understanding is that Genesis actually contains two separate creation stories. Scholars believe they were written at different times in Jewish history, the second being written during the Babylonian Exile. As such, they are apt to use the language a bit differently.
The King James translators were just rendering it all into English as best they could.

A: The style of usage with repeated "and" is arguably polysyndeton, as someone else pointed out, however, it is really more to do with the general idiom of Hebrew. Hebrew is a very different language than English, and it would be a mistake to try to project English rules and idioms (such as never start a sentence with "and") onto that language. It is worth remembering, for example, that early Hebrew texts did not have any punctuation, so the idea of "sentence" is rather different in early Hebrew.
A case might be made that the translators should have rendered the Hebrew idiom better into English idiom, as is done in many modern translations, but that is a subtle question about what "translation" means, and is way out of scope for this discussion forum.
As to whether using this polysyndeton structure in English conveys an archaic meaning, personally I don't think so. There are many other features of the KJV that do this better, such as the use of "thee" and its friends, the more diverse verb conjugations, and the unusual sentence structures. The repeated use of "and" — not so much.
I can comment more extensively on "LORD". This is a translation of the Hebrew word commonly transliterated as either Jehovah or Yahweh. In fancy circles they call it the tetragrammaton — which simply means "four letters," but is long and intimidating enough to keep out the riff raff. It is a four letter word used, arguably, as the personal name of God throughout the Bible. In the traditional reading of the Hebrew Bible this word was always considered too holy and pure to actually pronounce, and so they used a technique called kitiv-qere. This means "written/read", and essentially means that the word is written one way but pronounced a completely different way. In this case, the word is pronounced not as Yahweh but as Adonai, which is the Hebrew word for "Lord."
This tradition is also projected into the Greek of the New Testament and a Greek version of the Old Testament called the Septuagint which is commonly quoted in the New Testament.
When the English translators translated the Bible into English they wanted to respect this tradition so they translated it as it would have been read as the word "Lord", but to indicate that it was Yahweh and not Adonai which is to say that it referred to as the name of God, they distinguished it by capitalizing it.
There are some places where the grammar doesn't allow this, usually where Yahweh is preceded by Adonai. Translating The Lord LORD God..." seemed a bit redundant. So in these cases the kitiv/qere was to pronounce it as "Elohim", the Hebrew word for God. In these cases, you will see it translated as GOD in capital letters, usually it is Lord GOD.
There is a lot more to this than would be appropriate to convey in this answer. If you are interested in this, you should read the translators introduction to any modern Bible which will tell you more than you wanted to know.  Alternatively, check out Wikipedia on tetragrammaton for a great article on the subject.
The difference in the first chapter of Genesis reflects the underlying Hebrew fairly accurately. There is a theory as to why they are used differently. It is called the JEDP theory, or "The Documentary Hypothesis." Personally I think it is bunk, but Google and Wikipedia will tell you all you want to know about it.

A: To answer the second point first:
If you read the Genesis 1:1-2:3 as the first Genesis account, which was passed onto Adam, then Adam's account begins:

Genesis 2:4 These are the generations of the heavens and of the earth when they were created, in the day that the LORD God made the earth and the heavens,

and continues to:

Genesis 4:26 And to Seth, to him also there was born a son; and he called his name Enos: then began men to call upon the name of the LORD.
Genesis 5:1 This is the book of the generations of Adam. In the day that God created man, in the likeness of God made he him;

followed by a genealogy including the death of Adam in Genesis 5:5.
This pattern of "These are the generations of" marking the end of a book continues for a total of about 11 Genesis authors. At least that seems to be its natural structure.
It makes sense then that Adam refers to God as LORD, which in the King James bible is Jehovah (see Genesis 22:14;Exodus 6:3;17:15;Judges 6:24;Psalms 83:18;Isaiah 12:2;26:4) and God, the creator, refers to himself as simply God.
The accounts then are more easily reconciled. The first six days are described in Genesis 1. Adam, created on the sixth day, describes the events where God makes a garden, and makes one of each animal to see what he would call them. The creation of Eve from Adam's rib, is also mentioned and adds detail.
Additionally we may now read God ending his "work" in a rather more literal way if you see the connection of "work" with "word". God simply ended his account on the seventh day, and passed it to Adam.
What we call work, in the King James is called "labour". If you examine passages that make reference to "work", for example:

John 10:32 Jesus answered them, Many good works have I shewed you from my Father; for which of those works do ye stone me?

It makes sense to me that he was talking about the words he had given. I don't think he was talking about furniture.
To the first question I would merely observe that "AND" may be taken as a Fatherly pun which might make sense if you remember the original Hebrew is written right to left. It would be disappointing to me if the book beginning "Genes" "is" did not say anything about genes.


text:
Q: Drawing sprites in libgdx I get a NullPoinerExecption when calling
enemy.getSprite().draw(batch);

Where do I have to initialize my sprite?
It works in main class, but if I try to initialize texture and sprite in Enemy constructor then it gives me error.
Here's my main class:
  public class SpaceShooter implements ApplicationListener {

     private SpriteBatch batch;
        private Texture texture;
        private Sprite sprite, spriteEnemy;
        private Player p;
        private Enemy enemy;

        @Override
        public void create() {
            p = new Player();
            enemy = new Enemy(spriteEnemy);

            float w = Gdx.graphics.getWidth();
            float h = Gdx.graphics.getHeight();

            batch = new SpriteBatch();

            texture = new Texture(Gdx.files.internal("craft.png"));
            sprite = new Sprite(texture);
            sprite.setPosition(w/2 -sprite.getWidth()/2, h/2 - sprite.getHeight()/2);

            // Adding enemy sprite

        }

        @Override
        public void dispose() {
            batch.dispose();
            texture.dispose();
        }

        @Override
        public void render() {
            Gdx.gl.glClearColor(1, 1, 1, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

            // moving sprite left and right

            batch.begin();
            sprite.draw(batch);
            enemy.getSprite().draw(batch);
            batch.end();
        }

Enemy class
 public class Enemy {

    private Sprite sprite;
    private Texture texture;

    boolean gameOver;

    public Enemy(Sprite sprite){

        this.sprite = new Sprite();

    }

    public Sprite getSprite(){
        return sprite;
    }

    public void create() {
        texture = new Texture(Gdx.files.internal("enemy.png"));
        sprite = new Sprite(texture);
        this.sprite.setPosition(100, 200);
    }

A: You never called create() on your Enemy instance, so the texture and sprite in Enemy are never instantiated.  Call enemy.create() in your create() method. Or simplify things and move the code in enemy.create() into the Enemy constructor.
Also, in your Enemy constructor, you are instantiating a useless Sprite instance that does not reference a Texture and which will be thrown away once create() is called on the enemy. And the constructor does not even use the Sprite reference that's passed in (although you are currently just passing in null anyway because spriteEnemy in the SpaceShooter class is never instantiated).


text:
Q: How to return HTTP 400 response in Django? I want to return a HTTP 400 response from my django view function if the request GET data is invalid and cannot be parsed.
How do I do this? There does not seem to be a corresponding Exception class like there is for 404:
raise Http404

A: From my previous comment :
You can return a HttpResponseBadRequest
Also, you can create an Exception subclass like Http404 to have your own Http400 exception.

A: You can do the following:
from django.core.exceptions import SuspiciousOperation
raise SuspiciousOperation("Invalid request; see documentation for correct paramaters")

SuspiciousOperation is mapped to a 400 response around line 207 of https://github.com/django/django/blob/master/django/core/handlers/base.py

A: If you're using the Django Rest Framework, you have two ways of raising a 400 response in a view:
from rest_framework.exceptions import ValidationError, ParseError

raise ValidationError

# or
raise ParseError

A: Since Django 3.2, you can also raise a BadRequest exception:
from django.core.exceptions import BadRequest

raise BadRequest('Invalid request.')

This may be better in some cases than SuspiciousOperation mentioned in another answer, as it does not log a security event; see the doc on exceptions.


text:
Q: DocumentBuilder gives java.net.MalformedURLException: no !/ in spec I have a XML file in my resources folder. This is what I have been trying:
First get the file from the resources folder :
ClassLoader classLoader = ParseXML.class.getClassLoader();
File file = new File(classLoader.getResource("sample.xml").getFile());

Then use the DOM parse to read the file:
    DocumentBuilder dBuilder = null;
    Document doc =null;
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dBuilder = dbFactory.newDocumentBuilder();
    doc = dBuilder.parse(file)

    doc.getDocumentElement().normalize();
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

It keeps giving me "java.net.MalformedURLException: no !/ in spec". What am I doing wrong?
I also tried doing this :
fileAsString = IOUtils.toString(classLoader.getResourceAsStream("sample.xml"));
doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(fileAsString.getBytes("utf-8"))));

but error stays the same. Any help will be appreciated. Thank You.
As requested, including the stack trace :
java.net.MalformedURLException: no !/ in spec
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at com.northwestern.XMLParse.ParseXML.main(ParseXML.java:47)
Caused by: java.lang.NullPointerException: no !/ in spec
    at sun.net.www.protocol.jar.Handler.parseAbsoluteSpec(Unknown Source)
    at sun.net.www.protocol.jar.Handler.parseURL(Unknown Source)
    ... 18 more

A: From your comment, the XML file contains this line:
<!DOCTYPE Policies PUBLIC "-//OpenSSO Policy Administration DTD//EN" "jar://com/sun/identity/policy/policyAdmin.dtd">

The exception occurs because a jar: URL always takes the form jar:jar-url!/jar-entry-path, so "jar://com/sun/identity/policy/policyAdmin.dtd" is not a valid URL.  An example of a valid URL would be: jar:http://www.example.com/lib/dtds.jar!/com/sun/identity/policy/policyAdmin.dtd
Of course, the ideal solution would be to fix the XML file, or tell its authors to fix it.  But it sounds like you don't have that option.
The first thing I would try is to inhibit dereferencing of the system ID by adding dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); to your code, before you create a DocumentBuilder.  But, as your comment says, that doesn't seem to work.
The next thing I would try is dbFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");, though I suspect the implementation will try to convert the DOCTYPE's system ID to a URL regardless, which means setAttribute won't help either.
It's possible that this was someone's misguided attempt to specify a classpath resource as a URL (which cannot be done without knowing the location of the containing .jar file).  You might be able to account for their mistake by setting an EntityResolver:
dBuilder.setEntityResolver(new EntityResolver() {
    @Override
    public InputSource resolveEntity(String publicID,
                                     String systemID)
    throws SAXException,
           IOException {

        if (systemID.startsWith("jar:") && !systemID.contains("!/")) {
            String path = systemID.replaceFirst("^jar:/*", "/");
            return new InputSource(ParseXML.class.getResourceAsStream(path));
        }
        return null;
    }
});


text:
Q: Notifications are not shown when the app is closed, how can I fix it? It successfully shows notifications when the app is open. It shows even when the app is in the background. When I close the app it doesn't show up anymore. I don't want to use FCM. because I want to remember this when doing other applications. In a video, she said that the service above Android 8 does not work permanently, and that startForeground () should be used as a solution for this.But I don't want to use it because it creates a permanent notification on top
class MyFirebaseMessagingService : Service() {

private val channelId = "notification_channel"
private val channelName = "com.dombikpanda.doktarasor.service"
private val notificationTitle = "Sorunuz Cevaplanmıştır"
private val notificationMessage =
    "Doktor tarafından sorunuz cevaplanmıştır.Görmek için tıklayınız"
private var importance = 0
private var notifManagerId = 0

override fun onBind(intent: Intent): IBinder? {
    return null
}

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    questionNotification()
    return START_STICKY
}

override fun onDestroy() {
    super.onDestroy()
}

override fun onCreate() {
    createNotifChannel()
    super.onCreate()
}

private val crudRepository = CrudRepository()
private fun questionNotification() {
    val shared = getSharedPreferences("kontrol", MODE_PRIVATE)
    val control = shared.getLong("date", 0)
    val collection = Firebase.firestore.collection("questions")
    collection
        .addSnapshotListener { value, error ->
            error.let {

            }
            value?.let { result ->
                for (document in result) {
                    if (document["userid"] == crudRepository.getFirebaseAuth().uid) {
                        if (document["cevapdurum"] == true && document["messageDurum"] == true && document["date"] == control) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                createNotification()
                            }
                            break
                        }
                    }
                }
            }
        }
}

private fun createNotifChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        importance = NotificationManager.IMPORTANCE_HIGH //normal high
        val notificationChannel =
            NotificationChannel(channelId, channelName, importance).apply {
                description = notificationMessage
            }
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.createNotificationChannel(notificationChannel)
    }
}

@RequiresApi(Build.VERSION_CODES.O)
private fun createNotification() {
    val intent = Intent(this, MainActivity::class.java).apply {
        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    }
    val pendingIntent: PendingIntent =
        PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
    val notification = NotificationCompat.Builder(this, channelId)
        .setSmallIcon(R.drawable.ic_stat_name)
        .setContentTitle(notificationTitle)
        .setContentText(notificationMessage)
        .setAutoCancel(true)
        .setOnlyAlertOnce(true)
        .setStyle(NotificationCompat.DecoratedCustomViewStyle())
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setVibrate(longArrayOf(1000, 1000, 1000, 1000))
        .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
        .setContentIntent(pendingIntent)
    with(NotificationManagerCompat.from(this)) {
        notify(notifManagerId, notification.build())
        notifManagerId++
    }
}
}


text:
Q: Grails login doesn't work I'm new to Grails, and having a problem that is no doubt trivial, but I cannot find anything online!
I have a class:
package lib

class Login {

  String name
  String email
  String password
  String phonenumber

  static constraints = {
  }

}

In my Bootstrap file I create two instances of this class:
new Login(email:"tom", password:"password1")
new Login(email:"ian", password:"password2")

Now I have set up a Login form and I am trying to loop over these values and do something if they match:
def submit() {

  def result = Login.findAll { email == params.email && password == params.password }
  if (result.size() > 0) {
    println "good login"
  }
  else {
    println "bad login"
  }

  // some other stuff
}

The problem is that it is printing "bad login" every time, every when the entered email and password match those declared in the Bootstrap file. It's probably just a misunderstanding on my end, but I can't figure it out!
Thanks.

A: phonenumber and name are null in your initialisation. Therefore the users cannot be persisted in your bootstrap.groovy. Double check, that save works:
def login1 = new Login(..)
if (!login1.save()) {
    log.error("Login cannot be persisted: " + login1.errors);
}


text:
Q: How to convert time in YYYY-MM-DDTHH:mm:ss.SSSZ format to default timezone? The time that I am getting is in the format "2011-07-31T08:16:37.733Z". Actually the Z should be the timezone and then that time is converted to local timezone. How do I actually convert this time to default timezone now.

A: RFC 3339 describes a specific ISO 8601 'profile' for date/time representation.
If using 3rd-party open-source libraries is an option, take a look at Joda-Time's ISODateTimeFormat utility class.
Otherwise, if you need to roll out your own code it's not enough to use a SimpleDateFormat because of the way ISO 8601/RFC 3339 represents timezone information.
If all you need to parse is in 'Z' (Zulu or UTC), then it's relatively simple:
String input = "2011-08-11T01:23:45.678Z";
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
f.setTimeZone(utc);
GregorianCalendar cal = new GregorianCalendar(utc);
cal.setTime(f.parse(input));
System.out.println(cal.getTime());

Should print out "2011-08-11T01:23:45.678Z" in your local time zone.
If you need to handle arbitrary timezones in RFC 3339 then you'll need to extend the above to parse out the timezone designator and retrieve the corresponding Java TimeZone instance. That shouldn't be too hard if it's just whole hours +/- GMT, but in case of non-standard offsets you may have to create your own SimpleTimeZone instance.

A: private static SimpleDateFormat DATE_TIME_FORMAT=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

DATE_TIME_FORMAT.setTimeZone(TimeZone.getID()); //for example
date=DATE_TIME_FORMAT.format(curDate);


text:
Q: What is the difference between CPU Revision and Revision fields for arm processors? Making a cat /proc/cpuinfo on Android returns this kind of output:
    Processor   : ARMv7 Processor rev 1 (v7l)
    processor   : 0
    BogoMIPS    : 38.00

    processor   : 1
    BogoMIPS    : 38.00

    processor   : 2
    BogoMIPS    : 38.00

    processor   : 3
    BogoMIPS    : 38.00

    Features    : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32
    CPU implementer : 0x51
    CPU architecture: 7
    CPU variant : 0x2
    CPU part    : 0x06f
    CPU revision    : 1

    Hardware    : Qualcomm MSM8974PRO-AC
    Revision    : 0000
    Serial      : 0000000000000000

I do not find the meaning difference between those two fields:

*

*CPU revision

*Revision

A: CPU revision: It Indicates patch release or "minor revision". In your case it is 1. So this value is specific to your CPU. You can see that CPU revision is matching to Processor   : ARMv7 Processor rev 1 (v7l)
You can refer to attached image for the details of other filled as well.

Revision: It is related to your hardware (board) configuration. In your case your are using the Qualcomm hardware so revision number depends upon on it. It is independent of the CPU revision number.


text:
Q: Proving the identity $\frac{1}{\tan x}+\tan x=\frac1{\sin x\cos x}$ As I'm working on my trigonometry exercises, I come across an exercise called "prove the equality," which I proceed to solve. This all goes well, until I arrive at a certain point, after which I can't solve any further and don't understand the explanation offered in the answers section. If you would please help me understand the way of thinking needed to solve this question, I'd be very happy!
Here's the problem:

Solve the equality:

$$\frac1{\tan(x)} + \tan(x) = \frac1{\sin(x)\cdot\cos(x)}$$
And here's what I've solved for:
$$\text{RHS}=\frac{1}{\frac{\sin(x)}{\cos(x)}} + \frac{\sin(x)}{\cos(x)} =\frac{\cos x}{\sin x} +\frac{\sin(x)}{\cos(x)}$$
Then, I get stuck. The answers section says the next step should be:
$$\frac{\cos^2(x) + \sin^2(x)}{\sin(x) \cdot \cos(x)} = \text{RHS}$$
I understand how this proves the equality, but I don't understand how they just went from the previous step to this one: where do the exponents suddenly come from??
If you would be so kind as to explain this sudden raise of powers to me... My gratitude will be infinite!
Thanks in advance
Lila

A: Way of thinking: You want to simplify the more complicated side, which is the LHS, to a less complicated expression. You have two fractions with different denominators. So you multiply the numerator and denominators of the two fractions to obtain a common denominator.$$\frac1{\tan x}+\tan x=\frac{\cos x}{\sin x}+\frac{\sin x}{\cos x}=\frac{\cos^2 x}{\cos x\sin x}+\frac{\sin^2 x}{\sin x\cos x}=\frac{\cos^2 +\sin^2x}{\sin x\cos x}$$

A: We simply have
$$\frac1{\tan x}+\tan x=\frac{\cos x}{\sin x}+\frac{\sin x}{\cos x}=\frac{\cos^2 x+\sin^2 x}{\sin x\cos x}$$


text:
Q: How to lazy load multiple components at a same time in React const {A, B, C, D} = React.lazy(() => import("../test"));

Destructuring multiple components from one folder and applying lazy to all the components? Is this possible?

A: What you have described specifically is not possible.
It is in theory possible to destructure an import, but you wouldn't be able to interact with it outside of the closure passed to lazy because it isn't available yet. Remember, dynamic imports are not a function of React, but the browser. You can destructure a dynamically imported module, but to do so would require using await.
const {A, B} = await import('your/module');

In the context of React this would halt all execution in the file, which obviously is not what we want.
In order for it behave properly, you would need to destructure within the lazy callback.
I have not been able to test this, but in theory it should work:
const ComponentA = React.lazy(() => {
    const {A} = await import("../test");
    return A
})

const ComponentB = React.lazy(() => {
    const {B} = await import("../test");
    return B
})


text:
Q: How to parse the next xml using XPath in java?I want to extract the cue and the xscope from a sentence? This is my java code:
class SentenceNode {
    Node xscope;
    Node cue;
}

List<SentenceNode> getSentenceNodes(InputSource is) {
    List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
    try {

        Object xscopes = XPathFactory
                .newInstance()
                .newXPath()
                .evaluate("//xscope/cue", is,
                        XPathConstants.NODESET);
        if (xscopes != null) {
            NodeList cuesNodes = (NodeList) xscopes;
            for (int i = 0; i < cuesNodes.getLength(); i++) {
                SentenceNode sentenceNode = new SentenceNode();
                Node cue = cuesNodes.item(i);
                sentenceNode.cue = cue;
                NodeList xscope = cue.getParentNode().getParentNode()
                        .getChildNodes();
                for (int j = 0; j < xscope.getLength(); j++) {
                    Node n = xscope.item(j);
                    if (n.getNodeName().equals("xscope")) {
                        sentenceNode.xscope = n;
                        break;
                    }
                }
                sentenceNodes.add(sentenceNode);

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sentenceNodes;
}

public void displaySentenceNodes() throws ClassNotFoundException, ClassCastException,
        IOException {
    InputSource is = new InputSource(new StringReader("TestBIO.xml"));
    List<SentenceNode> nodes = getSentenceNodes(is);
    for (SentenceNode node : nodes) {

        System.out.println("Xscope: " + node.xscope.getTextContent());
        System.out
                .println("Cue: " + node.cue.getTextContent());

    }

I want to extract from this xml the sentence with its cue and xscope.For each sentence I want to obtain the xscope and cue.If the sentence has more xscopes and more cues I want to obtain all.
 Here is my xml:
   <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Annotation created="22/2/2010" creator="BioscopeWriterCasConsumer">
<DocumentSet>
        <Document type="Biological_abstract">
            <DocID type="PMID">1984449</DocID>
                <DocumentPart type="AbstractText">
                <sentence>When cells were infected with HIV, no induction of NF-KB factor was detected, <xscope>whereas high level of progeny virions was produced, <cue>suggesting</cue> that</xscope>.</sentence>
                <sentence> HIV <xscope><cue>could</cue> mimic some differentiation/activation stimuli allowing nuclear NF-KB expression</xscope>.</sentence>
                </DocumentPart>
        </Document>
</DocumentSet>
</Annotation>

An error occured when I am trying to parse the xml file.
[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown Source)

A: You are missing ? Character in xml. Should start:
  <?xml version="

A: I found the equivalent.Is like XPath but parse the xml with DOM parser bottom-up
Here is the code:
  class SentenceNode {
            Node xscope;
            Node cue;
        }

List<SentenceNode> extractElem(String file) throws ParserConfigurationException,
            SAXException, IOException {
        List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse("Test1.xml");
        document.getDocumentElement().normalize();
        NodeList nList = document.getElementsByTagName("cue");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            SentenceNode sentNode = new SentenceNode();
            Node nodeCue = nList.item(temp);
            sentNode.cue = nodeCue;
            NodeList xscope = null;
            if(nodeCue.getParentNode().getParentNode().getNodeName().equals("sentence")){
                 xscope = nodeCue.getParentNode().getParentNode()
                        .getChildNodes();
            }
            else if(nodeCue.getParentNode().getParentNode().getNodeName().equals("xscope")){
                 xscope = nodeCue.getParentNode().getParentNode().getParentNode()
                        .getChildNodes();
            }
            for (int j = 0; j < xscope.getLength(); j++) {
                Node n = xscope.item(j);
                if (n.getNodeName().equals("xscope")) {
                    sentNode.xscope = n;
                    break;
                }
            }

            sentenceNodes.add(sentNode);
        }
        return sentenceNodes;
    }

And it worked


text:
Q: How to change DevExpress MVC Grid header text on export to vertical (from bottom to top) I'm using DevExpress v14.1 to export the grid content as an image.
The whole functionality is working, I even got the header to show in vertical mode
settings.SettingsExport.RenderBrick += (s, e) => {
            if (e.RowType == GridViewRowType.Header)
            {
                e.BrickStyle.StringFormat = new DevExpress.XtraPrinting.BrickStringFormat( StringFormatFlags.DirectionVertical | StringFormatFlags.NoClip | StringFormatFlags.NoWrap);
                return;
            }
            else if (e.RowType != GridViewRowType.Data)
            {
                return;
            }

But I got the text starting at the top of the header and going to the bottom, and I want it the other way, going from the bottom to the top of the header.

A: That's the DevExpress forum answer.

Hello,
  As far as I understand you need to turn headers 180 degrees. I researched this scenario and found that RenderBrick does not provide the capability to do this. You can use our XtraReports suite that provides wide capabilities for export and allows the grid export. See the Create a Table Report documentation article. Let me know if you need any further assistance.
As for your second question, the cell size is calculated earlier than RenderBrick is raised based on cell content. RenderBrick allows customizing the exported text style but without changing cell size. So, your workaround is appropriate in this case.

That's the forum link


text:
Q: Data Migration to Cassandra using REST End points I need to fetch the data using REST Endpoints(returns JSON file) and load the data(JSON) into Cassandra cluster which is sitting on AWS.
This is a migration effort, which involves millions of records. No access to source DB. Only access to REST End points.

*

*What are the options I have?

*What is the programming language to use?(I am thinking of Python or any scripting language)?

*Since I will have to migrate millions of records, I would like to process the jobs concurrently.

*What are the challenges?

Thanks for the time and help.
--GK.

A: Cassandra 2.2.0 give feature to insert and get data as JSON .So you can use that .
Like for insert json data .
CREATE TABLE test.example (
    id int PRIMARY KEY,
    id2 int,
    id3 int
) ;
cqlsh >  INSERT INTO example JSON '{"id":10,"id2":10,"id3":10}' ;
For Select data as Json :
cqlsh >  SELECT json  * FROM  example;
 [json]
{"id": 10, "id2": 10, "id3": 10}


text:
Q: Can I have Mac, Windows, and linux share a git repo without line ending horror? Okay everyone: I'm setting up a git repository for researchers to share scripts and data for a research project. The researchers aren't programmers or particularly git-savvy, so I'm hoping to point desktop git clients at a shared repository — everyone has access to this in their local filesystem.
The problem: line endings. We have people using:

*

*Windows (mainly R) (CRLF)

*linux and Mac scripts (mainly R and python) (LF only)

*Excel on Mac, saving as .CSV (CR only, yes this is an actual thing)

git's autocrlf doesn't understand Mac line endings for some reason, so that doesn't work well for me.
First, I want to track changes to these files without telling people "you can't use the tools you're familiar with" because then they will just store the data and scripts somewhere outside of the repo.
Second, I want to have the git repo not be full of stupid line ending commits and merge conflicts, because I will probably need to solve all the merge conflicts that happen.
Third, I'd like people to not have to manually run some "fix all the line endings" script because that would suck. If this is what I need to do... whatever, I guess.
Assuming "first, normalize the line endings" is the answer, any sense of which ones I should choose?
I'd thought about a pre-commit hook, but it sounds like this would involve somehow getting the same script to run on both Windows and unix, and that sounds terrible. Maybe this is a secretly practical option?
Thanks.

A: As Marek Vitek said in comments, you may need to write at least a tiny bit of code.
Second, for a bit of clarity, here's how Git itself deals—or doesn't deal—with data transformation:

*

*Data (files) inside commits is sacrosanct.  It literally can't be changed, so once something is inside a commit, it is forever.1

*Data in the work-tree can and should be in a "host friendly" format.  That is, if you're on a Mac running program Pmac that requires that lines end with CR, the data can be in that format.  If you're on a Windows box running the equivalent Pwindows that requires that lines end with CR+LF, the data can be in that format.

*Conversions to "host format" happen when files move from the index/staging-area to the work-tree.  Conversions from "host format" to "internal storage format" happen when files move from the work-tree to the index/staging area.
Most of Git's built in filters do only CRLF to LF, or LF to CRLF, transformations.  There is one "bigger" built in filter, called ident (not to be confused with indent), and you can define your own filters called clean and smudge, which can do arbitrary things.  This means you can define a smudge filter that, on the Mac (but not on Windows) will (e.g.) change LF to CR.  The corresponding Mac-only clean filter might then change CR to LF.
Note that many transformations are not data-preserving on raw binary data: there might be a byte that happens to resemble an LF, or CR, or two in a row that resemble CRLF, but are not meant to be interpreted that way.  If you change these, you wreck the binary data.  So it's important to apply filtering only to files where a byte that seems to be one of these things, really is one of these things.  You can use .gitattributes path name matching, e.g., *.suffix, to infer which files get what filters applied.
The correct filtering actions to apply will, of course, depend on the host.
Merges and "renormalize"
When doing a merge, Git normally just takes the files directly from the pure versions inside each of the commits involved.  Since it's Git (and git diff) doing interpretation of lines, you generally want these to have Git's preferred "line" format, i.e., ending with LF (it's OK if they have or lack a CR before the LF as long as all three versions feeding into a three-way merge all have the same CR-before-LF-ness).  You can use the "renormalize" setting, though, to make Git do a virtual pass through your smudge-and-then-clean filters before it does the three-way merging.  You would need this only when existing commits (base and two branch tips) that you now intend to merge, were stored in a different way from the way you have all agreed now to keep inside the permanent commits.  (I have not actually tried any of this, but the principle is straightforward enough.)

1You can remove a commit, but to do so, you must also remove all of that commit's descendants.  In practice, this means commits that have been shared / pushed, generally never go away; only private commits can go away or be replaced with new-and-improved commits.  It's difficult to get everyone who has commit a9f3c34... to ditch it in favor of the new and improved 07115c3..., even if you can get this word out to everyone.


text:
Q: Test suites from MTM not running in the expected order We are running automation using xaml builds (automationdeploymenttemplate.xaml) and we were OK with whatever order it was picking the test cases from a particular suite.
After running all the test cases from that suite, it picks the next suite in alphabetical order.
It always follows the suite ordering, but all of sudden It's not following the previous suite order and picking test cases from any suite randomly.
How can we get the suites to run in alphabetical order again?


text:
Q: C# forms - updating chart I have been getting the error message: "Collection was modified; enumeration operation may not execute."
I was able to isolate, and reproduce the error with the code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        Thread tester;
        int testNum = 0;

        public Form1()
        {
            InitializeComponent();

            tester = new Thread(threadTester);
            tester.IsBackground = true;
            tester.Start();

        }

        public void threadTester()
        {
            bool testWhile = true;

            while (testWhile)
            {
                Thread.Sleep(1);

                testNum++;

                updateChart();

            }
        }

        public void updateChart()
        {
            testChart.Series["Series1"].Points.AddXY(testNum, testNum);
        }
    }
}

After reading some other similar problems, I am guessing I am recieving this error because the program is trying to display/update the chart while simultaneously adding a datapoint to the chart collection.
I read that because I am adding points from a separate thread, I am supposed to use the Invoke method but I cannot figure out how to implement it correctly into my code.
I am hoping someone could put me on the right path to fix this issue.


text:
Q: how to resize responsive image up and down Anyone know how to resize an image up and down on click.
Example: nrk.no

A: The website you give as an example uses CSS Transitions to make some of their images grow and shrink. You can learn more about CSS Transitions at https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions
Below is a simple example using JQuery. When you click on the Google logo it will grow and when you click on it again it will shrink.
<!DOCTYPE html>


text:
Q: transpose data set followed by sorting. Then, create new data set Data set we have is here.
a=np.array([2,6,9,5])
b =np.array([0.5,3,1,4])

what I'm looking for is (sorted data points by a)
a=np.array([2,5,6,9])
b =np.array([0.5,4,3,1])

The code I've been trying and gives me an error
If you can teach me the error, it would be very appreciable. I search answers for this, but I couldn't find out. Thank you so much in advance.
import numpy as np
a=np.array([2,6,9,5])
b =np.array([0.5,3,1,4])

#transpose data points
datatemp = np.array([a, b]).T

data=sorted(datatemp, key=itemgetter(0))

a=data[:,0]
b=data[:,1]
print(a)
print(b)

A: You don't actually need to do any of this crazy transpose stuff. The function np.argsort() is designed for this kind of stuff.
a = np.array([2,6,9,5])
b = np.array([0.5,3,1,4])
arg_order = np.argsort(a)

a = a[arg_order]
b = b[arg_order]

print(a)
print(b)
#: array([2, 5, 6, 9])
#: array([ 0.5,  4. ,  3. ,  1. ])

If you look at the value of arg_order, all it is is an array of which indexes to retrieve in the correct order.
print(arg_order)
#: array([0, 3, 1, 2])

Numpy arrays can take arrays as index arguments which describe what order to retrieve what elements in. (Give me a new array with the 0th, then the 3rd, then the 1st then the 2nd elements in that order).


text:
Q: Can an inherited static function access an overridden static private data member? I am wondering about the following:
In static.h:
class Base
{
    private: static const char* className;

    public:  static const char* getClass() { return className; };

};

class Sub : public Base
{
    private: const static char* className;
};

And in static.cpp:
#include "static.h"
#include <iostream>

const char* Base::className = "Base";
const char* Sub ::className = "Sub";

int main() {    std::cout << Sub::getClass(); }

// outputs "Base"

Is it possible to inherit such a function and have it use an overridden data member?

A: Yes, but this is not 'overriding', it is actually 'hiding'. The class can access its own private members, and its data members hide declarations using the same name in base classes.


text:
Q: Mean and Variance of the Area of a Circle with Uniform Radius
A circle with a random radius R∼Unif(0,1) is generated.  Let A be its area.(a) Find the mean and variance of A, without first finding the CDF or PDF of A.(b) Find the CDF and PDF of A.

So, quite obviously, we know the equation of a circle as A = ${\pi}r^2$. If we are given a uniform distribution, can we not just find $E(R)$ and then, using that value, find $E(A)$, and likewise for the variance? And, if we have $F(A)$, is this the CDF or PDF?

A: Some guide:

*

*Notice that $$\mathbb{E}(A) \neq  \pi (\mathbb{E}(R))^2$$ in general. Hence we can't say that since $\mathbb{E}(R)= \frac12$, hence $\mathbb{E}(A)=\frac{\pi}{2^2}$, this is not the right approach.

*We have,
$$\mathbb{E}(A) = \pi\mathbb{E}(R^2)$$
and to evaluate $\mathbb{E}(R^2)$, you might like use for the formula of $Var(X)=\mathbb{E}(X^2)-\mathbb{E}(X)^2$.

*To find variance of $A$, you might want to use the same formula as well.

*$F(A)$ usually denote CDF.


text:
Q: Firebase Realtime Database, how to know "synchronising" state? The server application puts an entry into FRD, and then sends an Firebase Cloud Message. I hear the notification alarm and turns on the Android phone. I see the FCM notification, but I do not see the newly added entry on the app. I wait a few seconds and then it shows up.
I think it may takes a few seconds until the app gets the onChildAdded. But how do I know if FRD is synchronising so that I can display something like "Synchronising..." so that users would not wonder why they got a notification for the new entry, but it is not showing up on the app for seconds?
override fun onCreate(savedInstanceState: Bundle?)
{
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    ...
    val database = FirebaseDatabase.getInstance()
    EntriesRef = database.getReference("entries")

    EntriesRef?.addChildEventListener(object:ChildEventListener{
        ...
        override fun onChildAdded(p0: DataSnapshot?, p1: String?)
        {
            //adds the new entry to the Recyler View
        }
    })
}