text:
Q: Adding AWS account to Trend Micro Deep Security Manager Below Lambda script is supposed to add AWS account to Trend Micro DSM (which is also in an AWS account). Endpoints are set up between the accounts allowing communication. It's failing with 400, it cannot add the account:
Logs:
2020-11-06T13:28:37.612+00:00   START RequestId: 074eff37-00cc-480b-affb-2e28f0e2a8af Version: $LATEST
2020-11-06T13:28:42.034+00:00   Assuming role: arn:aws:iam::414025531860:role/pcs-pipeline-role
2020-11-06T13:28:42.575+00:00   Assumed successfully!
2020-11-06T13:28:42.575+00:00   /var/runtime/botocore/vendored/requests/api.py:72: DeprecationWarning: You are using the get() function from 'botocore.vendored.requests'. This dependency was removed from Botocore and will be removed from Lambda after 2021/01/30. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.get() function instead.
2020-11-06T13:28:42.575+00:00   DeprecationWarning
2020-11-06T13:28:44.927+00:00   Allowing public IP for executing Lambda, 34.247.33.230/32, to temporarily call Trend DSM
2020-11-06T13:28:45.070+00:00   DONE!
2020-11-06T13:28:50.076+00:00   Logging into Trend DSM as Org tenant
2020-11-06T13:28:50.076+00:00   /var/runtime/botocore/vendored/requests/api.py:72: DeprecationWarning: You are using the post() function from 'botocore.vendored.requests'. This dependency was removed from Botocore and will be removed from Lambda after 2021/01/30. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.post() function instead.
2020-11-06T13:28:50.076+00:00   DeprecationWarning
2020-11-06T13:28:50.233+00:00   /var/runtime/urllib3/connectionpool.py:988: InsecureRequestWarning: Unverified HTTPS request is being made to host 'gdc-pcs-tre-dsmelb-fbsp95snsrjw-2115947587.eu-west-1.elb.amazonaws.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
2020-11-06T13:28:50.233+00:00   InsecureRequestWarning,
2020-11-06T13:28:50.319+00:00   200
2020-11-06T13:28:50.319+00:00   Logged in!
2020-11-06T13:28:50.319+00:00   Getting cloud accounts for Trend org tenant...
2020-11-06T13:28:50.319+00:00   /var/runtime/botocore/vendored/requests/api.py:72: DeprecationWarning: You are using the get() function from 'botocore.vendored.requests'. This dependency was removed from Botocore and will be removed from Lambda after 2021/01/30. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.get() function instead.
2020-11-06T13:28:50.319+00:00   DeprecationWarning
2020-11-06T13:28:50.493+00:00   /var/runtime/urllib3/connectionpool.py:988: InsecureRequestWarning: Unverified HTTPS request is being made to host 'xyz-abc-tre-dsmelb-fbsp95snsrjw-7443282981.eu-west-1.elb.amazonaws.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
2020-11-06T13:28:50.493+00:00   InsecureRequestWarning,
2020-11-06T13:28:50.528+00:00   Retrieved!
2020-11-06T13:28:50.528+00:00   Checking if tenant account already in Trend DSM Org Tenant
2020-11-06T13:28:50.528+00:00   Not found
2020-11-06T13:28:50.528+00:00   Adding 11994547362545 as Trend cloud account...
2020-11-06T13:28:50.528+00:00   /var/runtime/botocore/vendored/requests/api.py:72: DeprecationWarning: You are using the post() function from 'botocore.vendored.requests'. This dependency was removed from Botocore and will be removed from Lambda after 2021/01/30. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.post() function instead.
2020-11-06T13:28:50.528+00:00   DeprecationWarning
2020-11-06T13:28:50.693+00:00   /var/runtime/urllib3/connectionpool.py:988: InsecureRequestWarning: Unverified HTTPS request is being made to host 'xyz-abc-tre-dsmelb-fbsp95snsrjw-7443282981.eu-west-1.elb.amazonaws.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
2020-11-06T13:28:50.693+00:00   InsecureRequestWarning,
2020-11-06T13:28:51.373+00:00   400
2020-11-06T13:28:51.373+00:00   Failed!

`No lines are selected.
import os
import json
import time
import boto3
from botocore.vendored import requests
import layer as utils
def handler(event, context):
    try:
        # Extract the Job ID
        job_id = event['CodePipeline.job']['id']
        event_data = utils.parse_event_data(event)
        print(event_data)
        trend_micro_deep_security_integration(event_data['TenantAccountId'], event_data['Organisation'])
        utils.put_job_success(job_id)
    except Exception as err:
        utils.put_job_failure(job_id, str(err))
def trend_micro_deep_security_integration(tenant_account_id, tenant_organisation):
    #retrieve trend tenant password from ssm param store
    client = boto3.client('ssm', region_name='eu-west-1')
    TREND_TENANT_PASSWORD = client.get_parameter(Name='TrendTenantPassword', WithDecryption=True)['Parameter']['Value']
    #assume role in aws provider account for trend dsm
    sts_client = boto3.client('sts')
    trend_account_role_arn = 'arn:aws:iam::654533721364:role/{}'.format(os.environ['DEPLOY_ROLE'])
    TREND_SESSION = utils.get_sts_session(sts_client, trend_account_role_arn)
    #determine public ip of executing lambda function
    public_ip = requests.get('https://checkip.amazonaws.com').text.rstrip()
    global LAMBDA_PUBLIC_IP
    LAMBDA_PUBLIC_IP = '{}/32'.format(public_ip)
    #add lambda public ip as temp ingress cidr ip
    SG_ID = 'sg-01ct911f8ch7d2ed5'
    changed = authorize_trend_elb_ingress(TREND_SESSION, SG_ID)
    if changed:
        time.sleep(5)
    org_name = tenant_organisation.upper().strip()
    #log into trend dsm
    payload = get_trend_auth_payload_json(org_name, TREND_TENANT_PASSWORD)
    cookie = get_trend_org_cookie(org_name, payload)
    # check and if required, add tenant account into their trend tenant for the assigned org
    dsm_account_names = get_trend_org_cloud_accounts(cookie)
    if not is_account_in_trend_dsm(dsm_account_names, tenant_account_id):
        success = add_trend_cloud_account(cookie, tenant_account_id)
    else:
        success = True
    # always remove temp ingress rule
    revoke_trend_elb_ingress(TREND_SESSION, SG_ID)
    #if any error when adding account, throw exception
    if not success:
        raise Exception("Failed to add tenant as cloud account in Trend Deep Security Manager!")
    print("Trend Micro Deep Security Manager integration complete!")

## TREND DEEP SECURITY HELPER FUNCTIONS ###
def trend_sg_ingress_rule_exists(sg_rules):
    for elem in sg_rules:
        matches = [ x for x in elem['IpRanges'] if x['CidrIp'] == LAMBDA_PUBLIC_IP ]
        if any(matches):
            return True
    return False
def authorize_trend_elb_ingress(TREND_SESSION, SECURITY_GROUP_ID):
    ec2 = TREND_SESSION.resource('ec2', region_name='eu-west-1')
    elb_security_group = ec2.SecurityGroup(SECURITY_GROUP_ID)
    if trend_sg_ingress_rule_exists(elb_security_group.ip_permissions):
        return False
    print("Allowing public IP for executing Lambda, {}, to temporarily call Trend DSM".format(LAMBDA_PUBLIC_IP))
    elb_security_group.authorize_ingress(
        CidrIp=LAMBDA_PUBLIC_IP,
        FromPort=777,
        ToPort=777,
        IpProtocol='tcp',
    )
    print("DONE!")
    return True
def revoke_trend_elb_ingress(TREND_SESSION, SECURITY_GROUP_ID):
    ec2 = TREND_SESSION.resource('ec2', region_name='eu-west-1')
    elb_security_group = ec2.SecurityGroup(SECURITY_GROUP_ID)
    if not trend_sg_ingress_rule_exists(elb_security_group.ip_permissions):
        return False
    print("Revoking public IP for executing Lambda, {}, from Trend DSM ELB SG".format(LAMBDA_PUBLIC_IP))
    elb_security_group.revoke_ingress(
        CidrIp=LAMBDA_PUBLIC_IP,
        FromPort=777,
        ToPort=777,
        IpProtocol='tcp',
    )
    print("DONE!")
def is_account_in_trend_dsm(dsm_names, account_id):
    print("Checking if tenant account already in Trend DSM Org Tenant")
    for dsm_account_name in dsm_names:
        if account_id == dsm_account_name[-12:]:
            print("Found!")
            return True

    print("Not found")
    return False
def get_trend_org_cookie(org_name, payload):
    print("Logging into Trend DSM as Org tenant")
    headers = {'content-type': "application/json", 'accept': "application/json"  }
    r = requests.post(
        url = "https://xyz-abc-tre-dsmelb-fbsp95snsrjw-2912957566.eu-west-1.elb.amazonaws.com/rest/authentication/login",
        headers= headers,
        data = payload,
        verify=False
    )
    print(r.status_code)
    print("Logged in!")
    return r.text
def get_trend_auth_payload_json(org_name, org_tenant_password):
   auth = {
       'dsCredentials' : { 'userName' : 'MasterAdmin' , 'password' : org_tenant_password, 'tenantName' : org_name}
   }
   return json.dumps(auth)
def get_trend_org_cloud_accounts(cookie_string):
    cookie = {'sID': cookie_string}
    headers = {'content-type': "application/json", 'accept': "application/json"  }
    print("Getting cloud accounts for Trend org tenant...")
    r = requests.get(
        url = "https://xyz-abc-tre-dsmelb-fbsh952n1rbw-2185847414.eu-west-1.elb.amazonaws.com/rest/cloudaccounts/",
        headers= headers,
        cookies=cookie,
        verify=False
    )
    resp = r.json()['ListCloudAccountsResponse']
    print("Retrieved!")
    return [ x['name'] for x in resp['cloudAccount'] ]
def add_trend_cloud_account(cookie_string, account_id):
    cookie = {'sID': cookie_string}
    headers = {'content-type': "application/json", 'accept': "application/json"  }
    info = {}
    info['AddAwsAccountRequest'] = {}
    info['AddAwsAccountRequest']['crossAccountRole'] = {}
    info['AddAwsAccountRequest']['crossAccountRole']['roleArn'] = 'arn:aws:iam::{}:role/gdc-pcs-trend-micro-dsm-role'.format(account_id)
    info['AddAwsAccountRequest']['crossAccountRole']['externalId'] = '7F4DC12D-53B2-1BEX-7CB7-8759CDADEB71'
    print('Adding {} as Trend cloud account...'.format(account_id))
    r = requests.post(
        url = "https//xyz-abc-tre-dsmelb-fbsp95snsrjw-7443282981.eu-west-1.elb.amazonaws.com/rest/cloudaccounts/aws",
        headers= headers,
        cookies=cookie,
        data = json.dumps(info),
        verify=False
    )
    print(r.status_code)
    if r.status_code == 200:
        print("Done!")
        return True
    else:
        print("Failed!")
        return False`


text:
Q: Converting UTC to GMT I would like to convert a UNIX figure in to a GMT timestamp.
I first convert the UNIX number to UTC, but cannot seem to convert it to GMT?
For Example

Date
UNIX
Event_Unix_Timestamp
Country

2022-03-10
1646899782
2022-03-10 08:09:42 UTC
Nigeria

The query I currently have is :
SELECT
   DATE
  , EVENTUNIX
  , TIMESTAMP_SECONDS (EventUNIX) AS Event_Unix_Timestamp
  , COUNTRY
FROM TABLE
GROUP BY 1,2,3

I have tried the below function:
TIMESTAMP (DATETIME(TIMESTAMP_SECONDS(EventUNIX) , "Europe/London") ) AS Video_Event_Unix_Timestamp

and with 'GMT'

But this doesn't work.
Any help would be great! Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get these information(Organization information, user name, email address) from LDAP to Alfresco I can login to Alfresco using LDAP, but I couldn't get other information (e.g., Organization information, user name, email address...)
How can I get these information from LDAP to Alfresco?
Now, I'm using Alfresco Communnity Edition 5.0b

C:\Alfresco\tomcat\shared\classes\alfresco\extension\subsystems\Authentication\ldap-ad\ad1\
  ldap-authentication.properties

ldap.authentication.active=true
ldap.authentication.allowGuestLogin=false
ldap.authentication.userNameFormat=%sdomain.com
ldap.authentication.java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
ldap.authentication.java.naming.provider.url=ldap://AD_IP:389
ldap.authentication.java.naming.security.authentication=simple
ldap.authentication.escapeCommasInBind=false
ldap.authentication.escapeCommasInUid=false
ldap.authentication.defaultAdministratorUserNames=Administrator
ldap.synchronization.active=true
ldap.synchronization.java.naming.security.authentication=simple
ldap.synchronization.java.naming.security.principal=alfresco
ldap.synchronization.java.naming.security.credentials=Alfresc0.
ldap.synchronization.queryBatchSize=1000
ldap.synchronization.attributeBatchSize=1000
ldap.synchronization.groupQuery=(&(!(cn=00000)) (objectClass=group))
ldap.synchronization.groupDifferentialQuery=(&(objectclass=group)(!(whenChanged<={0})))
ldap.synchronization.personQuery=(&(objectClass=user)(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=512)))
ldap.synchronization.personDifferentialQuery=(&(objectClass=person)(userAccountControl:1.2.840.113556.1.4.803:=512) (!(modifyTimestamp<={0})))
ldap.synchronization.groupSearchBase=OU=Groups,dc=domaindc=COM
ldap.synchronization.userSearchBase=OU=Users,dc=domain,dc=COM
ldap.synchronization.modifyTimestampAttributeName=whenChanged
ldap.synchronization.timestampFormat=yyyyMMddHHmmss'.0Z'
ldap.synchronization.userIdAttributeName=cn
ldap.synchronization.userLastNameAttributeName=sAMAccountName
ldap.synchronization.userEmailAttributeName=mail
ldap.synchronization.userOrganizationalIdAttributeName=physicaldeliveryofficename
ldap.authentication.java.naming.read.timeout=0


text:
Q: Determining the Taylor series of $\sqrt{x}$ on $x_0 = 1$ I've attempted to determine the Taylor series of $\sqrt{x}$, centered on $x_0 = 1$. Here's what I have thus far:
$f(1) = 1$
$f'(1) = \frac{1}{2\sqrt{x}} = \frac{1}{2}$
$f''(1) = -\frac{1}{4x^{3/2}} = -\frac{1}{4}$
$f^{(3)}(1) = \frac{3}{8x^{5/2}} = \frac{3}{8}$
$\vdots$
Trivially, the Taylor series is of the form:
$$1 + \frac{1}{2(1!)}(x-1) - \frac{1}{4(2!)}(x-1)^2 + \frac{3}{8(3!)}(x-1)^3 + \cdots$$
Notice that the denominators are of the form $2^n(n!)$. We also have an alternating term, $(-1)^{n+1}$
$$\to \sum_{k=0}^{\infty} = \frac{(-1)^{k+1}(x-1)^n}{2^n(n!)}$$
When I graph this, however, it doesn't seem to be a particularly nice approximation of $\sqrt{x}$ anywhere.

A: Let $f(x)=\sqrt x=x^{1/2}$. Then:

*

*$f'(x)=\frac12x^{-1/2}$;

*$f''(x)=-\frac1{2^2}x^{-3/2}$;

*$f^{(3)}(x)=\frac{3}{2^3}x^{-5/2}$;

*$f^{(4)}(x)=-\frac{3\times5}{2^4}x^{-5/2}$
and so on… So,$$n>1\implies f^{(n)}(1)=\frac{(-1)^{n-1}(2n-3)!!}{2^n}.$$

A: What do you worry about ? The four first terms that you computed do match the square root fairly closely.


text:
Q: Mutating a slice field of a struct even though all methods are defined with value receivers
6.2 Methods with a Pointer Receiver
If all the methods of a named type T have a receiver type of T itself
(not *T ), it is safe to copy instances of that type; calling any of
its methods necessarily makes a copy. For example, time.Duration
values are liberally copied, including as arguments to functions. But
if any method has a pointer receiver, you should avoid copying
instances of T because doing so may violate internal invariants. For
example, copying an instance of bytes.Buffer would cause the original
and the copy to alias ( §2.3.2 ) the same underlying array of bytes.
Subsequent method calls would have unpredictable effects.
(The Go Programming Language Alan A. A. Donovan · Brian W. Kernighan)

I understand the general meaning of the quote, but I am wondering whether it's correct to say that is safe to copy instances of that type.
If a struct has a slice/map field then all copies receive their own copies of the pointers to the backing array/hashmap so it is still possible to mutate those data structures.
Even though all the methods might be defined using value receivers, we can break the internal state of the struct.
I understand why that happens, but doesn't that possibility contradict what is written in that paragraph above?
Copying values might have unwanted consequences regardless of the method receivers and also depends on the field types.
What am I missing here?
package main

import "fmt"

type T struct {
    s []string
}

func main() {
    original := T{s: []string{"original"}}
    copycat := original
    copycat.s[0] = "copycat"
    fmt.Println(original.s[0] == "copycat") // true
}

A: I'm neither Donovan nor Kernighan, so I can't definitively say what they were trying to communicate here, but my understanding is not that "using value receivers makes copying safe", but rather "using value receivers indicates copying is safe". You are correct that any pointer field, or any field which contains a pointer field (including slices and maps), will make copying unsafe; I believe what the authors are trying to get across is that an API which uses a value receiver is indicating to its consumers that no such fields exist.


text:
Q: iPhone - openAL stops playing if I record with AVAudioRecorder this is an iPhone-related question:
I use openAL to play some sound (I have to manage gain, pitch, etc.).
I want to record what I'm playing and I use AVAudioRecorder but when I "prepareToRecord" openAL stops to play audio.
What's the problem?
Here is the record IBAction I use:
- (IBAction) record: (id) sender
{
NSError *error;
    NSMutableDictionary *settings = [NSMutableDictionary dictionary];
    [settings setValue: [NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [settings setValue: [NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
    [settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
    [settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    NSURL *url = [NSURL fileURLWithPath:FILEPATH];
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
    self.recorder.delegate = self;
    self.recorder.meteringEnabled = YES;
    [self.recorder prepareToRecord];
    [self.recorder record];
}

Thanks
EDIT:
I tried with AudioQueue recording too.
This time sounds stops after this code:
status = AudioQueueEnqueueBuffer(recordState.queue, recordState.buffers[i], 0, NULL);

So it's possible to record when iPhone is playing with openAL???
Thanks again

A: FILEPATH is same as path where another file is being played...?
and if record and prepareToRecord are called from same place... actually you do not need to call prepareToRecord... record will do the job...
see
http://developer.apple.com/iphone/library/documentation/AVFoundation/Reference/AVAudioRecorder_ClassReference/Reference/Reference.html#//apple_ref/occ/instm/AVAudioRecorder/prepareToRecord


text:
Q: Permissions - Groups I'm having a look at Google Drive and we have instances where we will need item level permissions on files. We have groups of people would would have write access to the file. I notice that the API allows you to set permissions on a file with a group id but am unsure how to setup the group in the first place?
Could someone please advise on how to do this?
The other alternative would be to send a permission for each user but this seems like a less ideal workaround.

A: Just share with a google group which has an email.


text:
Q: Flash 10 Attaching a png file from an external swf compiled with swfmill I wish to load an external swf compiled with swfmill, at run time. In other words, loading it asynchronously (not compiled together with the file). This swf contains 2 assets: file1.png and file2.png.
It's mostly working, except for this problem: how to attach the resources in the file? Normally I would use attach()…
var _urlLoader = new URLLoader();
var _urlRequest = new URLRequest("libgfx.swf");
_urlLoader.load(_urlRequest);
_urlLoader.addEventListener(Event.COMPLETE, onComplete);

public function onComplete(e:Event) {
    trace("Received shared libgfx.swf. Length: " + _urlLoader.data.length);  // displaying the size correctly

    var displayObjectLoader:Loader = new Loader();
    displayObjectLoader.load(_urlRequest);
    var displayObject:DisplayObject = addChild(displayObjectLoader);

    // How would you attach file1.png or file2.png?
    // …?
}

Any help appreciated :)

A: *

*Convert the assets to MovieClip.

*Add Linkage for them.

*Use the following code to load it:
var context:LoaderContext       = new LoaderContext( );
    context.applicationDomain   = ApplicationDomain.currentDomain;

var loader : Loader = new Loader( );
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, complete );
    loader.load( new URLRequest( "assets.swf" ), context );

    function complete ( e:Event ) : void
    {
        var Asset : Class = e.target.applicationDomain.getDefinition("the linkage of the asset") as Class;
        var asset : MovieClip = new Asset( );
        addChild( asset );
    }

Hope this helps.
Cheers
Tamas Gronas


text:
Q: Are rooms associated with per-site-metas shown when viewing a question? I will include a rather lengthy explanation, which might be unnecessary for users familiar with the stuff I describe. Therefore:
TL;DR: Per-site-metas can have chat rooms associated with them, too. Are they shown in the side-bar when viewing the questions?
When viewing a questions, sometimes chat rooms are shown on the right in the side-bar. It might look something like this:

(Maybe you can see something similar while you are viewing this question.)
They do now always appear there. They are shown when viewing both questions on main and questions on meta. I do not know how the rooms are selected, but it seems that usually they are rooms which were active not too long ago. When I tried it now, on both main and meta I saw rooms associated with the main site.
I learned that some per-site-metas have also rooms associated with them from here: http://meta.math.stackexchange.com/questions/18990/mathematics-meta-chat-room. There are not many per-site-metas which have chat rooms. If we do not count meta.SE, which is not a per-site-meta site, then I was able to find such rooms at meta.gaming.SE, meta.matheducators.SE, meta.math.SE, meta.mathoverflow.net, meta.SF, meta.SO and meta.SU. I do not know why only some meta sites have chat rooms.
One advantage of these rooms is that for every site (which includes per-site-metas), at least one room is always left. I.e., it is not frozen even if it was inactive for 14 days. The users usually do not create rooms associated with a meta site - you can see that in examples I have linked above only one room is associated with each of those meta sites (at the moment). So unless other rooms associated with the same meta, these rooms will theoretically exist indefinitely.
Perhaps such rooms could be put to some good use. But there is a question whether users will notice them. I guess that typically when users go to chat, their view rooms associated with the site they were on. The rooms associated with meta are not shown there. So will users notice existence of a room associated with meta somewhere? This brings me finally to the question:

Are the rooms associated with per-site-meta shown too when viewing questions on main or meta? Are they perhaps shown in some other places I did not notice?

A: I have just seen this on MathOverflow:

Link to this room associated with meta.MO was shown in sidebar.
So it seems that now also the rooms associated with metas are shown there (and they are also shown among rooms associated with the site).
I guess that the behavior changed recently as a result of this: Why can meta sites be parents of chatrooms?


text:
Q: Can Percy Jackson see under deep water? I know that after 1000 meters there is no light under the sea. Could Percy Jackson see in the dark, if he was under the water?

A: Yes, he has some limited underwater vision.
This is made clear by a quote in The Last Olympian:

Beyond this, the sea floor stretched into gloom. I could see battles raging—flashes of energy, explosions, the glint of armies clashing. A regular human would've found it too dark to see. Heck, a regular human would've been crushed by the pressure and frozen by the cold. Even my heat-sensitive eyes couldn't make out exactly what was going on.
Percy Jackson and the Olympians, book 5: The Last Olympian, chapter 2: "I Meet Some Fishy Relatives" (emphasis added)

So while he can't see perfectly underwater, he does have some limited special vision.

A: Not only can Percy see better underwater than regular mortals, but he can also sense the presence of many things when they are underwater, as though he has the ability to use sonar.

I should've been blind, too,
  this deep in the water at night, but I could see the heat from living forms, and the cold of the
  currents. It's hard to describe. It wasn't like regular seeing, but I could tell where everything
  was.
Percy Jackson and the Titan's Curse -- Chapter 8: I Make a Dangerous Promise


text:
Q: css table center not working in Firefox I've centered a table using the following:
table{
margin-left: auto;
margin-right: auto;
}

It works great on Google Chrome but not at all on Firefox, any ideas?
Should I wrap the table in a Div and use a specific ID for it?
P.S I didn't use -webkit- on it. If I used -webkit-, I made sure to also add -moz-
JSFiddle
Here is a link for you guys to examine:
you can see for yourself

A: CSS
Add this to your CSS file:
header
{
    float:none!important
    /* or remove float:right; in your current CSS file */
}
#nav
{
    background:none;
    float:right
}
#tb
{
    margin:0 auto;
    width:1080px;
    border-spacing:0;
    border:0;
    border-collapse:collapse
}
.clearfix:after
{
    clear:both;
    content:'.';
    display:block;
    font-size:0;
    height:0;
    line-height:0;
    visibility:hidden
}
.clearfix
{
    display:block;
    zoom:1
}

HTML
And in your HTML code change:

to:

A: Well, it all depends on how/where your table is nested, you need either to center the content in your parent container or to center the page body, or add position:absolute; to the table css.


text:
Q: How to request write permission using Firebase Twitter Login I'm integrating Firebase Twitter Login into my web app. The idea is to allow users login to my app with their twitter account. I'm using Firebase on the backend, and it supports Twitter login out of the box.
The problem that I'm facing is that firebase requests 'read-only' permission for some reason. I need 'write' permission as well.
Here's my setup:
- created an app on Twitter and selected "Read and Write" access
- setup Firebase Twitter Auth according to the instructions
Here is my JavaScript code:
firebase.auth().getRedirectResult().then(result => {
  console.log(result.credential);
  if (result.credential === undefined) {
    const provider = new firebase.auth.TwitterAuthProvider();
    firebase.auth().signInWithRedirect(provider);
  }
})
.catch(error => {
  console.log("Login error");
});

When the user gets redirected to Twitter to login, Twitter says that the app will not be able to post any tweets. Once the user logs in, my app does show up as "read-only" in Settings->Apps.


text:
Q: The meaning of "is right up there"
Bob Dylan's first electric tour, the Velvets' Exploding Plastic
  Inevitable, the Pistols and Buzzcocks in Manchester '76. Some gigs
  continue to resonate for decades after the band leaves the stage. The
  Pink Floyd and The Soft Machine launching radical paper the
  International Times at the Roundhouse on October 15th 1966 is right up
  there.

I can't get the meaning of the last sentence. I know the construction "to be right up with" but it doesn't fit here.

A: "right up there" means near the top of the list of the best and greatest.


text:
Q: Cannot assign ws response to $scope variable I have a problem with setting result when i get a ws message.
I have a controller, when i click some button, it invokes getStops func.
In this func (getStops) i use ws connection, when i get message
(at ws.onmessage) i need to get
tramState['stop_id'] and assing it to $scope.current_stop.
And then in ul list, appropriate li should become active.
But it doesn't happen, $scope.current_stop is always null.
Where is the problem? Thanks.
angular.module('tramApp').
    controller('tramController', ['$scope', 'tramAPIService', function($scope, tramAPIService) {
        $scope.trams = [];
        $scope.stops = [];
        $scope.active_tram = null;
        $scope.current_stop = null;

    $scope.getStops = function (tram_id) {
        tramAPIService.getStops(tram_id)
            .then(stops => $scope.stops = stops);

        $scope.active_tram = tram_id;

        const ws = new WebSocket(`ws://192.168.0.103:8080/tram_ws/?tram_id=${tram_id}`);

        ws.onmessage = (message) => {
            let tramState = JSON.parse(JSON.parse(message.data));
            $scope.current_stop = (tramState['stop_id'] !== "None") ? Number(tramState['stop_id']) : null;
            console.log(tramState);
        };
    };

    tramAPIService.getTrams()
        .then(trams => $scope.trams = trams);

}]);

<ul class="list-group">
      <li
          class="list-group-item"
          ng-repeat="s in stops"
          ng-class="{'active': s.stop_id === current_stop}">
          {{ s.stop_id }}, {{ s.stop_name }}
      </li>
</ul>

A: The problem is, you are updating angular $scope varaible from outside AngularJS context, where angularjs isn't aware about those changes and hence the changes doesn't reflect in the UI. The process of updating binding w.r.t it $scope is called as digest cycle system. In this case you have to trigger this process manually to see updates on the screen.
You can trigger this process by two way

*

*By calling $apply method on $scope

*Or $timeout and $applyAsync method. (Preferred way)
ws.onmessage = (message) => {
    let tramState = JSON.parse(JSON.parse(message.data));
    $scope.$applyAsync(function(){
       $scope.current_stop = (tramState['stop_id'] !== "None") ? Number(tramState['stop_id']) : null;
    });
};


text:
Q: Shift column based on index I want to shift the column based on index.
In my example( I attached image), I just want to move index 4th to 5th column. Since 4th is named as null I could not iterate.
I have checked with following code,
if df.columns[4] != 'nan'
df.shift..
For me rows>5057 where columns got shifted.
Output: I just need to shift the column in index column 4 plus 1 and it will fine.
Please help me how to do this.
Thanks.

A: I would try this:
rows = df.iloc[:, 4].notna()
cols = slice(df.columns[4], None)

df.loc[rows, cols] = df.loc[rows, cols].shift(1, axis=1)

P.S.
If things go stranger, and there's no ways to organize your labels, then maybe it's better to use numpy.array:
data = df.values

index = ~np.isnan(data[:,4])
data[index, 5:] = data[index, 4:-1]
data[:, 4] = np.nan

df[:] = data


text:
Q: Meaning of "Would you value the ethics of consequence over means?" I've been reading a book for a while and I've stumbled on the following sentence, which I didn't quite understand:

Would you value the ethics of consequence over means?

The context is the following:
Person A steals a valuable book and doesn't tell his superiors (In the book, this is punishable by death, since he's hiding information and this act caused a war earlier), person B is As friend and doesn't do anything about the book (person B is religious).
The mentioned superiors find out about the book and thus, person A is sent to court, where person B is a witness.
Person A asks B to lie, but him being religious, isn't able to do so.
Since B didn't lie in court, but did nothing before the act of hiding the information was found out (aka "I'm all good with it until there isn't something for me to lose), is called a hypocrite by person A, so he goes through a psychological drama, before talking to person C (person C being a priest and a good friend of person B).
During the discussion, person B lets C in on his drama and gives the aforementioned question as answer to his person Bs psychological drama.

A: An ethics of consequence is one which posits that the ethical value of an action is dependent upon its outcome, or perhaps its foreseeable outcome (different ethics of consequence could disagree on how much one is culpable for an unforeseeable outcome, and questions around the difference between two or more foreseeable outcomes with different likelihoods).
An ethics of means is one which puts forward certain rules, and holds that the ethical stance is to follow them.
In practice, there are definite overlaps. One is that ethics of means often arise out of considering possible outcomes in the abstract (e.g. we could argue that the ethics of means that considers it unethical to ever drink and drive is in fact an ethics of consequence because the rule against drinking and driving is there to prevent accidents) so the difference may be primarily about when one does or doesn't decide to make exceptions to rules. An ethics of means can also include consideration of outcome, e.g. many concepts of a Just War are primarily ethics of means but also consider a war for which a victorious outcome cannot be reasonable foreseen as unethical as it can only lead to bloodshed without any benefit (some make a further of means exception for defence against invaders of ones homeland as always justifiable).
The character in your story is including the argument in favour of one or the other of these, as part of his moral wrestling over the actions he did and didn't take.


text:
Q: Built-in sorted() function in Python I saw in a book how to pass a specific sorting function to Python's own built-in sorted() function as follows:
def mysort(a, b):
    if a[3] < b[3]:
        return -1
    elif a[3] > b[3]:
        return 1
    else:
        return 0

data = [
('Alpha Centauri A', 4.3, 0.26, 1.56),
('Alpha Centauri B', 4.3, 0.077, 0.45),
('Alpha Centauri C', 4.2, 0.00001, 0.00006),
("Barnard's Star", 6.0, 0.00004, 0.0005),
('Wolf 359', 7.7, 0.000001, 0.00002),
('BD +36 degrees 2147', 8.2, 0.0003, 0.006),
('Luyten 726-8 A', 8.4, 0.000003, 0.00006),
('Luyten 726-8 B', 8.4, 0.000002, 0.00004),
('Sirius A', 8.6, 1.00, 23.6),
('Sirius B', 8.6, 0.001, 0.003),
('Ross 154', 9.4, 0.00002, 0.0005),
]

sorted_data = sorted(data, mysort)

the code above sorts the data based on the 4th element of the 4-element tuple. Here, I am trying to figure out how the sorted() function feeds the a and b arguments to the mysort function. My intention is passing another argument to the mysort function similar to:
def mysort(a, b, i):
    if a[i] < b[i]:
        return -1
    elif a[i] > b[i]:
        return 1
    else:
        return 0

where it will tell the function which element should the sorting be based on. I am confused, because in the line
sorted_data = sorted(data, mysort)

we do not pass any arguments to the mysort function. The sorted() function seems to do its own magic, and provide the a and b arguments to the mysort function. To summarize, I wonder if there is a way to add a 3rd argument to the mysort function for different sorting types?
Thank you!

A: You really want to use the key argument instead; sorting on the 4th column with operator.itemgetter():
from operator import itemgetter

sorted(data, key=itemgetter(3))

or you could use a lambda:
sorted(data, key=lambda elem: elem[3])

or you could use functools.partial():
from functools import partial

def mykeyfunc(column, item):
    return item[column]

sorted(data, key=partial(mykeyfunc, 3))

All 3 options create a new callable that is passed each item in data.
The cmp argument to sorted() has been removed in Python 3.

A: You usually don't sort with cmp (the second argument). The key argument is the best choice 99% of the time:
def mysort(item):
    return item[3]

sorted_data = sorted(data, key=mysort)

Or more concisely:
sorted_data = sorted(data, key=lambda item: item[3])

To make your second function work, you need to create a function with your function:
def mysort(i):
    def sort_func(a, b)
        if a[i] < b[i]:
            return -1
        elif a[i] > b[i]:
            return 1
        else:
            return 0

    return sort_func

And use it like:
sorted(data, mysort(3))

But a better way would be to use something builtin:
from operator imoprt itemgetter

sorted_data = sorted(data, key=itemgetter(3))


text:
Q: Webscraping Beautifulsoup remove div how do I remove the div brackets? I just want the names of the car models left: "E-Pace", "F-Pace SVR"...
Highly appreciate your input. I am new to coding so would be nice to get your solution.
Thank you
Code:
import requests
import time

#Inputs/URLs to scrape:
URL_model = ('https://carbuzz.com/cars/jaguar')
(response := requests.get(URL_model)).raise_for_status()
soup = BeautifulSoup(response.text, 'lxml')
overview = soup.find()

for car_model in soup.find_all(class_='sub-model-with-score-preview__name'):
    car_model
    print(car_model)

Output:

E-Pace

F-Pace SVR

F-Pace

I-Pace

F-Type Coupe

A: Simply use get_text() to extract the texts from your tag and use strip parameter to get rid of leasing/ trailing whitespaces or linebreaks:
print(car_model.get_text(strip=True)


text:
Q: Problem with accessing image folder in Laravel How can i access public folder image?
I imported a folder from the internet and it is not letting me implement the codes.
I am not seeing the folder images, what is the mistake?

A: You can access the public folder imported in your laravel by using:
asset() method in your blade, for example
<img src="{{ asset('img.jpg') }}" alt="">


text:
Q: Parse Image -> UITableViewCell Not Displaying (Swift) I'm struggling to get an image stored in Parse to display in my UITableViewCell. The cell is being populated from other data stored in the Parse object (name, etc) - just the image isn't displaying correctly.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")

    cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator

    if let client: PFObject = self.clientList[indexPath.row] as? PFObject {
      let forename: String = client["forename"] as! String
      let surname: String = client["surname"] as! String
      let fullname: String = forename + " " + surname
      cell.textLabel?.text = fullname

      cell.detailTextLabel?.text = client.objectId

      let userImageFile = client["image"] as? PFFile
      if let imageFile = userImageFile {
        println(imageFile)
        imageFile.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
          if error == nil {
            if let imageData = imageData {
              self.image = UIImage(data: imageData)!
            }
          }
        })
    // THIS DOESN'T DISPLAY AN IMAGE WHEN RUN
        cell.imageView?.image = image
      } else {

    // THIS IS A LOCAL IMAGE DISPLAYED IF THE PARSE OBJECT DOESN'T CONTAIN AN IMAGE FILE. THIS DOES DISPLAY CORRECTLY WHEN CALLED.
        let image = UIImage(named: "userMale")
        cell.imageView?.image = image
        println("Local Image")
      }
    }

    cell.imageView?.layer.cornerRadius = 40
    cell.imageView?.layer.masksToBounds = true
    cell.imageView?.layer.borderColor = UIColor.lightGrayColor().CGColor
    cell.imageView?.layer.borderWidth = 1
    return cell
}

A: Your background retrieval is not complete when you plug it in as shown 'cell.imageView?.image = image'. You need to use a post a notification and after the background is done and then set the cell after you receive the notification. If you do a println on the image just before you assigne it to the cell you will find that it shows a size of 0 by 0. An example of notification is in my example code in example


text:
Q: How to redirect to https but keep the host pattern the same I have the below nginx server config that works by redirecting any http request to https://www.foo.com
My application has potentially hundres of subdomains also, so I need it to redirect but maintain the sub domain so:
http://asdf.foo.com  -> https://asdf.foo.com
http://abc123.foo.com -> https://asdf.foo.com
How can I do this?
server {
   listen       80;
   server_name foo.com www.foo.com;

   location ^~ /.well-known/acme-challenge/ {
      alias /etc/letsencrypt_webroot/.well-known/acme-challenge/;
   }

   location / {
      return 301 https://www.foo.com$request_uri;
   }
}

A: There is a variable $host that you can use for the host portion of the URL.
Change the last stanza to
   location / {
     return 301 https://$host$request_uri;
   }


text:
Q: sshd "listen on all interfaces" behaviour, OSX and Ubuntu Given an extra loopback interface in the 127.0.0.X (X>1) range on BoxA (which can be running either OSX or Linux), I want to bind port 22 of this extra loopback interface to a forward SSH tunnel (ie. local port forward) that is pointed at BoxB.
On OSX this works fine (strangely, in retrospect). [Taking X=2] after bringing up the loopback alias with ifconfig lo0 alias 127.0.0.2 up, SSH can establish a tunnel with ssh -NfL 127.0.0.2:22:localhost:22 BoxB. Then in a new shell on BoxA, ssh 127.0.0.2 logs me into BoxB.
On Ubuntu, I can bring up the loopback alias on BoxA, but when trying to establish the SSH tunnel, ssh complains about not being able to bind (and hence forward) BoxA's port 22. The subsequent ssh 127.0.0.2 (in a new shell on BoxA) gives a fingerprint warning, which if bypassed, logs me back into BoxA. Makes sense - sshd on BoxA is listening to all interfaces.
Looking at the sshd_config in each, both are configured to listen on 0.0.0.0 (and :: for IPv6).
lsof for OSX gives:
launchd       1           root   40u  IPv6 0xddfcabed61001f0d      0t0  TCP *:ssh (LISTEN)
launchd       1           root   41u  IPv4 0xddfcabed6100413d      0t0  TCP *:ssh (LISTEN)
launchd       1           root   43u  IPv6 0xddfcabed61001f0d      0t0  TCP *:ssh (LISTEN)
launchd       1           root   44u  IPv4 0xddfcabed6100413d      0t0  TCP *:ssh (LISTEN)

and for Ubuntu:
sshd       1287              0    3u     IPv4           21903340        0t0        TCP *:ssh (LISTEN)

So both are listening on all interfaces, though I'm not sure why OSX uses 4 processes. In any case, Ubuntu gives the expected behaviour. Why does OSX behave differently?
The follow up question of course, is how to make Ubuntu behave like OSX in this regard.
While I wish for the sshd_config to have state, wildcards and/or logical operators (e.g. "do not listen on 127.0.0.*; listen on 127.0.0.1") like iptables, it doesn't seem to be the case...

A: That's reproducible using socat (1.7.3.2-2, not 1.7.3.1-2+deb9u1 which ignores reuseport) on Debian (so similar for Ubuntu):
term1$ socat -d -d  TCP4-LISTEN:5555,reuseaddr,fork -
2018/08/03 08:20:43 socat[25084] N listening on AF=2 0.0.0.0:5555

term2$ socat -d -d TCP4-LISTEN:5555,bind=127.0.0.2,reuseaddr,fork -
2018/08/03 08:21:00 socat[25085] E bind(5, {AF=2 127.0.0.2:5555}, 16): Address already in use
2018/08/03 08:21:00 socat[25085] N exit(1)

Now if you add reuseport on both:
term1$ socat -d -d  TCP4-LISTEN:5555,reuseaddr,reuseport,fork -
2018/08/03 08:21:28 socat[25086] N listening on AF=2 0.0.0.0:5555

term2$ socat -d -d TCP4-LISTEN:5555,bind=127.0.0.2,reuseaddr,reuseport,fork -
2018/08/03 08:21:56 socat[25092] N listening on AF=2 127.0.0.2:5555

otherterm$ netstat -tnlp 2>/dev/null|grep :5555
tcp        0      0 127.0.0.2:5555          0.0.0.0:*               LISTEN      25092/socat
tcp        0      0 0.0.0.0:5555            0.0.0.0:*               LISTEN      25086/socat

Using an other socat or netcat to connect will show it's properly routed to the correct listening socat depending on the IP address.
So the behaviour difference is most certainly on how the bind and setsockopt calls are done on MacOS and Ubuntu for ssh (maybe launchd has a role to play too?). Using strace, this is added in the working socat case:
 setsockopt(5, SOL_SOCKET, SO_REUSEPORT, [1], 4) = 0

UPDATE:
While I will address the letter of the OP's question: make it work, I also think the question doesn't tell about the broader goal and this goal might be achieved with an entirely different solution.
So to alter sshd and ssh behaviour when they bind a socket, it's possible to use a dlsym() wrapper that will alter bind(3)'s function behaviour before the real bind(2) syscall.
compile the file reuseport-wrapper.c below with:
gcc -shared -fPIC -o reuseport-wrapper.so reuseport-wrapper.c -ldl
#define _GNU_SOURCE
#include <dlfcn.h>

#include <sys/socket.h>
#include <stddef.h> /* NULL */

int bind(int socket, const struct sockaddr *address, socklen_t address_len) {
    static const int optval=1;
    static int (*orig_bind)(int, const struct sockaddr *,socklen_t)=NULL;

    if (orig_bind == NULL && (orig_bind=dlsym(RTLD_NEXT,"bind")) == NULL)
        return -1;
    if (address != NULL && (address->sa_family == AF_INET || address->sa_family == AF_INET6)) {
        if (setsockopt(socket, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof optval) != 0) {
            return -1;
        }
    }
    return orig_bind(socket, address, address_len);
}

This will put a wrapper on bind(3) to always set SO_REUSEPORT before binding an inet or inet6 socket.
Place it somewhere (eg as /usr/local/lib/reuseport-wrapper.so but it really doesn't matter since it's explicitely loaded like would a plugin).
Edit /etc/default/ssh and add:
LD_PRELOAD=/usr/local/lib/reuseport-wrapper.so

restart the ssh server (eg service ssh restart)
And run any other tool (including ssh) as root (see below why) with LD_PRELOAD=/usr/local/lib/reuseport-wrapper.so exported. For example:
$ sudo su -
[...]
# LD_PRELOAD=/usr/local/lib/reuseport-wrapper.so ssh -NfL 127.0.0.2:22:localhost:22 userB@BoxB

This command has to be started as root for two reasons: port 22 requires root to bind to it, and even with some additional capability, there's an additional restriction described in socket(7):

SO_REUSEPORT (since Linux 3.9)
      Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket
  (including the first socket) prior to calling bind(2) on the socket.
  To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be
  employed with both TCP and UDP sockets.

Once this is done:
# netstat -tnlp |grep -w 22
tcp        0      0 127.0.0.2:22            0.0.0.0:*               LISTEN      157/ssh
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      143/sshd
tcp6       0      0 :::22                   :::*                    LISTEN      143/sshd

And the tunnel will work as expected.


text:
Q: How to populate certain text field after selecting item from  JSF 2.0 i want that, when user select item in  a inputText field populates with data from database.
I have a select menu list:
<h:selectOneMenu id="blah" value="#{controller.selected.id}" title="#{bundle.CreateTitle_id}" >
     <f:selectItems value="#{controller.listOfId()}" />
</h:selectOneMenu>

and let's say have input text like this:
<h:inputText value="In here we place value from backing bean"></h:inputText>

How can i make after selecting an item from a list(which holds the id) populate text field with other data from my backing bean(let's say a name).
Here is my backingBean:
@ManagedBean(name = "controller")
@SessionScoped
public class Bean implements Serializable {

private Catalog current;// here i'm holding int id, String name and other stuff...
private DataModel items = null;
@EJB
private probaSession.CatalogFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;

public KatalogController() {
}

public Katalog getSelected() {
    if (current == null) {
        current = new Catalog();
        selectedItemIndex = -1;
    }
    return current;
}

private KatalogFacade getFacade() {
    return ejbFacade;
}

public PaginationHelper getPagination() {
    if (pagination == null) {
        pagination = new PaginationHelper(10) {

            @Override
            public int getItemsCount() {
                return getFacade().count();
            }

            @Override
            public DataModel createPageDataModel() {
                return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
            }
        };
    }
    return pagination;
}

//......
public ArrayList<Catalog> listOfId()  {
          ArrayList<Catalog> list=new ArrayList<Catalog>();
   try{

    String upit="select id from Catalog";

   Statement st=connection.createStatement();
   ResultSet rs=st.executeQuery(upit);

   while(rs.next()) {

      Katalog k=new Katalog();
      k.setId(rs.getInt(1));
      k.setName(rs.getString(2));

         list.add(k);

   }

 disconnect();

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

   return list;
}

and that's pretty much it.
I'm here if anything needs to explaining. It think it is easy(using ajax let's say) but i don't even know how to start doing it...

A: You must add an f:ajax (that is standard, many component library offer extended versions) to catch a change event in the inputText
<h:selectOneMenu id="blah" value="#{controller.selected.id}" title="#{bundle.CreateTitle_id}" >
  <f:selectItems value="#{controller.listOfId()}" />
  <f:ajax
     event="change"        <-- The event to capture. I believe that if not specified
                                 there is a default event to capture from
                                 each component (for inputText it would be "change")
     render="myForm:foo"  <-- Only repaint "blah"
     listener="#{controller.myBlahListener}"
</h:selectOneMenu>

<h:inputText id="foo" value="#{controller.fooText}"/>

Your listener will read the new value in this.getSelected().getId(), and change the model so that controller.getFooText() returns the new value (the easiest way probably is this.setFooTest(this.getSelected().getId(), but that depends of your model.


text:
Q: Laravel 8 : Storage::delete (file) return false Since yesterday I cannot delete a file from the folder
This my code in the controller.

public function update_avatar(Request $request)
{
    // Handle the user upload of avatar
    if ($request->hasfile('avatar')) {
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();
        if (auth()->user()->avatar) {
            // dd('/uploads/avatars/'. auth()->user()->avatar);
            Storage::delete('/uploads/avatars/'. auth()->user()->avatar);
            //dd(Storage::delete('/uploads/avatars/'. auth()->user()->avatar));
        }
        Image::make($avatar)->resize(500, 500)->save(public_path('/uploads/avatars/' . $filename));

        $user = Auth::user();
        $user->avatar = $filename;
        $user->save();
    }

    return view('profile', array('user' => Auth::user()) );

}

which does not delete the file in the folder, after debugging the method
 dd('/uploads/avatars/'. auth()->user()->avatar);
i get the file correctly, but when I debug on
 dd(Storage::delete('/uploads/avatars/'. auth()->user()->avatar));
the result is FALSE
ps: Im using laravel 8

A: At first you are doing Storage::delete('/uploads/avatars/'. auth()->user()->avatar); so by default if you have not changed anything, the disk is set to local,
You can check it from your config/filesystems.php(Showing here from laravel github official repo (https://github.com/laravel/laravel/blob/8.x/config/filesystems.php#L44))
So if you select, Storage::disk('public')->delete($filename);, it would select the disk for public with path, app/public, even you can add it manually(I have not tested this method so can't guarantee its success.)
Second, if you use File,
As you can see from https://github.com/laravel/framework/blob/8.x/src/Illuminate/Filesystem/Filesystem.php#L262,
it basically calls unlink() method of php.
Basically both of them call the delete method in Illuminate/Filesystem/Filesystem, but passing the path & methods of calling are different.
So you can use either,

*

*use Illuminate\Support\Facades\File;  File::delete($filename);

*use IIlluminate\Support\Facades\Storage Storage::disk('public')->delete($filename);  (on github)

*unlink() from php

A: DO this .
       if (Storage::exists('public'.$slider->image)) {
            Storage::delete('public'.$slider->image);
        }

Store method
        $image = Storage::disk('public')->put('admin/slider/', $request->image);
        $image = basename($image);
        $slider->image = '/admin/slider/' . $image;

save image using storage method in Database.


text:
Q: jquery mobile How to stop auto scroll to focused input in Mobile web browser In mobile device, when I open my page, and select an inputbox, the virtual keyboard is open, and page got scrolled automatically to put inputbox at center.
I do not want this action.
I have googled many answers, most of them suggested to manually call following javascript code in resize event.
window.scrollTo(0,0)

But when I tried, it makes the page twitched, like page scrolled down, and then got back shortly.
Any good solution?
Thanks.

A: Okay.
So now you know how to detect virtual keyboard open event, by following answer:
jquery mobile how to detect if mobile virtual keyboard is opened

For rough approach, you can add following code in the handler:
setTimeout(function(){
    window.scrollTo(0,0);
}, 100);

But this really makes the page flickered, and not a smooth solution.
What you need to know is that mobile device tries to detect active input element position, and if it s about to hidden by the keyboard, then simply scroll the whole page down, to make it shown fully.
So here is the tricky way: you just deceive mobile device to think that element is very top position now, and this trick will be done in different way for iOS and Android.
iOS
Following code will work perfect for iOS:
$(document).on('touchstart', 'textarea, input[type=text], input[type=date], input[type=password], input[type=email], input[type=number]', function(e){

            var intv = 100;
            var $obj = $(this);

            if (getMobileOperatingSystem() == 'ios') {

                e.preventDefault();
                e.stopPropagation();

                $obj.css({'transform': 'TranslateY(-10000px)'}).focus();
                setTimeout(function(){$obj.css({'transform': 'none'});}, intv);
            }
            return true;
        });

Android
In the virtual keyboard open event handler, hide some elements above the active input element, to make mobile device thinks active input element is in very top, and then after some seconds, show the hidden things again.
So in following sample code, $wrap is the whole content of the page, and $wrap.find('.content') is the elements above the active inputbox, so simply hide it to trick the mobile device, and then show back again shortly.
function onKeyboardOnOff(isOpen) {
    // Write down your handling code
    if (isOpen) {
        // keyboard is open
        $wrap.css({opacity: 0})
           .find('.content').hide(); // trick the browser thinks the element is relatively top position...
        setTimeout(function(){
            $wrap.css({opacity: 1})
                 .find('.content').show();
        }, 10);
    }
}

Well, so far these are working code, but not guaranteed for new version of mobile device OS. :-)
Honestly I really want mobile web browsers support some hook and functions to handle this kind of headache issues.


text:
Q: Is it possible to save html web page on client side in session or local storage? I have save a menu code of my website in separate html file , and i include in on my webpages.
which take time to render cause it is ajax call.
so there any method to save html page in session or local storage. ?
thanks in advance

A: Local storage is an fairly new idea in web development.  Not all browsers are currently on the same page and so you will end up finding that sometimes your methods will work perfectly in for someone and not at all for someone else.  None-the-less you can use the new feature in HTML5 (localStorage and sessionStorage) to accomplish your task.
You can find an example at http://www.w3schools.com/html/html5_webstorage.asp
First:
if(typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

Then, if storage is possible you can implement your code in the above if-case:
// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

OR with sessionStorage:
if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";

So essentially, at a high level you need to do the following:

*

*You will want to create a JavaScript routine that checks if the user's browser supports localStorage and if so check to see if you already stored the sidemenu in it.

*If you did store the sidemenu then simply load it into that <div> element. If you did not store the sidemenu then set the "ng-include" attribute (or do a manual ajax call) instead.

*If the user does support localStorage and you ended up doing an ajax call, then all you need is a mechanism to detect when the sidemenu.html is finished loading and then dump all of the content of that div into localStorage.

A: Why are you including the file with ajax call instead of <?php include 'menu.php';?> or <?php require 'menu.php';?> ? It is more reliable and fast, also as mentioned above both local and session storages aren't well supported at this time and date.


text:
Q: Using YEAR from Prompt entry in Date Selection Criteria I'm trying to figure out how to use a YEAR entered via a prompt in a date selection criteria... so the user enters 2018 for the Balance_Year... and I want to look for the TAXFORM_DED record with an EFFDT between 01/01/YEAR and 31/12/YEAR. Where YEAR = Prompt value?

A: using the extract syntax might work.
e.g.
select effdt
from taxform_ded
where extract(year from effdt) between :1 AND :2

Here's a demonstration:
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=d33f938fbb1428058cad54f74134bd28
select * from V$VERSION;

CREATE TABLE TAXFORM_DED
    ("EFFDT" timestamp);

INSERT ALL
    INTO TAXFORM_DED ("EFFDT")
         VALUES ('01-Jan-2010 12:00:00 AM')
    INTO TAXFORM_DED ("EFFDT")
         VALUES ('06-Jun-2013 12:00:00 AM')
    INTO TAXFORM_DED ("EFFDT")
         VALUES ('09-Sep-2019 12:00:00 AM')
SELECT * FROM dual;

select effdt
from taxform_ded
where extract(year from effdt) between 2012 AND 2018;

references:

*

*https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm

*https://www.oracletutorial.com/oracle-date-functions/oracle-extract/


text:
Q: Discrete Math: Multiplying a set by ∅ How would you multiply any set by  $\varnothing$? Lets say $A \times \varnothing$. Would that simply be equal to  $\varnothing$? or Would I write out $(a,  \varnothing ), (a_1,  \varnothing), (a_2,  \varnothing)$ etc. If possible could you explain your answer in words or short proof?

A: $(a, \varnothing ), (a1, \varnothing), (a2, \varnothing) $ are elements of $A\times \{\varnothing \}$. If $(a,x) \in A\times \varnothing$ then $a \in A$ and $x \in \varnothing$. But there is no $x \in \varnothing$, so there is no $(a,x) \in A\times \varnothing$. So $A\times \varnothing$ is empty, which means $A\times \varnothing=\varnothing$.

A: By definition, $\forall x: x\notin \varnothing$ and $\forall x,y:[(x,y)\in A\times\varnothing \iff x\in A \land y\in\varnothing]$.
Suppose $(a,b)\in A\times\varnothing$. Then $b\in\varnothing$, leading to a contradiction. Therefore, $\forall x, y:[(x,y)\notin A\times\varnothing],$ i.e. $A\times \varnothing$ is empty.


text:
Q: ZEND: Cannot Access Post Data Greets.
{{Solved}}
In order to get POST data you MUST use $this->formHidden in order to hold all the data. Even though variables are inside the  they don't get passed if they aren't in some sort of form item.
I am unable to access post data in ZEND.
Path of User -
START
INDEX PAGE
 ->Submit Page
   ->Pay Page
I created a controller, extended the Zend Controller, and added an action called payAction. The user can go from the Index Page to the Submit Page. After I have all their data inside variables, I used a form and a submit button to go to the "pay page". However, I cannot get any of the POST data.
public function payAction()
{
 $data = $this->getRequest();
}

I have tried putting getRequest, getParam, getRawBody inside that controller function.
In the page itself I have tried.
echo 'Hello';
   echo $request;
   echo $data;
   echo $_POST['payZip'];
   echo $_POST['data'];
   echo $_POST[$data];
   echo $request;
   echo $this->values['payZip'];
   echo $payZip;
   echo $this->values['shippingDone'];
   echo $stuff;

Is there ANYTHING I can place in my controller or in my view in order to get my post data? I used a form method="post" and a button and it DOES allow me to get to the page. I can see Hello. But NONE of the post data is available.
Any assistance would be appreciated.
Thank you.
-- Update
    $data = $this->getRequest();
    $param = $this->_request->getParam('payZip');

    if($this->getRequest()->isPost())
    {
    print_r($this->_getAllParams());
    echo $param;
    }

Doing that gives me -
HelloArray ( [controller] => wheel [action] => pay [module] => default [shipping] => UPS Ground [payPal] => Secure Payment System )
But I still can't print payZip... I did echo and nothing comes out.

A: To get parameters from Zend Framework you need to do this in the Action Controller:
$data = $this->_request->getParams();

You can also get individual params like this
$param = $this->_request->getParam('payZip');

What it appears your doing wrong is you're only getting the "request object".  You need to then call that objects method to get the request data.
Here's some simple code I often use when testing parameters:
public function indexAction()
{
    #::DEBUG::
    echo '
'; print_r($this->_request->getParams()); echo '
';
    #::DEBUG::
}

This will show all your parameters.  What you will notice is that you will also get the names of the Module, Controller and Action with your params.
EDIT
Ps.  If you're trying to use the parameter in the view script you need to do this:
echo $this->data['payZip'];

echo $this->param;

In your Action Controller, you save your data to the "view" object by doing this:
$this->view->myVariable = 'Hello';

But when you're in a view script, you are IN the view script, so $this represents $this->view from the action controller.
So, you access the variable like this:
echo $this->myVariable;

Wrapping everything into a bigger code chunk for understanding:
Your Controller
public function indexAction()
{
    // get all parameters and pass them to the view
    $this->view->params = $this->_request->getParams();
    // get an individual parameter and pass it to the view
    $this->view->payZip = $this->_request->getParam('payZip');
}

Your View Script

<?php print_r($this->params); ?>

My PayZip is: <?php echo $this->payZip; ?>

My PayZip (array) is: <?php echo $this->data['payZip']; ?>

I hope that helps!


text:
Q: Php form not submitting data to MySql database Im trying to make a register system that will allow the user to make their own account, the script says that the information was sent to the database successfully, but in actual fact it's not. here is the code.
Index.php
    <?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: home.php");
}
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Network TV Login Page</title>
    <link href="css/bootstrap.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Network TV

                                Login

                                Register

                                <form id="login-form" action="" method="post" role="form" style="display: block;">

                                        <input id="name" name="username" placeholder="Username" type="text" tabindex="1" class="form-control">

                                        <input id="password" name="password" placeholder="Password" type="password"   tabindex="2" class="form-control">

                                                <input class="form-control btn btn-success" name="submit" type="submit" value="Log In" id="submit" tabindex="3" >

                                                    Forgot Password?

                                </form>
                                <form id="register-form" action="index.php" method="post" role="form" style="display: none;">

                                        <input type="text" name="newusername" id="newusername" tabindex="1" class="form-control validate-input" placeholder="Username" value="" autocomplete="off">

                                        <input type="email" name="newemail" id="newemail" tabindex="2" class="form-control validate-input" placeholder="Email Address" value="" autocomplete="off">

                                        <input type="password" name="newpassword1" id="password" tabindex="10" class="form-control" placeholder="Password" autocomplete="off">

                                        <input type="password" name="newpassword1" id="password" tabindex="10" class="form-control" placeholder="Password" autocomplete="off">

                                                <input type="submit" name="register-submit" id="register-submit" tabindex="12" class="form-control btn btn-success" value="Register">

                                </form>

<?php
If($_POST){
    mysql_connect("localhost","root","Oliver");
    mysql_select_db("users");
    if(isset($_POST['register-submit'])){
    $user_name = $_POST['newusername'];
    $password = $_POST['newpassword1'];
    $email = $_POST['newemail'];
    }
    $passwordmd5 = md5($password);
    $query = "insert into username (username,password,email) values ('$user_name','$passwordmd5','$email')";
    $query = "DELETE FROM username WHERE username = ''";

    mysql_connect("localhost","root","Oliver");
    mysql_select_db("videos");
    $query = "DELETE FROM videos WHERE name = ''";

    if (mysql_query($query)){
        echo 'registration successful';
        exit;
    }

}
?>

Login.php
    <?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username = $_POST['username'];
$password = md5($_POST['password']);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "Oliver");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("users", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from username where password='$password' AND username='$username'", $connection);
$rows = mysql_num_rows($query);
if(isset($_SESSION['login_user']))
session_destroy();
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>

I know I should upgrade the code to MySqli or PDO.

A: Sorry, this was getting hard to read in the comments... The below worked for me:
if(isset($_POST['register-submit'])){
        $name = $_POST['newusername'];
        $pass = md5($_POST['newpassword1']);
        $email = $_POST['newemail'];
    }
$query = "INSERT INTO `username` (`username`, `email`, `password`) VALUES ('$name', '$email', '$pass')";


text:
Q: Display only Start and End object names in victory charts in X-Axis My requirement is to display all the details of my object in Y- Axis and to show first and last object details in X-Axis (like to show a range). My code as bellow
render() {

    let array = [ ];
    this.props.data.map(data => {
        array.push({ x: data.date, y: data.total })
      })

    return (
        <View>
            <VictoryChart>
                <VictoryLine
                    style={{
                        data: { stroke: "#c43a31" },
                        parent: { border: "1px solid #ccc" }
                    }}
                    data={array}
                />
            </VictoryChart>
        </View>
    );
  }

The current display of the graph as per the above code as bellow

I only wants to show the fist and last dates on my X-Axis. What am I missing here ??

A: I know this is an old question but better late than never. I didn't test this. I'm just guiding you.
You can make use of tickValues for VictoryAxis. doc here
Try to give your array of values as tickValues for the axis like this.
['11-08', '', '', '', '', '11-15]


text:
Q: Critical Error: This server does not appear to have Microsoft XML 4.0 Core Services installed. Object required I saw this when I run the website project:

Critical Error:  This server does not appear to have Microsoft XML 4.0
  Core Services installed. Object required

I researched it and downloaded MSXML 4.0 Service Pack 3 (Microsoft XML Core Services) (I tried to install the first one, then run the website, still saw the error, even after I restarted my web browser and computer.)and it's Pack 2 version after I tried the Pack 3.

A: Interestingly, I uninstalled the IIS URL Rewrite Module 2, it solved this problem.....


text:
Q: 301 moved permanently with AllowAutoRedirect I wrote a class that get the html from a site, this is the code:
public class NetworkHelper {
    static Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() => {
        var handler = CreateHandler();
        return new HttpClient(handler) {
            Timeout = TimeSpan.FromSeconds(3)
        };
    });

    static HttpMessageHandler CreateHandler() {
        var handler = new HttpClientHandler();
        // if the framework supports redirect configuration
        // set max redirect to the desired amount the default is 50
        if (handler.SupportsRedirectConfiguration) {
            handler.AllowAutoRedirect = true;
            handler.MaxAutomaticRedirections = 5;
        }
        // if the framework supports automatic decompression
        // set automatic decompression
        if (handler.SupportsAutomaticDecompression) {
            handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip |
                System.Net.DecompressionMethods.Deflate;
        }
        return handler;
    }

    ///
    /// Get the html structure of a site.
    ///
    /// <param name="url">Represents the URL of the page where to download the data.</param>
    /// <returns>Return a string that contains the html of the site.</returns>
    public async Task<string> GetHtmlAsync(Uri url, CancellationToken cancellationToken = default(CancellationToken)) {
        var response = await httpClient.Value.GetAsync(url, cancellationToken);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
}

the problem's that when I try to download the data from this url:
string html = await new NetworkHelper().GetHtmlAsync(new Uri("https://int.soccerway.com/charts/statsplus/2139109"));

I'll get this content:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>301 Moved Permanently</title>

Moved Permanently

The document has moved here.

so I guess AllowAutoRedirect isn't working as expected?

A: I discovered that changing:
return new HttpClient(handler) {
        Timeout = TimeSpan.FromSeconds(3)
    };

to:
return new HttpClient(handler) {
            //Timeout = TimeSpan.FromSeconds(3)
        };

all works well. Seems that there is a limited number of HTTP requests you can do per second, others get queued.


text:
Q: Reading a LP file with binary variables with GLPK I am trying to read a very simple LP file into GLPK. This LP file has 4 variables of which 2 are binary, and seems that GLPK reads badly these 2 binary variables (HACE_MESAS, HACE_SILLAS). It logs:

warning: lower bound of variable HACE_MESAS redefined warning: upper
  bound of variable HACE_MESAS redefined warning: lower bound of
  variable HACE_SILLAS redefined warning: upper bound of variable
  HACE_SILLAS redefined

and it solves badly because puts real values to these two variables:
HACE_MESAS = 0.01
HACE_SILLAS = 0.02

The LP file is like this:
Maximize
 obj: 5 MESAS + 3 SILLAS
Subject To
 IloC0: MESAS + 2 SILLAS >= 0
 IloC1: MESAS + 2 SILLAS <= 50
 IloC2: 2 MESAS + SILLAS >= 0
 IloC3: 2 MESAS + SILLAS <= 40
 IloC4: MESAS - 1000 HACE_MESAS <= 0
 IloC5: SILLAS - 1000 HACE_SILLAS <= 0
 IloC6: HACE_MESAS + HACE_SILLAS <= 1
Bounds
      MESAS >= 0
      SILLAS >= 0
 0 <= HACE_MESAS <= 1
 0 <= HACE_SILLAS <= 1
Binaries
 HACE_MESAS  HACE_SILLAS
Generals
 MESAS  SILLAS
End

Can anyone tell me what i am doing bad? Thanks.

A: Just remove the redundant bounds (they are unnecessary but as you see cause trouble)
 0 <= HACE_MESAS <= 1
 0 <= HACE_SILLAS <= 1

That is, I run this model:
Maximize
 obj: 5 MESAS + 3 SILLAS
Subject To
 IloC0: MESAS + 2 SILLAS >= 0
 IloC1: MESAS + 2 SILLAS <= 50
 IloC2: 2 MESAS + SILLAS >= 0
 IloC3: 2 MESAS + SILLAS <= 40
 IloC4: MESAS - 1000 HACE_MESAS <= 0
 IloC5: SILLAS - 1000 HACE_SILLAS <= 0
 IloC6: HACE_MESAS + HACE_SILLAS <= 1
Bounds
      MESAS >= 0
      SILLAS >= 0
Binaries
 HACE_MESAS  HACE_SILLAS
Generals
 MESAS  SILLAS
End

Everything works as expected:
Problem:
Rows:       7
Columns:    4 (4 integer, 2 binary)
Non-zeros:  14
Status:     INTEGER OPTIMAL
Objective:  obj = 100 (MAXimum)

   No.   Row name        Activity     Lower bound   Upper bound
------ ------------    ------------- ------------- -------------
     1 IloC0                      20             0
     2 IloC1                      20                          50
     3 IloC2                      40             0
     4 IloC3                      40                          40
     5 IloC4                    -980                           0
     6 IloC5                       0                           0
     7 IloC6                       1                           1

   No. Column name       Activity     Lower bound   Upper bound
------ ------------    ------------- ------------- -------------
     1 MESAS        *             20             0
     2 SILLAS       *              0             0
     3 HACE_MESAS   *              1             0             1
     4 HACE_SILLAS  *              0             0             1

Integer feasibility conditions:

KKT.PE: max.abs.err = 0.00e+00 on row 0
        max.rel.err = 0.00e+00 on row 0
        High quality

KKT.PB: max.abs.err = 0.00e+00 on row 0
        max.rel.err = 0.00e+00 on row 0
        High quality

End of output


text:
Q: How remove default google map current location icon? I am creating hybrid app using Ionic 2 & Typescript. I have added cordova-plugin-googlemaps plugin and added MAP in my page.
On view load I found the user location and adding the marker. My marker also added successfully. But default map current location icon (Blue dot) also added automatically. I wanted to hide/remove that.
Can anybody please let me know how we can hide this icon?

A: The blue dot will be visible when you have set the "myLocationButton" value to true. Either remove it or set the value to false.
new GoogleMap('YOUR_MAP_ELEMENT', {
                'backgroundColor': 'white',
                'controls': {
                    'compass': true,
                    'myLocationButton': false,
                    'zoom': true
}});


text:
Q: Pandas Plot: How to change xlim in datatime format? The range of date is from 2020-01-30 to 2020-03-31. The format of Date is datetime64[ns].
I want to change the xlim range to (2020-01-30, 2020-03-31), but not working.
My code is as follows:
#Plot left Y
fig, ax1 = plt.subplots()
fig.autofmt_xdate()

x_lim = (datetime.date(2020, 1, 30), datetime.date(2020, 3, 31))

df.plot(x = 'Date', y = ["TotalCount", "CumVirusCount"], ax = ax1, xlim = x_lim)

Plot right (Y)
ax2 = ax1.twinx()
df.plot(x = 'Date', y = ["Percent"], ax = ax2, xlim = x_lim, ylim=(0,70), color = 'tab:green')

#Decorations
#ax1:
ax1.set_xlabel('Date', fontsize=18)
ax2.set_ylabel("Percentage")

plt.show()

The plot is as follows:

I expect the first date to be 2020-01-30 and the last date to be 2020-03-31 on the x-axis.
How to make that happen? Why my approach doesn't work?
Thank you!

A: You do set the x-range in your code with xlim=..., and it works fine. But the ticks that matplotlib places on the x-axis by default do not necessarily include the min and max values. To change that, you have to change the ticks, not the range. Pandas' df.plot() wrapper takes an xticks keyword argument for this, e.g. pass this in the plot function call:
xticks=[x_lim[0], <some in-between dates to label>, x_lim[1]]


text:
Q: Attach TProcess to a running process I want to read some info from a console process. I know how to do this by using TProcess to start the the process and read bytes through pipes, see here.
Is this possible if the console process is already running? How do I attach TProcess to the handle of the console process?


text:
Q: Show that the set $A := \{x \in Q : x < 0 \text{ or } x^{2} < 2\}$ has no maximum. Does it have a supremum? If yes, what is it? Show that the set
$$A := \{x \in Q : x < 0  \text{ or }  x^{2} < 2\}$$
has no maximum. Does it have a supremum? If yes, what is it?

A: Since There is always some rational point as much as you want near to every number, in your question, $-\sqrt 2 \ \& \  0$, from both sides, So there is neither minimum nor maximum, respectively. But these number are infimum and supremum, respectively. Can you prove it now? Tell me how much you can continue from this hint...


text:
Q: What algebraic topology book to read after Hatcher's? I've currently finished chapter 2 of his book and done all the exercises of in chapter 0, 1 and 2. Was wondering when I finished reading this book what book do I read next in algebraic topology?

A: J.Peter May and Kate Ponto's More Concise Course In Algebraic Topology is a follow-up to May's introductory book containing cutting edge topics such as spectral sequences, model categories,basic homotopy theory,localization and completion of spaces and more. I haven't seen the whole book,but what I have seen looks terrific.
Homotopy theory is another natural place to go after learning basic algebraic topology. There's a wonderful new book that looks outstanding for this purpose: Jeffery Strom's Modern Classical Homotopy Theory. The book is beautifully written,very modern and geometric at the same time and it's written in the form of a directed set of exercises with no explicit proofs.It takes a lot of guts to write a problem course in algebraic topology and Strom's looks fabulous. It's definitely worth a look after Hatcher.
Also, you might want to check out the back appendix of May's A Concise Course In Topology -he gives many excellent recommendations for directions for further study.

A: Lecture Notes in Algebraic Topology by Davis and Kirk was a great post-Hatcher book for me. It covers characteristic classes, obstruction theory, spectral sequences, fiber bundles, etc.

A: After reading Hatcher's book, the next topics you would want to learn to do serious work in algebraic topology are as follows.

*

*Characteristic classes of vector bundles.  Milnor's book on the subject is fantastic.  Hatcher has notes on this on his webpage, but I think that Milnor's book is much, much better.

*The Serre spectral sequence (and maybe some of the other spectral sequences that show up in algebraic topology, like the Eilenberg-Moore spectral sequence).  I'm a big fan here of the notes on spectral sequences on Hatcher's webpage.

*Topological K-Theory.  Probably Atiyah's book is the best source, though I also like Karoubi's book and the notes on Hatcher's webpage.

A: If you are interested in the homotopy groups of spheres, after you have finished reading the rest of Hatcher's book (especially chapter 4) you should try some of the following (this is a supplement to Adam Smith's list, which you should also read!)

*

*You should try and learn some homological algebra at some stage (derived functors for example). You could try Rotman's Homological Algebra book

*Stable Homotopy and Generalised Homology by Adams. This is a funny little book. It has three parts, and strangely enough, you should start in Part 3! The first few chapters in Part 3 give  a nice introduction to generalised cohomology theories and spectra. A warning though, I wouldn't go through in great detail the construction of smash product, etc, as a lot of this has been superceded now. (This is also covered nicely in Chapter 2 of Hatcher's spectral sequnce book, if I recall correctly)

*You can try and add to your knowledge of spectral sequences with A User's Guide to Spectral Sequence by McCleary. This is kind of the ultimate book on spectral sequences, but for me personally I don't find it particuarly useful to learn from, but it is an excellent reference

*I can definitely recommend Mosher and Tangora's Cohomology Operations and Applications in Homotopy Theory. Excellent introduction to cohomology operations and the Steenrod algebra - and as an aside it is an excellent introduction to spectral sequences.

*If you are still intrested in homotopy groups of spheres after all this you probably want to explore the connection between formal groups laws and generalised cohomology theories. This is not a particularly easy topic! This is covered in a number of places

*

*Part 2 of the afermentioned book by Adams

*Chapter 4 of Complex Cobordism and Stable Homotopy Groups of Spheres by Ravenel (you will also need Apendix 2 on formal group laws). Note that this is kind of the ultimate book on the Adams-Novikov spectral sequence and all things related, but it is a difficult read. This will also give you an introduction to the spectra MU and BP, etc

*There are several good course notes on the internet:

*

*Haynes Miller's notes on cobordism

*Some course notes from Mike Hopkins - but some of the 'stacky' stuff can probably wait

*Some notes from Hal Sadofsky on formal group laws in Algebraic Topology

That should keep you busy for a while!


text:
Q: knockout.js mapping plugin add function Let's I have the following code to map json object to model:
$.getJSON('{% url "api-planner-planner-list" %}?format=json').then(function(data){
    planner = data[0];
    planner_model = ko.mapping.fromJS(planner);
    ko.applyBindings(planner_model);
});

How do I add a test function to the model to work with data-bind="click: test"??

A: Your question is unclear what you want to achieve if you want to add click event after model binding you can do this before applyBindnng or you can define viewmodel and merge it with data. Both will work

$.getJSON('{% url "api-planner-planner-list" %}?format=json').then(function(data){

    planner = data[0];
    planner_model = ko.mapping.fromJS(planner);

   planner_model.test = function(){
      //your code..
   }

    ko.applyBindings(planner_model);
});


text:
Q: reducer not called by driver in mapreduce wordcount program    package com.delhi;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class UppercaseDriver extends Configured implements Tool {

    public int run(String[] args) throws Exception{
        if(args.length !=2){
            System.out.printf("Two parameters are required- <input dir> <output dir>n");
        return -1;}

    Configuration conf = new Configuration();
    Job job=Job.getInstance(conf);
    job.setJobName("uppercase");
    job.setJarByClass(UppercaseDriver.class);
    job.setMapperClass(UpperCaseMapper.class);
    job.setReducerClass(UpperCaseReduce.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(LongWritable.class);
    FileInputFormat.setInputPaths(job,new Path(args[0]));
    FileOutputFormat.setOutputPath(job,new Path(args[1]));
    //job.setNumReduceTasks(1);
    boolean success = job.waitForCompletion(true);
    return success ?0:1;
    }
    public static void main(String[] args) throws Exception {
        int exitcode = ToolRunner.run(new UppercaseDriver(), args);
        System.exit(exitcode);
    }

}

This is driver program.
next is reducer program:
package com.delhi;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class UpperCaseReduce extends Reducer< Text,LongWritable, Text, LongWritable>{

    public void reduce(Text key, Iterable<LongWritable> value,
        org.apache.hadoop.mapreduce.Reducer.Context context)
        throws IOException, InterruptedException {

      int sum=0;
      System.out.println("how +++++++++++++++++" + key);
      for(LongWritable st: value){
          sum = (int) (sum + st.get());

      }
      System.out.println("how +++++++++++++++++" + key);
    context.write(key, new LongWritable(sum));
}

}

next is mapper program:
package com.delhi;

import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class UpperCaseMapper extends Mapper<Object, Text, Text, LongWritable>{

@Override
protected void map(Object key, Text value,
        org.apache.hadoop.mapreduce.Mapper.Context context)
        throws IOException, InterruptedException {
    String line = value.toString();
    String arr[] = line.split(" ");
    System.out.println("hello++++++++++++++++++++++++++++");
    for(String st: arr){
    //context.write(new Text(st.toUpperCase().trim()),new LongWritable(1));
    context.write(new Text(st),new LongWritable(1));
    }
}
}

from the already exist solution I find it out that in this type of problem outputkeyclass and outputvalueclass should match with reducer.I think I takecare  that part properly.I my case @Override for reduce is not working.I am using hadoop 7.2.3. I try to use trim function also.Problem is wordcount is not happening.I is giving me only "word 1", for any word in output file.
I started with different problem and I ended like this.Please help me.
Thanks.

A: So if you add an @Override annotation to your reduce method you get an error:

Method does not override method from its superclass

So you have a problem where the method signature doesn't match the one in Reducer.
You have:
public void reduce(Text key, Iterable<LongWritable> value,
                   org.apache.hadoop.mapreduce.Reducer.Context context)

If you change it to:
public void reduce(Text key, Iterable<LongWritable> value, Context context)

The error goes away. Since your reduce method wasn't overriding any methods it wouldnt have been called and it would have used an Identity reduce which matches your output.


text:
Q: Chrome extension...execute CSS from JS? I'm making a Chrome extension where I want to make all the images on a page spin using CSS keyframe animation, but I also want it to toggle on/off using JS. I've already figured out how to toggle on and off, but how should I execute the CSS from the JS? All I can think of is to just find all images, and add the .animation class, but it doesn't seem to work.
manifest.JSON
{
  "manifest_version": 2,

  "name": "SPINS",
  "description": "SPINS",
  "version": "1.0",
  "browser_action": { },

  "icons": { "16": "icon16.png",
           "48": "icon48.png",
          "128": "icon128.png" },

  "background": {
    "scripts": ["background.js"]
  },

  "content_scripts":
    [{
      "matches": ["<all_urls>"],
      "css": [ "spin.css"],
      "js": [ "content.js"]
      }],

  "permissions": [
   "activeTab"
   ]
}

background.JS
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.sendMessage(tab.id,{});
});

content.JS
var toggle = false;
chrome.runtime.onMessage.addListener(function() {
  toggle = !toggle;
  Array.prototype.forEach.call(document.querySelectorAll('img'), function(el) {
    el.addClass("animation");
  });
});

spin.CSS
@keyframes spin {
    from {transform:rotate(0deg);}
    to {transform:rotate(360deg);}
}

.animation {
    animation: 40s spin infinite linear;
}

A: Please replace
el.addClass("animation");

with
el.className = el.className + " animation";


text:
Q: why am I gettig null for some parameters in jersy rest post method? I am trying to set up a rest endpoint with jersey. I am using an angular2 client.
the angular code looks like this:
  post() {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    this.http.post('http://localhost:8050/rest/addentity', JSON.stringify(this.getValues()), new RequestOptions({ headers: headers })).
    subscribe(data => {
                alert('ok');
          }, error => {
              console.log(JSON.stringify(error.json()));
          });

  }

The post is sent correctly and I can see in the payload that all the values are there.
However, for two values I always get null in the server. Here's the method:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("addentity")
public void saveEntity(User user) {
    System.out.println("ADD CALLED");
    System.out.println(user.getId()); // null
    addUser(user);
}

I have no idea why. The media type is correct, I get a 204 response...
Does anybody have any ideas what I'm doing wrong?
EDIT
JSON
{"id":"1234",
"name":"john",
"age":15,
"height":"6.2"}

User
public class User implements Serializable {

    private static final long serialVersionUID = -5320367665876425279L;

    private Integer userId;
    private String name;
    private double height;
    private int age;

    public User() {
        // TODO Auto-generated constructor stub
    }

    public User(final Integer userId, final String name,
            final double height, final int age) {
        this.userId = userId;
        this.name = name;
        this.height = height;
        this.age = age;
    }

    public Integer getuserId() {
        return userId;
    }

    public void setuserId(final Integer userId) {
        this.userId = userId;
    }

    public String getname() {
        return name;
    }

    public void setname(final String name) {
        this.name = name;
    }

    public double getheight() {
        return height;
    }

    public void setheight(final double height) {
        this.height = height;
    }

    public int getage() {
        return age;
    }

    public void setage(final int age) {
        this.age = age;
    }

}

All values except height are null or 0, so only the double value is read correctly.

A: Well your actual code shows many problems, from what we can state:

*

*In your User class you have an attribute userId while in your JSON you don't have it, it's id instead.

*And the getters and setters in the User class are incorrect they should have the attribute first letter in Uppercase, ie : getage() should be getAge() and setage should be setAge().

You have to fix these problems otherwise your POJO won't be correctly mapped with your JSON.
You can refer to Getters and Setters in Java convention for further reading about it.


text:
Q: How to filter an R data.table by index and condition Please have a look at the following sample code.
DT <-data.table(1:15,0,rbinom(15,2,0.5))

I can filter by condition DT[V3 == 1,] or select rows by index DT[1:5,].
How can I do both? In the following code, the sequence of the indexed rows seems to by ignored:
DT[V3 == 1 & 1:5]

I could do DT[1:5,][V3 == 1], but then, for example, I wouldn't be able to modify the filtered rows:
DT[1:5,][V3 == 1, V2 := 1]

This only works with the following workaround:
DT[V3 == 1 & DT[,.I <= 5], V2 := 1]

However, this looks too data.frame-ish to me. Is there a more elegant way and why does DT[V3 == 1 & 1:5] not work?

A: We can try
DT[V3==1 & 1:.N %in% 1:5,  V2 := 1]

Or another option is
DT[intersect(which(V3==1), 1:5), V2 := 1]

Benchmarks
set.seed(24)
DT <- data.table(1:1e6, 0, rbinom(1e6, 2, 0.5))
DT1 <- copy(DT)
DT2 <- copy(DT)

OP's version
system.time({
 DT[V3 == 1 & DT[,.I <= 5], V2:= 1]
})
#user  system elapsed
#0.08    0.00    0.08

Modified options
system.time({
 DT1[V3==1 & 1:.N %in% 1:5,  V2 := 1]
})
# user  system elapsed
#  0.14    0.00    0.14

system.time({
  DT2[intersect(which(V3==1), 1:5), V2 := 1]
})
 # user  system elapsed
 #  0.05    0.00    0.05

A: Here's a faster way for @akrun's example:
set.seed(24)
DT <- data.table(1:1e6, 0, rbinom(1e6, 2, 0.5))
DT1 <- copy(DT)
DT2 <- copy(DT)

library(microbenchmark)
microbenchmark(
    DT1[which(V3[1:5]==1L), V2:= 1],
    DT2[intersect(which(V3==1), 1:5), V2 := 1]
, times = 1, unit = "relative" )

# Unit: relative
#        expr      min       lq     mean   median       uq      max neval
#  sequential  1.00000  1.00000  1.00000  1.00000  1.00000  1.00000     1
#     set_ops 55.43582 55.43582 55.43582 55.43582 55.43582 55.43582     1

It's "sequential" in the sense that we subset by index before evaluating the condition.
The generalization is
cond = quote(V3 == 1)
indx = 1:5

DT[ DT[indx, indx[eval(cond)]], V2 := 1]
# or
set(DT, i = DT[indx, indx[eval(cond)]], j = "V2", v = 1)


text:
Q: how to assign correct function to button of slideshow? I'm trying to make this little slideshow, it works, but I can't write a correct function for the buttons.
I want every time that a button is clicked, its related div display.
and then slideshow continue its regular way.
demo: http://jsfiddle.net/sabeti05/dsagcc5u/
html

        one

        two

        three

    <button class="one">one</button>
    <button class="two">two</button>
    <button class="three">three</button>

css
body{text-align:center}
#slideshow {
    height: 40px;
    margin: 0 auto;
    position: relative;
    width: 100px;
}
#slideshow > div {
    position: absolute;
}
.hide {
    display: none;
}
.block {
    display: block;
}

jquery
$(document).ready(function(){
    setInterval(function() {
      $('#slideshow > div.block')
        .removeClass("block")
        .next()
        .addClass("block")
        .end()
        .appendTo('#slideshow');
    },  1000);
});

A: Have a look at changes I made to your demo.
You made really clever trick with rotating DOM elements but that way divs lose their relation with buttons. Just leave elements in place and select next(). If selection is empty, select first() of siblings.
Also the markup needs to change so that buttons have type="button" (thus avoiding their default type submit) and have them contained in div #controls.
Now you can bind single event listener to container's click event on button element. In listener, find its index in container and show corresponding div with help of jQuery selectors. (Note that with jQuery 1.6.4 you have to use bind instead of on for binding event handler.)
Last but not least, there's the code to restart slideshow on button click.


text:
Q: forge connector in power automate when i try to connect with the forge connector in power automate, it sayes no items in the folder (bim 360).
[![enter image description here](https://i.stack.imgur.com/1V1Qg.png)](https://i.stack.imgur.com/1V1Qg.png)
i expect contact wit bim 360

A: Here are two possible missing steps in your setup. Please check that on your ACC account and project.

*

*Go to account admin to enable the Power Automate App. https://learn.microsoft.com/en-us/connectors/autodeskforgedataexc/#how-to-get-credentials

*Open your Revit model on your acc Project, select either view in the model, create an Exchange and save it to your Sentralfil folder. See https://youtu.be/VNzmxkMze48?t=45