text:
Q: Is it possible to return the correct values from a list of dictionaries based on user inputted subject ID? I apologize for any formatting issues or unclear parts, I'm VERY new to Python and programming in general. I want to make a script that pulls a list of research participant records (the code provided here is sample data) and the list contains separate dictionary-like items that have all of the screening questions (including the record id, or subject ID). I want to pull particular items (self-harm reports and suicidal thoughts questions) from this depending on what the script's user inputs as the record id
I want the script to be able to pull from a growing list of dictionaries, so it has to index So far I have tried to return a tuple based on the user input, but it returns the same values
regardless of what I input for subj, it returns the same three values ('1', '2', '1'), the values of ONLY the first dictionary
 from redcap import Project, RedcapError
 URL = 'https://redcap.lib.umd.edu/api/'
 #API KEY for sample data
 API_KEY = 'B2E685118B86FA89F57C49A1C9A38BDC'
 project = Project(URL, API_KEY)
 all_data = project.export_records()
 def find(subj, data):
  index = 0
  j = 0
   for i in data:
    for k,v in i.items():
        if k == 'record_id' and v == subj:
            index = j
            j+=1
        else:
            j+=1
    return data[index]['record_id'],data[index]['selfharm_18yr'],data[index]['talksaboutkillingself_18yr']

AN EXAMPLE OF DATA RECORD
 [{'record_id': '1', 'child_gender': '', 'c_age': '', 'c_dob': '', 't_date': '', 'school_yn': '', 'school_grade': '', 'father_job': '', 'mother_work': '', 'parentgender': '', 'relation_to_child': '', 'other': '', 'no_sports': '', 'sport_a': '', 'average_time_a': '', 'average_skill_a': '', 'sport_b_yes': '', 'sport_b': '', 'average_time_b': '', 'average_skill_b': '', 'sport_c_yes': '', 'sport_c': '', 'average_time_c': '', 'average_skill_c': '', 'hobby_a_yes': '', 'hobby_a': '', 'hobby_a_time': '', 'hobby_a_skill': '', 'hobby_b_yes': '', 'hobby_b': '', 'hobby_b_time': '', 'hobby_b_skill': '', 'hobby_c_yes': '', 'hobby_c': '', 'hobby_c_time': '', 'hobby_c_skill': '', 'clubs': '', 'club1': '', 'activeclub1': '', 'clubs_2': '', 'club2': '', 'activeclub2': '', 'clubs_3': '', 'club3': '', 'activeclub3': '', 'chore_a_yes': '', 'chore_a': '', 'chore_a_skill': '', 'chore_b_yes': '', 'chore_b': '', 'chore_b_skill': '', 'chore_c_yes': '', 'chore_c': '', 'chore_c_skill': '', 'close_friends': '', 'friends': '', 'get_along_siblings': '', 'along_withkids': '', 'behave': '', 'play_work': '', 'attend_school': '', 'school_reason': '', 'performance1': '', 'performance2': '', 'performance3': '', 'performance4': '', 'othersubjects': '', 'other_subjects': '', 'performanceother': '', 'other2': '', 'other_subjects_2': '', 'performanceother_2': '', 'other3': '', 'other_subjects_3': '', 'performanceother_3': '', 'specialeducation': '', 'sp_ed': '', 'repeat_grades': '', 'repeat2': '', 'academic_problems': '', 'describe_problems': '', 'problems_date': '', 'problems_yn': '', 'end_problems': '', 'disabilities': '', 'disability2': '', 'concerns': '', 'best_things': '', 'too_young': '', 'alcohol': '', 'describe_alc18yr': '', 'argues': '', 'fails_finishing_things': '', 'enjoyment': '', 'bm': '', 'bragging': '', 'concentration': '', 'obsessions': '', 'describe_obesessions': '', 'restlessness': '', 'dependence': '', 'lonely': '', 'confusion': '', 'crying': '', 'cruelty_animals': '', 'cruelty': '', 'daydreams': '', 'selfharm_18yr': '2', 'attention': '', 'destruction': '', 'destruction2': '', 'disobedience': '', 'school_disobedience': '', 'eating_well': '', 'getting_along': '', 'guilt_misbehaving': '', 'jealousy': '', 'rule_breaking': '', 'fearful': '', 'describe_fears': '', 'fears_school': '', 'fears_thoughts': '', 'perfection': '', 'loveless': '', 'others_outtoget': '', 'worthlessness': '', 'accident_prone': '', 'fights': '', 'teasing': '', 'trouble_makers': '', 'voices': '', 'describe_voices': '', 'impulsive_acts': '', 'solitary': '', 'lying_cheating': '', 'fingernails': '', 'tense': '', 'movements': '', 'describe_movements': '', 'nightmares': '', 'likeability': '', 'constipation': '', 'fear_anxiety': '', 'dizziness': '', 'guilt': '', 'overeating': '', 'overtired': '', 'overweight': '', 'aches_pains': '', 'headaches': '', 'nausea': '', 'eye_problems': '', 'describe_eyes': '', 'skin_problems': '', 'stomach_aches': '', 'vomiting': '', 'other_conditions': '', 'describe_other': '', 'physical_violence': '', 'picks_skin': '', 'describe_skin': '', 'public': '', 'public2': '', 'school_work': '', 'coordination': '', 'older_kids': '', 'younger_kids': '', 'talking_refusal': '', 'compulsions': '', 'describe_compulsions': '', 'runs_away': '', 'screams': '', 'secretive': '', 'seeing_things': '', 'describe_seeingthings': '', 'self_conscious': '', 'sets_fires': '', 'sexual_problems': '', 'describe_sexualproblems': '', 'clowning': '', 'shy_timid': '', 'sleeps_less': '', 'sleeps_more': '', 'describe_sleeping': '', 'inattentive': '', 'speech_problems': '', 'describe_speechproblems': '', 'stares_blankly': '', 'steals_home': '', 'steals_outside': '', 'stores': '', 'describe_hoarding': '', 'strange_behavior': '', 'describe_strangebehavior': '', 'strange_ideas': '', 'describe_ideas': '', 'stubborn_sullen': '', 'mood_changes': '', 'sulking': '', 'suspicious': '', 'swearing_obscenities': '', 'talksaboutkillingself_18yr': '1', 'sleeptalking_walking': '', 'describe_sleeptalking': '', 'talks_toomuch': '', 'frequent_teasing': '', 'temper_tantrums': '', 'thinks_sex': '', 'threatens_people': '', 'thumb_sucking': '', 'smoking': '', 'sleeping_troubles': '', 'describe_sleepingtroubles': '', 'truancy': '', 'low_energy': '', 'depression': '', 'loud': '', 'uses_drugs': '', 'describe_drugusage': '', 'vandalism': '', 'wets_self': '', 'wets_bed': '', 'whining': '', 'opposite_sex': '', 'withdrawn': '', 'frequent_worries': '', 'additional_problems': '', 'problem_a': '', 'prob_a_true': '', 'problem_b_yes': '', 'problem_b': '', 'prob_b_true': '', 'problem_c_yes': '', 'problem_c': '', 'prob_c_true': ''}, {'record_id': '2', 'child_gender': '', 'c_age': '', 'c_dob': '', 't_date': '', 'school_yn': '', 'school_grade': '', 'father_job': '', 'mother_work': '', 'parentgender': '', 'relation_to_child': '', 'other': '', 'no_sports': '', 'sport_a': '', 'average_time_a': '', 'average_skill_a': '', 'sport_b_yes': '', 'sport_b': '', 'average_time_b': '', 'average_skill_b': '', 'sport_c_yes': '', 'sport_c': '', 'average_time_c': '', 'average_skill_c': '', 'hobby_a_yes': '', 'hobby_a': '', 'hobby_a_time': '', 'hobby_a_skill': '', 'hobby_b_yes': '', 'hobby_b': '', 'hobby_b_time': '', 'hobby_b_skill': '', 'hobby_c_yes': '', 'hobby_c': '', 'hobby_c_time': '', 'hobby_c_skill': '', 'clubs': '', 'club1': '', 'activeclub1': '', 'clubs_2': '', 'club2': '', 'activeclub2': '', 'clubs_3': '', 'club3': '', 'activeclub3': '', 'chore_a_yes': '', 'chore_a': '', 'chore_a_skill': '', 'chore_b_yes': '', 'chore_b': '', 'chore_b_skill': '', 'chore_c_yes': '', 'chore_c': '', 'chore_c_skill': '', 'close_friends': '', 'friends': '', 'get_along_siblings': '', 'along_withkids': '', 'behave': '', 'play_work': '', 'attend_school': '', 'school_reason': '', 'performance1': '', 'performance2': '', 'performance3': '', 'performance4': '', 'othersubjects': '', 'other_subjects': '', 'performanceother': '', 'other2': '', 'other_subjects_2': '', 'performanceother_2': '', 'other3': '', 'other_subjects_3': '', 'performanceother_3': '', 'specialeducation': '', 'sp_ed': '', 'repeat_grades': '', 'repeat2': '', 'academic_problems': '', 'describe_problems': '', 'problems_date': '', 'problems_yn': '', 'end_problems': '', 'disabilities': '', 'disability2': '', 'concerns': '', 'best_things': '', 'too_young': '', 'alcohol': '', 'describe_alc18yr': '', 'argues': '', 'fails_finishing_things': '', 'enjoyment': '', 'bm': '', 'bragging': '', 'concentration': '', 'obsessions': '', 'describe_obesessions': '', 'restlessness': '', 'dependence': '', 'lonely': '', 'confusion': '', 'crying': '', 'cruelty_animals': '', 'cruelty': '', 'daydreams': '', 'selfharm_18yr': '3', 'attention': '', 'destruction': '', 'destruction2': '', 'disobedience': '', 'school_disobedience': '', 'eating_well': '', 'getting_along': '', 'guilt_misbehaving': '', 'jealousy': '', 'rule_breaking': '', 'fearful': '', 'describe_fears': '', 'fears_school': '', 'fears_thoughts': '', 'perfection': '', 'loveless': '', 'others_outtoget': '', 'worthlessness': '', 'accident_prone': '', 'fights': '', 'teasing': '', 'trouble_makers': '', 'voices': '', 'describe_voices': '', 'impulsive_acts': '', 'solitary': '', 'lying_cheating': '', 'fingernails': '', 'tense': '', 'movements': '', 'describe_movements': '', 'nightmares': '', 'likeability': '', 'constipation': '', 'fear_anxiety': '', 'dizziness': '', 'guilt': '', 'overeating': '', 'overtired': '', 'overweight': '', 'aches_pains': '', 'headaches': '', 'nausea': '', 'eye_problems': '', 'describe_eyes': '', 'skin_problems': '', 'stomach_aches': '', 'vomiting': '', 'other_conditions': '', 'describe_other': '', 'physical_violence': '', 'picks_skin': '', 'describe_skin': '', 'public': '', 'public2': '', 'school_work': '', 'coordination': '', 'older_kids': '', 'younger_kids': '', 'talking_refusal': '', 'compulsions': '', 'describe_compulsions': '', 'runs_away': '', 'screams': '', 'secretive': '', 'seeing_things': '', 'describe_seeingthings': '', 'self_conscious': '', 'sets_fires': '', 'sexual_problems': '', 'describe_sexualproblems': '', 'clowning': '', 'shy_timid': '', 'sleeps_less': '', 'sleeps_more': '', 'describe_sleeping': '', 'inattentive': '', 'speech_problems': '', 'describe_speechproblems': '', 'stares_blankly': '', 'steals_home': '', 'steals_outside': '', 'stores': '', 'describe_hoarding': '', 'strange_behavior': '', 'describe_strangebehavior': '', 'strange_ideas': '', 'describe_ideas': '', 'stubborn_sullen': '', 'mood_changes': '', 'sulking': '', 'suspicious': '', 'swearing_obscenities': '', 'talksaboutkillingself_18yr': '2', 'sleeptalking_walking': '', 'describe_sleeptalking': '', 'talks_toomuch': '', 'frequent_teasing': '', 'temper_tantrums': '', 'thinks_sex': '', 'threatens_people': '', 'thumb_sucking': '', 'smoking': '', 'sleeping_troubles': '', 'describe_sleepingtroubles': '', 'truancy': '', 'low_energy': '', 'depression': '', 'loud': '', 'uses_drugs': '', 'describe_drugusage': '', 'vandalism': '', 'wets_self': '', 'wets_bed': '', 'whining': '', 'opposite_sex': '', 'withdrawn': '', 'frequent_worries': '', 'additional_problems': '', 'problem_a': '', 'prob_a_true': '', 'problem_b_yes': '', 'problem_b': '', 'prob_b_true': '', 'problem_c_yes': '', 'problem_c': '', 'prob_c_true': ''}]

I expect it to output a truple of the three keys, depending on what the record id of the corresponding dictionary is, but it instead outputs the same thing regardless of the subject ID
AN EXAMPLE OF THE OUTPUT
 find('1', all_data)
 ('1', '2', '1')

 find('2', all_data)
 ('1', '2', '1')

In the future I also want to be able to send those to an Excel spreadsheet.

A: So in this case, you're doing a ton of unnecessary iteration. The beauty of python dictionaries is that they're hashed and optimized for lookup operations.
Rather than iterating through keys and values, all you need to do is supply the key as the index and return early if the record exists. (Note, I changed a few names around for clarity, and to ensure that things like find() don't shadow built-in methods from other classes)
def find_item(subj, data):
    for subdict in data:
        if subdict['record_id']== subj:
            return subdict['record_id'],subdict['selfharm_18yr'],subdict['talksaboutkillingself_18yr']
    return "No Records Found"

find_item('1',data)
('1', '2', '1')

find_item('2',data)
('2', '3', '2')

find_item('zyzzyx',data)
"No records found"

And, regarding your function, here's where I believe the problem lies:
if k == 'record_id' and v == subj:
    index = j
    j+=1
else:
    j+=1

In the case of the provided list of 2 records, this means you're setting index==0 before you update j, so even if the record is found at i[1], you still return the values from i[0]


text:
Q: Does usb support control (IN) transfer with wLength = 0? Recently, I'm learning usb protocol with libusb and linux gadget (g_zero). When I do the following control transfer, the usb device just stucks.
libusb_control_transfer(devh
  0xC0, // bRequestType (IN, device to host)
  0x5C, // bRequest
  0x0000, // wValue
  0x0000, // wIndex
  NULL, // buffer
  0, // buffer length
  1000 // timeout
)

I also use a usb analyzer to monitor the usb packets, it show as follow:
Setup Stage:
    SETUP Packet
    DATA0 Packet: c0 5c 00 00 00 00 00 00
    ACK Packet
Data Stage:
    nothing here, then follow immediately with
Status Stage:
    OUT Packet
    DATA1 Packet (length: 0)
    NAK Packet
PING Packet // then PING Packet infinitely

After that, I search the usb 2.0 specification and found (in ch 8.5.3) that the specification describes only three type of control transfer:
             Setup                      Data                      Status
             Stage                      Stage                     Stage
            /---------\  /------------------------------------\  /-------\
Control     <Setup (0)>  <Out (1)>  <Out (0)>  ...  <Out (0/1)>  <In  (1)>
Write           DATA0      DATA1      DATA0           DATA0/1      DATA1

Control     <Setup (0)>  <In  (1)>  <In  (0)>  ...  <In  (0/1)>  <Out (1)>
Read            DATA0      DATA1      DATA0           DATA0/1      DATA1

             Setup        Status
             Stage        Stage
            /---------\  /-------\
No-Data     <Setup (0)>  <IN  (1)>
Control         DATA0      DATA1

So I guess maybe usb doesn't support Ctrl-IN-0 transfer?

redpajama_set_name: RedPajamaStackExchange


text:
Q: java.security.cert.CertificateParsingException: java.io.IOException: subject key, Could not create EC public key hi, I got this error when executing my program. I am trying to read a certificate from a Keystrore and i got the following error:
java.security.cert.CertificateParsingException: java.io.IOException: subject key, Could not create EC public key
at sun.security.x509.X509CertInfo.<init>(X509CertInfo.java:171)
at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1781)
at sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:196)
at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:97)
at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:339)
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:747)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
......

This is the code i used to read the certificate:
public static Certificate getCerticate(String KSpwd, String KSname, String alias) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{

    //Before a keystore can be accessed, it must be loaded.
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        // get user password and file input stream
        char[] password = KSpwd.toCharArray();
        java.io.FileInputStream fis = new java.io.FileInputStream(KSname);
        ks.load(fis, password);
        fis.close();

    //Get the certificate from the Key Store
        Certificate cert = ks.getCertificate(alias);

        return cert;
}

A: You have to comment out the NSS provider in the java.security file and everything will be working fine then.


text:
Q: How to use SED regex in toml config file? I'm trying to create a custom prompt for zsh theme starship which has an API configurable via a .toml file...
The code which I'm trying to use at the moment is:
[custom.vtex]
command = "cat $HOME/.config/configstore/vtex.json | grep account | sed -n 's/.*\:.*\"\(.*\)\".*/\1/p'"
description = "My custom prompt"
files = [".vtexignore"]
style = "fg:red"

The .json I have is:
{
    "env": "prod",
    "_nextFeedbackDate": "2021-08-17T12:43:59.194Z",
    "account": "example",
    "workspace": "workspace",
    "_lastUsedWorkspace": "master",
    "login": "email@email.com",
    "token": "eyJhbGciOiJFUzI1NiIsImtpZCI6IkEwRkQ4NDgzNTFG...",
    "_lastUsedAccount": "other-account",
    "apps": {
      ...
    }
}

The cat & grep alone returns this:
    "account": "example",

And what I'm trying to accomplish is extract everything but example to show it in my prompt. Problem is I'm not sure if it cannot be done in a .toml file but I get this error:
[ERROR] - (starship::config): Unable to parse the config file: invalid escape character in string: `:` at line 14 column 83

And if I add/remove scaping characters then no more errors show but sed returns nothing.

EDIT:
Added de .json as example.
I succesfully solved this with your help but changing David response because I still needed to escape double quotes since the command in .toml was between them.
Finally I did this, note that I needed account and workspace, didn't mention it earlier cause I thought I'd be able to solve it by myself (but probably someone can make it in a more efficient/fashion way):
vtex_prompt.sh
#!/usr/bin/zsh
account=$(sed -n -E '/^[[:blank:]]*\"account"/s/^[[:blank:]]*[^[:blank:]]+[[:blank:]]\"([^\"]+)\",$/\1/p' $HOME/.config/configstore/vtex.json)
workspace=$(sed -n -E '/^[[:blank:]]*\"workspace"/s/^[[:blank:]]*[^[:blank:]]+[[:blank:]]\"([^\"]+)\",$/\1/p' $HOME/.config/configstore/vtex.json)
echo "$account/$workspace"

starship.toml
[custom.vtex]
command = "zsh ~/vtex_prompt.sh"
description = "VTEX Prompt"
files = [".vtexignore"]

A: You can extract "example" (without the quotes) from your string above, regardless of the leading whitespace in the line with a substitution and backreference. Using extended regex with the -E option will cut down on the number of escapes with '\' needed. Using [[:blank:]] to match whitespace will match all types of whitespace.
Putting it together you can do:
sed -E 's/^[[:blank:]]*[^[:blank:]]+[[:blank:]]"([^"]+)",$/\1/'

This presumes your cat/grep output ends with the ',' without trailing whitespace. (adjust if it does)
Example Use/Output
$ echo '    "account": "example",' |
> sed -E 's/^[[:blank:]]*[^[:blank:]]+[[:blank:]]"([^"]+)",$/\1/'
example

Let me know if that is what you intended or if I misinterpreted your need. Also let me know if you have further questions about the sed expression.
As @WiktorStribiżew notes, you should be able to get rid of the cat and grep and use sed alone with:
sed -n -E '/^[[:blank:]]*"account"/s/^[[:blank:]]*[^[:blank:]]+[[:blank:]]"([^"]+)",$/\1/p'

Where -n suppresses the normal printing of pattern-space and /^[[:blank:]]*"account/ before the s/find/replace/ locates the line beginning with   "account".. before extracting and printing. That would make things a bit more efficient.


text:
Q: Custom Spring scope based on constructor args I need to define a custom scope where given a constructor argument same bean instance is used when the arg is the same.
But, the objectFactory parameter doesn't give access to the constructor arguments.
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {

        // This method doesn't exists. It's what I need
        String arg = (String) objectFactory.getArg(1);

        if (!mScopedObjects.containsKey(arg)) {

            mScopedObjects.put(arg, objectFactory.getObject());
        }

        return mScopedObjects.get(arg);
    }

//Configuration
@Bean
@Scope("myscope")
public Foo getFoo(String fooId) {

    return new Foo(fooId);
}

//Somewhere in the project
Foo one = context.getBean(Foo.class, "one");
Foo two = context.getBean(Foo.class, "two");
Foo bar = context.getBean(Foo.class, "one");

"one" and "bar" should be same instance, "two" another instance.
Other solutions states to use a FactoryBean class. But I need a custom scope.
Any solution?


text:
Q: Trying to use the INDIRECT function within an INDIRECT function and I can't get the syntax to work I am using the following countif formula, inside which there are 2 INDIRECT functions to reference a different sheet
=COUNTIF(INDIRECT("'"&W18&"'!H$3:H$200"),   ">"&INDIRECT("'"&W18&"'!A$1")-"8")

What I'm trying to do is set up the ability to change the two 'H' in the formula to any column letter from within another cell.  I.e if I change the letter in a Cell from 'H' to 'I', the formula will change accordingly to give:
=COUNTIF(INDIRECT("'"&W18&"'!I$3:I$200"),   ">"&INDIRECT("'"&W18&"'!A$1")-"8")

I am trying to input another INDIRECT function into the formula to achieve this but everything I'm trying doesn't seem to work.  Any ideas as to how this could work?
Thanks!

A: You don't nest INDIRECTS.  You just concatenate the new reference in the string:
INDIRECT("'"&W18&"'!" & A18 & "3:" & A18 & "200")

Where A18 is the cell with the column letter.
remember that INDIRECT takes a text string that looks like a range reference and returns the actual range reference.  So no matter how may concatenations one has to create that string, only on INDIRECT per range reference is needed.


text:
Q: Reusing threads/spawning new browsers with maven surefire and TestNG with low threadCount Reusing of threads is probably not quite the right terminology, however I am running a test automation setup that uses <threadCount> from maven surefire in order to run my testNG test suites.  the problem is that:
the tests are running and opening a new browser until the number of tests to run is greater than the specified threadCount.  For example, if I have 10 tests in the run and specify 7 threads, I will have 7 browsers launch originally, however instead of waiting until these are closed to launch another 3, it will re-use 3 of the 7 browsers to execute the next tests.
How can I have it wait for the 7 to finish in this instance, then launch up another 3 browsers brand new, without reusing the same browser instance.
Scaling this up will become non-viable, if i have for example 100 tests to run and using 10 threads, I will get 90 tests re-ran in the origin 10 browser instances.
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>${maven.surefire.version}</version>
  <configuration>
     <parallel>methods</parallel>
     <threadCount>${thread.count}</threadCount>
      <suiteXmlFiles>

here is some code used for instiating my drivers:
@BeforeSuite(alwaysRun = true, description = "Driver Instantiation")
public static void instantiateDriverObject() {
    driverFactory = new ThreadLocal<DriverFactory>() {
        @Override
        protected DriverFactory initialValue() {
            DriverFactory driverFactory = new DriverFactory();
            webDriverThreadPool.add(driverFactory);
            return driverFactory;
        }
    };
}


text:
Q: How to run code only when iframe loaded I have been battling with this issue for a few days now and finally found a partial solution but I think it could be improved.
In my project, I have a series of iframes that contain videos. When a link is clicked are displayed with a slide transition and when the link is clicked again the video stops and the span containing the iframe is hidden also with a transition.
This is achieved by adding and removing a css class of "open" that has a height and a transition in it. In addition to this I have an event listener that collapses the containing span also when the video finishes. All this works fine and to save time I am not posting the code.
The issue I was having was with slow page loading times, so I removed the src attribute for the iframes from the html and moved it to my js file and assigned it only after the click is performed. This wasn't working and I realised I needed the iframe to fully load before running the rest of the code inside the "click" method. So I delayed this part of the code by 100ms.
All this works, but I feel it would be better to have the rest of the code run not after a 100ms lapse but when the iframe is loaded (in case page viewed by slower computers). Not sure how to do this.
Here is the code as it stands now:
var player;
var frame = $("#frame");

frame.bind("load", function () {
    player = $(this).contents().find("#myVid");
    player.on('ended', function () {
        frame.removeClass("open");
    });
});

$("#clickableLink").click(function(){

        if (frame.hasClass("open")) {

            frame.removeClass("open");
            frame.contents().find('#myVid').get(0).pause();

        } else {

            function delayed(){

                frame.addClass("open");
                frame.contents().find('#myVid').get(0).play();

            }
            frame.attr("src","iframe.html");
            setTimeout(delayed, 100);
        }

});

Fairly new to development so I am looking for the simplest way to do this. Any help appreciated.

A: Here is a super simple example of calling code when the iframe has loaded. Check out the onload attribute of the iframe tag:

<head>
  <script>
  function frameLoaded() {
    alert('frame loaded!');
  };
  </script>
</head>

<body>
  <iframe id="frame" src="https://en.wikipedia.org/wiki/HTML_element#Frames" onload="frameLoaded(this)" />
</body>


text:
Q: How to give user credentials to create a contact in Contact Api V3(.Net) I need to create an application for managing contacts.  Once I add a contact into my DB it will automatically update in Google contacts.
I try to create a google contact through my application using Contact API V3. I have referred to this link to do this.
Here I don't know where to give the user credentials(Username & Password).
Can anyone clarify?

A: There are two scenarios here:
1.If you want to add contacts to yourself, then enter the clientid and client secret in the code(which you get when application is registered in the Google developers console) itself. Here is the link for the documentation.
2.When you want to add contacts to the users of your application:
Requests to the Google Contacts API for non-public user data must be authorized by an authenticated user. Google authenticates with Oauth 2.0 where user is prompted to give the user id and password(for the first time) to authenticate the application to access user's data. Here is the link for the documentation.
Also, you try using oauth playground to see how oauth works.


text:
Q: Best way of implementing a family tree in Java using a data structure https://softwareengineering.stackexchange.com/questions/285418/name-of-data-structure-thats-tree-like-with-multiple-root-nodes
I stumbled upon the above where someone answered a question regarding implementing a tree that has > 2 nodes and I just wanted to get someone's thoughts on how best to implement a family tree with parent nodes which have more than two children nodes. I had looked in Binary Trees, but since they can only have two children nodes decided to research elsewhere. I also looked into using a Forest Data Structure to implement a Family Genealogy Tree that consist of multiple nodes with 0-multiple children. Possibly may use a Forest Tree, however from most representations that I searched up on and found, it looks similar to a disjointed set, but I do not want a parent node to already be pre-destined to have no children.
I hope it makes sense what I am saying.
Any advice or comments anyone is able to offer would be much appreciated.

A: If you want to represent a list of children, simply have a list of Person instances inside your Person class:
class Person {
  List<Person> children;
  Person father;
  Person mother;
}

Then you can add as many Persons as you want to the children list.
I also added father and mother fields here to allow you to navigate to parents.
One tip: Be very thorough with your modelling. Familial relations have some easy to miss cases, e.g. adoption. "Father" and "mother" is almost certainly too simplistic.


text:
Q: C# metro - Background task refresh less than 15 minutes I have a BackgroundTask to refresh live tile. I use TimeTrigger but I need a more quickly refresh than 15 minutes. I read it's impossible, but oficial app Social use it for show a profiles pictures of users friend, so some way must exist.
Can you help me?

A: This sample shows you how to do it:
http://code.msdn.microsoft.com/windowsapps/Tile-Update-every-minute-68dbbbff
It basically creates ScheduledTileNotifications for every minute for the next couple of hours. When that time is up a BackgroundTask creates the ScheduledTileNotifications again.

A: Maybe you should use tile notification queue, with it's help you can show up to 5 notifications, as it does the app Social.


text:
Q: SNMP can't find the OID in the OID Tree I installed net-snmp on centos 7 with yum :
yum install net-snmp

I configured the /etc/snmp/snmpd.conf file to see all the oid tree :
#Make at least  snmpwalk -v 1 localhost -c public system fast again.
#       name           incl/excl     subtree         mask(optional)
#view    systemview    included   .1.3.6.1.2.1.1
#view    systemview    included   .1.3.6.1.2.1.25.1.1
view    all     included        .1      80

when i tap the snmpwalk command :
snmpwalk -v 1 -c public 127.0.0.1

it works , but i want to search a specefic oid which is :
snmpwalk -v 1 -c public 127.0.0.1 iso.3.6.1.4.1.8711.101.28.1.2.7.20.40.30.10

the snmpwalk doesn't return a result .
how can i add this oid to the oid tree ??

A: Looking into IANA's PEN registry you see that the private enterprise number 8711 is registered to 'THALES Broadcast & Multimedia'. You installed net-snmpd which doesn't have a subagent registered under this number in it's default configuration.
Since this company seems to be selling IPTV products (I only did a very quick search, no real research) I assume you actually want to query some parameters on the device itself; you don't need a snmp-daemon running on a different machine. Try querying the real target machine instead.
However, if your vendor really provided you with a subagent which shall be installed on your Linux machine, you need to tell net-snmpd to pass all queries to the vendor OID 1.3.6.1.4.1.8711 to this agent. The configuration methodes depends on the type of subagent; if it's AgentX extension configure the master agentx statement and start your subagent after restarting snmpd. If it's just a simple script, you should read up on the EXTENDING AGENT FUNCTIONALITY section in the manual. There are many ways to accomplish this.
Extra-note: The OID you're querying is already deep down the vendor tree. Many subtrees are dynamic and depend on the actual hardware configuration. Try an snmpwalk higher up the tree. I suggest starting directly at 1.3.6.1.4.1.8711. However, it won't work on that certain net-snmp your configured anyway.


text:
Q: Syncronize new / modified files trought SFTP on Linux I only have a SFTP access on my NAS, on Lacie OS 3.X, (so exit rsync) and i want to backup it from a remote debian server.
The problem is that the NAS is 4TB and it can take a lot of time if i transfert all files everytimes.
Is there a simple way to do that, based on modification time and or file size in a small script or a command line ?

A: It seems that your NAS can be configured to perform remote backups (which appears to be what you want). This line is of interest
... It can also be a third-party NAS compatible with rsync.
In your case, the remote debian server should be considered a NAS. I expect you can configure rsyncd on it and then configure the NAS to use it as a target.


text:
Q: How to select a file from the gallery? I want to select a picture/movie file via Android gallery. I followed a similar question in SO: Get/pick an image from Android's built-in Gallery app programmatically and this solves the problem somehow.
The question is, in this code, the returned object is of Bitmap type. How can we return a raw file? I mean, I don't want it to be decoded to Bitmap, I just want to receive the file itself, as is.
The following code is part of the solution to this question: Get/pick an image from Android's built-in Gallery app programmatically
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};

Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
final String filePath = cursor.getString(columnIndex);
cursor.close();

Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
/* Now you have choosen image in Bitmap format in object "yourSelectedImage". You can use it in way you want! */

So, how can I do that?

A: All you need to do is,
File myRawFile = new File(filePath);

and then use the file to get what you want. You can read more about File class from here,
https://developer.android.com/reference/java/io/File.html


text:
Q: How to create Channel Factory Hi I'm trying to call a WCF service from within console application, and return this:

Unhandled Exception: System.InvalidOperationException: The underlying channel factory could not be created because no Binding was passed to the ChannelFactory.

My code:
EndpointAddress address = new EndpointAddress("http://xx.xx.xx.xx:xxxxxx/xxxx/FormulationService");

var servis = new ChannelFactory<IFormulasyonHost>().CreateChannel(address);
((IServiceChannel)servis).Open();

if (args[0].ToString() == "-update")
{
   if (args[1].ToString() == "all")
   {
      servis.UpdateAll();
      ((IServiceChannel)servis).Close();
   }
}

A: Assuming the basic binding is used
var address = ...
var binding = new BasicHttpBinding();

var servis = new ChannelFactory<IFormulasyonHost>(binding,address)
    .CreateChannel();


text:
Q: how to check item is exists and renew value only in python gspread How to check item is exists and renew value only, if not exists and add new one?
For example:
I have an item 1 and value 1 already in my sheet, and then I get new value of item 1, I want to renew value 1 only, otherwise, if I get new item 2 and value 2, I want to add this in new columns.
I don't know how to write code, I search it long time but cannot found, could anyone help me? Many thanks!
The script below, the steps are:
first step, check my gmail get keyword 1
second, use keyword search datas in website (beautifulsoup module)
the last step, upload datas to google sheet (gspread module)
def Check_emailbox(box='Inbox', lab='SUBJECT', title='[PASS]'):

    global email_content, report_info1, my_msg, report_info

    dirpath = 'XXX'

    with open(dirpath) as act:
        content = act.read()

    my_act = yaml.load(content, Loader=yaml.FullLoader)
    user, password = my_act['user'], my_act['password']

    imapUrl = 'imap.gmail.com'
    my_mail = imaplib.IMAP4_SSL(imapUrl)
    my_mail.login(user, password)
    print('Login gmail account seccess.')

    my_mail.select(box)
    key = lab
    value = title
    _, data = my_mail.search(None, key, value)
    mail_id_list = data[0].split()
    msg_id = mail_id_list[-1]
    res, data = my_mail.fetch(msg_id, '(RFC822)')
    report_info = []
    if res == 'OK':
        raw_msg_txt = data[0][1]
        try:
            my_msg = email.message_from_bytes(raw_msg_txt)
            print('Subject: ', my_msg['subject'])
            print('From: ', my_msg['from'])
            print('Time: ', my_msg['date'])
            print('------------------------------------------------------------------------------------')
            print('Content:')
            for part in my_msg.walk():
                email_content = part.get_payload()
                report_info.append(email_content)
                report_info1 = ''.join('%s' % id for id in report_info)
                print(report_info1, type(report_info1))
                # print('Hide info, if want to see detail, unmark previous code')
            print('------------------------------------------------------------------------------------')
            # my_mail.store(msg_id, '-FLAGS', '\SEEN')

        except AttributeError:
            my_msg = email.message_from_string(raw_msg_txt)
            print('AttributeError: ', my_msg)

    return email_content, my_msg, report_info, report_info1

Check_emailbox()

keyName = re.findall(r'Daily Report :  (.*?)$', report_info1)
fwName = ''.join(keyName)
print(fwName)
# ↑ This data will be upload to sheet, and this is main item for check:
#    if "feName" is exists, renew below datas only, if not exists, add new one in next row.

fwVersion = ''.join(re.findall(r'\d-(.*?)-', fwName)).rsplit('.',1)[0]
print(fwVersion)

# connect to the website and use beautifulsoup
ele = requests.get('XXXXXX')
felement = BeautifulSoup(ele.text, 'html.parser')
# print(felement.prettify())

fwinfo = felement.find(['a'], text = fwName)
fwhref = fwinfo.get('href')
print('Info: ', fwinfo)
print(fwhref)

rowid = ''.join(re.findall(r'data/(.*?)$', fwhref))
print('Download id is: ', rowid)

fwlink = 'XXXXXXXXX' + rowid
print('Download link: ', fwlink)

json_key = "XXXXXXX"
spread_url = ['https://spreadsheets.google.com/feeds']
connect_auth = SAC.from_json_keyfile_name(json_key, spread_url)
google_sheets = gspread.authorize(connect_auth)
sheet = google_sheets.open_by_key('XXXXXXXXX').worksheet('Pass Data')
Sheets = sheet

upload = []
upload.append(fwName)
upload.append(fwVersion)
upload.append(rowid)
upload.append(fwlink)

Sheets.append_row(upload)

print('==== Uplod to Google Sheet Done. ====')

A: In your situation, how about the following modification?
Modified script:
In this case, please use your google_sheets.
# Please set your values here.
fwName = "###"
fwVersion = "###"
rowid = "###"
fwlink = "###"

sheet = google_sheets.open_by_key('XXXXXXXXX').worksheet("Pass Data")
values = sheet.get_all_values()[2:]
obj = {}
for i, r in enumerate(values):
    obj[r[0]] = i + 3
if obj.get(fwName):
    sheet.update("B" + str(obj.get(fwName)), [[fwVersion, rowid, fwlink]], value_input_option="USER_ENTERED")

*

*When this script is run, first, the values are retrieve from the sheet. And, by searching the value of column "A", new value is put to the searched row.

Note:

*

*I prepared this modified script using your sample image. In your sample image, the 1st 2 rows are header rows. And, the search column is the column "A". I used them. So, when you change your Spreadsheet, this script might not be able to be used. Please be careful about this.

References:

*

*update(range_name, values=None, **kwargs)

*get_all_values(**kwargs)


text:
Q: Using Mosquitto MQTT certs with ActiveMQ So I can follow the steps here
Securing Apache ActiveMQ - How do I use SSL
to secure ActiveMQ and generate the required keystores/truststore for a JAVA client to connect sucessfully.
I can also secure Mosquitto following the steps here
mosquitto-tls — Configure SSL/TLS support for Mosquitto
..and I can connect to Mosquitto securely using mosquitto_pub/sub etc...
What I haven't been able to do is manually create the keystore/truststores that JAVA needs from the Mosquitto steps...
Or follow the ActiveMQ steps and then export the certs/keys for use by non-JAVA apps.
This is for MQTT on port 8883, but I'm sure that same challenges exist for anyone using SSL for sftp/https etc...
If anyone had a link to a good guide or could lists the steps to convert the ActiveMQ keystores/truststores for non-Java use, that would be really helpful.


text:
Q: Symfony2 - 301 redirects for article posts I'm fairly new to Symfony2 and redirects, I am trying to move posts from an articles section into a new section of a website.
Also, do I just leave the original articles as they (as they are indexed with Google's SEO) are in the MySQL database and create new versions of them in the new section?
E.g.,
original location:
http://example.com/articles
http://example.com/articles/this-is-article-1
new location:
http://exmaple.com/
http://example.com/this-is-article-1
I've come across the following in the Symfony2 Cookbook but I am unsure which one I would use.
http://symfony.com/doc/current/cookbook/routing/redirect_in_config.html

A: What you can do is to keep your old routing and add new route in your routing yml or annotation to point to the same action in your controller, this way you keep your old routing to articles which are SEO indexed and use your new routes in your twigs so that they get indexed with time, when you feel the need you don't need the old routing you can delete them when the new routes get better SEO.
Another solution which is redirecting as you asked is this :
routing.yml
root:
    path: /articles
    defaults:
        _controller: FrameworkBundle:Redirect:redirect
        route: new_route_name_articles_index
        permanent: true

This will redirect your http://example.com/articles to your new routing that you created


text:
Q: how to use the nthroot function in R I am trying to use the nthroot function from the pracma package.
However, whenever I run it I get an error:

Error in nthroot(x, 5) : could not find function "nthroot"

I tried installing the pracma package but that didn't help either. Could anyone give me any ideas on why this isn't working?

A: nthroot handles negatives, e.g. returning nthroot(-2,3) == -1.259921, rather than NA
To define this yourself:
nthroot = function(x,n) {
  (abs(x)^(1/n))*sign(x)
}

A: Just do
x ^ (1 / n)

Where n is the root.


text:
Q: OSX won't boot after re-install Got the flashing folder of death.
Tried verifying, repairing the disk. No luck.
Restored from Time Machine. No luck.
Rebooted with Command-Option-P-R. No luck.
The drive as far as I can tell is working properly....
Reinstalled and it still won't boot off the hard drive. How can this be the install worked fine?
Even went as far as putting a bootable USB flash drive and it sees that.
I tried pressing the OPTION key on boot but it only sees the USB drive.
This is madness. How can OSX install on a drive BUT then fail to boot from it?
(I could understand if the drive was failing, but this makes no sense)
I can replace the drive but that seems silly and might not be the issue in the first place.

A: Sounds like the partitioning is damaged.  If you can boot from OS X on an external drive, use Disk Utility to "Repair Disk".  If that reports OK, the Repair the partition with the OS X installation.
The particular kind of Mac might be helpful, and the OS versions.
Also, for Intel Macs, the disk must be partitioned with GUID.  If its gotten to be Master Boot Record or Apple Partition, it won't see the disk as a boot source.


text:
Q: Information Leakage on Page Eviction IIUC Linux doesn't zero out newly allocated memory, and users who care about security should zero the allocation before it is freed to prevent other processes from reading the old content.
However I don't see how this can prevent evicted pages being reused by another process.
Consider process A and M, where A stores a plaintext in memory to be encrypted. Then process M allocates a lot of memory and dumps them. Is there a chance that A's plaintext page could evicted and reused by M, therefore allowing M to read A's data?


text:
Q: Awareness of text under prompt? Continue of this question: here
In 2nd my_processes function:
my_processes() (
  for c in sc rc ed cnorm civis; do eval "$c=\$(tput $c)"; done

  trap 'printf %s "$rc$ed$cnorm"; exit' EXIT INT

  printf %s "$sc$civis"

  while true; do
    printf %s "$ed$(ps -o pid,user,%cpu,command | head -n 30)$rc"
    sleep 1
  done
)

If I use another ps command that contains long list of processes (e.g: no head) in a small wide tmux pane, that would cause text in terminal messed up and some time I resize tmux pane that also cause text messed up.
I current chose above function over zle as zle's cost is flicker.
How to have text display only in a fixed wide of screen/pane (e.g: 10 lines) and be able to go back to its state in event of resize pane for instance.
Thanks in advanced.

A: Within GNU screen, you can run:
screen -X eval split focus 'resize 10' 'screen watch -n1 ps' 'focus prev'

To run watch ps in a 10 line high pane if that's you're looking for.
Note that it runs watch in a new terminal emulator and attached to a new pty device, so ps without arguments like that will only show the processes in that terminal, you'll likely want to adapt the ps line so it shows the processes you want it to show.
Maybe something like:
screen -X eval split \
               focus \
               'resize 10' \
               "screen watch -n1 ps -t $TTY -o pid,user,%cpu,args" \
               'focus prev'


text:
Q: how to create a crystal Report with condition I have a table like this image.

I want to create report from that table with condition.
I want to sum if Purpose Column is Banana then sum LoanAmount. Example: On the table There are 2 records of Purpose= "Banana" So LoanAmount will be 120000 for Banana. I also want to sum LoanAmount if LoanStatus="UC" and so on. How can i create that report?

A: One option is to simply insert a CrossTab in the report header or footer. Set rows to 'Purpose' and value to sum as 'Loan Amount'.
Another option is to create 3 formulas. The one for 'Banana' would look like:
IF {Purpose} = "Banana" Then {LoadAmount} ELSE 0

Then SUM those formulas to get the totals.
You can also use a Running Total with an evaluation condition but the approaches above are better.


text:
Q: Crystal Report PrintToPrinter Timeout Error In VS 2008, I have a crystal main report with about 20 sub reports. These sub reports all run their own individual query. When viewing the report in CrystalReportViewer, I can see the entire report without any hassles. The same thing happens at the client's PC.
The problem comes in at the client when using the PrintToPrinter function. I get a "The server request timed out" error. When using it on my side, it works 100% but not at the client.
To resolve this, I tried increasing the Crystal timeout to 180 seconds via the following command:
oReport.Subreports["TicketBoxCorro.rpt"].DataSourceConnections[0].Attributes.Collection.Set("Command Timeout", "180");
oReport.Subreports["TicketBoxCorro.rpt"].DataSourceConnections[0].SetConnection(this.DBServer, this.DBDatabase, this.DBUsername, this.DBPassword);
The problem is that on the clients machine, the error pops up just after a minute, it never reaches 180 seconds.
Any suggestions?

A: Not to worry, I finally solved this. Perhaps I should have mentioned that my report is printed from an UpdatePanel. Now the error message pops up because the UpdatePanel was timing out - for those who don't know, the default timeout is 90 seconds which I just discovered. You can override this in the script manager.
This probably explains why I had no answers =)


text:
Q: Unable to run single(!) rails interactor at rails 6 Unable to run single(!) rails interactor at rails 6. According to https://github.com/collectiveidea/interactor-rails execute: rails generate interactor authenticate_user to create interactor. Command bin/rspec works perfectly and produce output:
Pending: (Failures listed here are expected and do not affect your suite's status)

  1) AuthenticateUser.call add some examples to (or delete) /Users/.../spec/interactors/authenticate_user_spec.rb
     # Not yet implemented
     # ./spec/interactors/authenticate_user_spec.rb:5

Command bin/rspec spec/interactors/authenticate_user_spec.rb to run single interactor produces error:
An error occurred while loading ./spec/interactors/authenticate_user_spec.rb.
Failure/Error:
  RSpec.describe AuthenticateUser, type: :interactor do
    describe '.call' do
      pending "add some examples to (or delete) #{__FILE__}"
    end
  end

NameError:
  uninitialized constant AuthenticateUser
# ./spec/interactors/authenticate_user_spec.rb:3:in `<top (required)>'
No examples found.

Finished in 0.00004 seconds (files took 0.25648 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

Does anybody know how to run spec for single interactor? As far as I understand interactors dir is not autoloaded. Thanks!
Sincerely yours,
Anna

A: fix: default generator produce "require 'spec_helper'", it should be replaced with "require 'rails_helper'". The problem has been fixed by this replacement.


text:
Q: Executing `where.exe` within PowerShell I'm wanting the same functionality within PowerShell that where.exe gives me.
I've tried to find a cmdlet alternative to the standard where executable but can't find anything.
So by default, I resulted into trying to execute the where command within PowerShell but there is an Alias mapped to that command.

PS C:\> Get-Command where

CommandType     Name                                           Version    Source
-----------     ----                                           -------    ------
Alias           where -> Where-Object

Is there a way to execute where within PowerShell or is there a better way to achieve the same result?

A: Of course, if you do not wish to remove the where alias which points to Where-Object, you can type .exe (typing . followed by the TAB key is enough), as in:
where.exe notepad

Otherwise, have you tried Get-Command (alias gcm) with the -All parameter (PowerShell 3 and later)? For example:
gcm notepad -All

on my machine, gives:
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     notepad.exe                                        10.0.10... C:\Windows\system32\notepad.exe
Application     notepad.exe                                        10.0.10... C:\Windows\notepad.exe
And it will find PowerShell things as well, as in the example gcm where -All which gives:
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           where -> Where-Object
Application     where.exe                                          10.0.10... C:\Windows\system32\where.exe

If you do want to remove the "standard" alias, use Remove-Item alias:where (can by put in a profile file if you want it done at each start-up of PowerShell).

A: I would not remove the existing where alias since this would cause scripts you might use to fail. Instead you could define a new alias for it:
Set-Alias -Name "wherecli" -Value "where.exe"

And then you can use wherecli.

A: I've found a workaround with just the Get-ChildItem and Where-Object but this seems slower than where.exe but thought I'd list it as depending what you're searching it might be useful.
PS C:\> Get-ChildItem -Path "c:\Windows\" -Recurse -File | Where-Object {$_.Name -eq "notepad.exe"}


text:
Q: Data from notification.userInfo I am reading an usb-rawHID-device with
var read_byteArray = [UInt8](repeating: 0x00, count: BUFFER_SIZE)
var result = rawhid_recv(0, &read_byteArray, Int32(BUFFER_SIZE), 50)

I can read the read_byteArray with
for  i in 0...16
        {
           print(" \(read_byteArray[i])", terminator: "")
        }

+++ new read_byteArray in Timer: 0 9 69 0 0,...

I then want to distribute the data with a notification.
        let nc = NotificationCenter.default
        nc.post(name:Notification.Name(rawValue:"newdata"),
                object: nil,
                userInfo: ["data":read_byteArray])

I register the notification and read it with
@objc func newDataAktion(_ notification:Notification)
{
  print("new Data")
  let data = notification.userInfo?["data"]
  print("data: \(String(describing: data)) \n") // data: Optional([0, 9, 51, 0,....
  if let d = notification.userInfo!["data"]
  {
     print("d: \(d)\n") // d: [0, 9, 56, 0, 0,...
     let t = type(of:d)
     print("typ: \(t)\n") // typ: Array<UInt8>
  }
}

The data is of type Array, but my attempts to read an element of this array with
print("element: \(d[1])\n")

gives me the error

Type 'Any' has no subscript members

How can I get the UInt8 elements out of the data?

A: The user info dictionary is of type [String: Any] so when you grab the key out of if you should also cast it to the correct type (otherwise its wrapped in Any and its not an array; type(of:) can tell you its an [UInt8] at run time but the compiler can't know that at compile time unless you tell it):
  if let d = notification.userInfo?["data"] as? [UInt8] {
     d.forEach{ print($0) }
  }


text:
Q: Нужно вывести 8 записей. две первых надо с одной версткой вывести и еще 6 с другой Нужно вывести 8 записей из таблицы. В один div блок две заметки (картинка, название, краткое описание и т.д.), а во второй div блок, еще шесть заметок (картинка и название).Уже задавал этот вопрос но так и не понял, объясните пожалуйста на коде.

                    <?php if($brands): ?>

                                <?php foreach($brands as $brand): ?>

<?=$brand->title;?>

 <?=$brand->title;?>  3

<?=$brand->description;?>

                                <?php endforeach; ?>

                                            <?=$brand->title;?>

 <time datetime="2017-01-10T03:34:37+00:00" class="meta-item">Jan 10, 2017</time>

                    <?php endif; ?>

A: Вы можете вывести из исходного массива несколько элементов и удалить их после вывода, а в другом блоке ниже, вы снова перебираете этот-же массив но уже в нем ну будет выведенных ранее элементов.
Второй вариант решения данной проблемы как правильно заметил splash58 и я полагаю дал вам ответ в предыдущем вашем вопросе это использовать array_splice вы просто можете брать нужные вам элементы и скажем 1-ый раз перебрать первые 2 от массива а второй раз все остальные исключая первые два.

<?php if($brands): ?>

      <?php foreach($brands as $key => $brand): ?>

<?=$brand->title;?>

 <?=$brand->title;?>  3

              <?=$brand->description;?>

      <?php unset($brands[$key]); ?>

      <?php if($key >= 1) break; ?>
      <?php endforeach; ?>

      <?php foreach($brands as $brand): ?>

            <?=$brand->title;?>

 <time datetime="2017-01-10T03:34:37+00:00" class="meta-item">Jan 10, 2017</time>

      <?php endforeach; ?>

<?php endif; ?>


text:
Q: How can one safely add html code to a wordpress theme header file? I tried adding some HTML code to a WordPress theme header file. It worked well at least that's what I thought but when I click one of my post, it redirects the whole site to the same posts over and over again. The pictures and titles are so different though so I am sure it loops correctly. I feel it is where I am adding the HTML code. It is in the theme header PHP file. How can I do this better?

    <?php
                    if(!is_front_page()){
                        echo '

                          Trending

                                   ';
                                global $wpdb;
                                $query = new WP_Query(array(
                                 'posts_per_page' => 12,
                               'category_name' => 'featured-posts',
                                       ));
                                 $posts =  $query -> posts;

                                 ?>
                                 <?php
                                foreach ($posts as $post) {
                                echo '

                               guid.'" class="card">

                                   ID, 'thumbnail' ).'" alt="">
                               /div>

'.$post->post_title.'

                                ';

                                 ?>
                                <?php }
                               echo '

                     <button class="prev">

                    </button>
                    <button class="next">

                     </button>

                    ';

                    ?>
                    <?php } ?>

my code
Website header php file code I added it to the site grid.

                        <?php $zox_lead_page2 = get_option('zox_lead_page2'); if (($zox_lead_page2 == "1" && is_front_page()) || ($zox_lead_page2 == "2" &&  ! is_404()) || ($zox_lead_page2 == "3" && ! is_front_page() && ! is_404())) { ?>
                            <?php $zox_lead_img2 = get_option('zox_lead_img2'); $zox_lead_url2 = get_option('zox_lead_url2'); if ($zox_lead_img2 && ! is_404()) { ?>

                                    <a href="<?php echo esc_url($zox_lead_url2); ?>" target="_blank">
                                    <img src="<?php echo esc_url($zox_lead_img2); ?>" />

                            <?php } else { ?>
                                <?php $zox_lead_ad2 = get_option('zox_lead_ad2'); if ($zox_lead_ad2 && ! is_404()) { ?>

                                        <?php echo html_entity_decode($zox_lead_ad2); ?>

                                <?php } ?>
                            <?php } ?>
                        <?php } ?>


text:
Q: How to handle mixing of different libraries (eg. stl and eigen3) that use different types for indices (size_t, int, ...) I have following problem. I have some code that uses Eigen3. Eigen3 uses int or long int for indices. At some points in the code I have to store values from the eigen-arrays in a std::vector.
Here is some example:
std::vector myStdVector;
Eigen::VectorXd myEigen;
....

for(size_t i=0; i<myStdVector.size(); i++)
{
    myStdVector[i] = myEigen(i);
}

Here I get the compiler warning:

warning: implicit conversion loses integer precision: 'const size_t'
  (aka 'const unsigned long') to 'int'

So of course I could add a static_cast<int>(i) to all the functions where such a scenario occurs, but I wonder if there is a better way to deal with such things. I guess this happens with many other "library-mixing" too.

A: In this specific case, I would suggest using the smaller container's index type; this would be Eigen's index type, as determined by your Eigen::VectorXd.  Ideally, it would be used as Eigen::Index, for forwards-compatibility.
It might also be worth looking into how Eigen defines its index type.  In particular, you are allowed to redefine it if necessary, by changing a preprocessor directive, by #defineing the symbol EIGEN_DEFAULT_DENSE_INDEX_TYPE; it defaults to std::ptrdiff_t.
[Note, however, that in my own code, I generally prefer to use the larger index (in this case, size_t), but do range checks as if using the smaller of the index types if applicable (in this case, Eigen::Index).  This is just a personal preference, however, and not necessarily what I consider to be the best option.]

Generally, when trying to choose the best index type, I would suggest that you look at their available ranges.  First, if one or more of the potential types are signed, and if one or more signed potential type allows negative values*, you'll want to eliminate any unsigned types, especially ones that are larger than the largest signed type.  Then, you'd look at your use case, eliminate any types that aren't viable for your intended purpose, and choose the best fit out of the remaining potential types.
In your case specifically, you want to store values from an Eigen3 container in an STL container, where the Eigen3 container is indexed with ptrdiff_t and (as mentioned in your comment) to your knowledge only uses non-negative index values.  In this case, either is a viable option; the range of non-negative index values provided by ptrdiff_t fits nicely inside size_t's range, and the loop condition will be determined by your VectorXd (and thus is also guaranteed to fit inside the Eigen3 container's index type).  Thus, both potential types are viable choices.  As the additional range provided by size_t is currently unnecessary, I would consider the index type provided by your Eigen setup to be slightly better suited to the task at hand.
*: While it's typically safe to assume that index values will always be positive due to how indexing works, I can see a few cases where allowing negatives would be beneficial.  These are typically rare, though.
Note that I assumed the loop condition i<myStdVector.size() in your example code was a typo, due to not lining up with the initial description or the operation performed inside the loop body.  If I was incorrect, then this decision becomes more complex.


text:
Q: Dismissing a view with SwiftUI I want to show an instruction page the first time a user opens my app. I have gotten this to work, but I cannot understand how to get back to the contentView (without restarting the app).
Just to clarify: I want the "Dismiss this view" button on InstructionView to set the view to be shown to "ContentView" and to dismiss the InstructionView. As it is now the viewRouter.setToContentView() makes the App crash, and I cannot get around it.
Thanks in advance
TestDismissApp
import SwiftUI

@main
struct TestDismissApp: App {
    var body: some Scene {
        WindowGroup {

            MotherView()
        }
    }
}

MotherView
import SwiftUI

struct MotherView : View {

    @ObservedObject var viewRouter = ViewRouter()

    var body: some View {
        VStack {
            if viewRouter.currentPage == "InstructionView" {
                InstructionView()
            } else if viewRouter.currentPage == "ContentView" {
                ContentView()
            }
        }
    }
}

ViewRouter
import Foundation

class ViewRouter: ObservableObject {
    init() {
        //UserDefaults.standard.set(false, forKey: "didLaunchBefore") remove // if you want to show the instructions again for test reasons
        if !UserDefaults.standard.bool(forKey: "didLaunchBefore") {
            UserDefaults.standard.set(true, forKey: "didLaunchBefore")
            currentPage = "InstructionView"
        } else {
            currentPage = "ContentView"
        }
    }

    func setToContentView () {
        currentPage = "ContentView"
    }

    @Published var currentPage: String

}

ContentView
import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("My wonderful content")
            .padding()
    }
}

InstructionView
import SwiftUI

struct InstructionView: View {
    @Environment(\.dismiss) var dismiss
    @EnvironmentObject var viewRouter: ViewRouter
    var body: some View {
        VStack {
            Text("Instruction: This app shows a wonderful sentence")

            Button {
                viewRouter.setToContentView()
                dismiss()
            } label: {
                Text("Dismiss this view")
            }

        }
    }
}

A: try this:
in MotherView use @StateObject var viewRouter = ViewRouter()  and
InstructionView().environmentObject(viewRouter)


text:
Q: Microservices using .net Framework 4 and above ( instead of .NET Core) I am a .net developer and trying to learn implementing Microservice using .NET Framework >4.0.
All the article that I refer from internet search, they all talks about implementing Microservices using .NET Core.  But I wonder, I could not find any article that says how to develop microservice using .NET Framework >4.0.
I knew that .net core has all the features and run time for Microservices but my question is as below
Question -
1. Is not possible develop Microservice using .NET framework at all ? If not then what are all constrain and limitation ?
2. What are the alternatives if we choose .NET Framework only to develop Microservices oriented architecture
3. Any example/ sample code will be helpful
Thank you

A: As mentioned in the comments, microservices (MS) is not bound to any language, it's an architectual principle.

Microservices are a software development technique —a variant of the
  service-oriented architecture (SOA) structural style— that arranges an
  application as a collection of loosely coupled services. In a
  microservices architecture, services are fine-grained and the
  protocols are lightweight.
https://en.wikipedia.org/wiki/Microservices

You can build MS/SOA with any language and a variety of platform solutions, but there are drawbacks of course to some implementations.
All you do is define a small service A and another small service B to act as your system, exposing data through lightweight REST API(s) (maybe even gRPC) and let them talk to each other - and voila! you have your MS system.
But why are e.g. Microsoft pushing to use .NET Core for MS systems? My best guess would be because of Docker (and other container solutions), to containerize each MS. The difference between .NET Core and .NET Framework in this context is containerization, .NET Core can run on all platforms, such as linux - and docker supports linux containers.

In computing, self-contained system (SCS) is a software architecture
  approach that focuses on a separation of the functionality into many
  independent systems, making the complete logical system a
  collaboration of many smaller software systems
https://en.wikipedia.org/wiki/Self-contained_system_(software)

Why are the linux containers important? Well, I would argue because of Kubernetes (or other container orchestration tools).

Kubernetes (commonly stylized as k8s) is an open-source
  container-orchestration system for automating application deployment,
  scaling, and management. It was originally designed by Google, and
  is now maintained by the Cloud Native Computing Foundation. It aims to
  provide a "platform for automating deployment, scaling, and operations
  of application containers across clusters of hosts". It works with
  a range of container tools, including Docker. Many cloud services
  offer a Kubernetes-based platform or infrastructure as a service (PaaS
  or IaaS) on which Kubernetes can be deployed as a platform-providing
  service. Many vendors also provide their own branded Kubernetes
  distributions.
https://en.wikipedia.org/wiki/Kubernetes

Kubernetes is a very powerful container orchestration system. I't can scale your loosely coupled MS linux containers at will - and so much more.
Now, I'd suggest you to keep on reading, a good start would be this:
Read

*

*https://learn.microsoft.com/en-us/dotnet/architecture/microservices/
Source code

*

*https://github.com/dotnet-architecture/eShopOnContainers

*https://github.com/EdwinVW/pitstop
Videos

*

*https://www.youtube.com/watch?v=-AfZxdXa7yc

*https://www.youtube.com/watch?v=qWUINCZHs6E


text:
Q: webview doesn't show URL I am new to iOS development, i am trying to use a UIWebView using the following code
import UIKit
class SecondViewController: UIViewController {
@IBOutlet var myWebView: UIWebView!
@IBOutlet var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let url = NSURL (string: "http://www.chrisharrisracing.com/twitterapp.php");
        let requestObj = NSURLRequest(URL: url!);
        myWebView.loadRequest(requestObj);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

However when I build the the web page is not displayed, although when I go to the web address in a browser the page works fine, any help would be appreciated

A: I just created a sample project to check your issue and its working for me.
class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL (string: "http://www.chrisharrisracing.com/twitterapp.php");
        let requestObj = NSURLRequest(URL: url!);
        webView.loadRequest(requestObj);

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

If you want you can  download the sample project from the following link
https://www.dropbox.com/home/SAMPLE%20GIT%20PROJECTS%20%5BSHARED%5D/WEBVIEW?preview=webViewSample.zip

You should add NSTransportSecurity to info.plist
HOPE THIS HELPS.....

A: I made a sample project with your code and it works just fine. The only difference is that I didn't use the second outlet (@IBOutlet var webView: UIWebView!) you have in this code. My guess is you haven't added any constraints for your webview and that's why you can't see it. So go to your storyboard choose your webview and then go to the triangle icon at the bottom right and choose Add missing constraints.

Of course make sure your internet connection is ok and that you have added the allow arbitrary loads key in your info.plist

A: Maybe you haven't added your constraints yet, which is why myWebView might not be visible. Or maybe, this is probably a longshot, but I've noticed that you have another unused UIWebView called webView. Maybe, just maybe, webView is covering up myWebView, thus you aren't seeing myWebView loading the page.


text:
Q: Given $\|x\| \leq 1$ in an infinite dimensional Hilbert space, show there exists a orthonormal sequence that converges weakly to $x$ Let $H$ be an infinite dimensional Hilbert space. Given $x\in H$ with $\| x\| \leq1$, show there exists an orthonormal sequence $(x_n)$ such that $(x_n)$ converges weakly to $x$.
Below are my ideas and thoughts so far:
I thought about using the orthonormal basis to construct such sequence. But since we don't know if $H$ is countable, we can't assume there exists an orthonormal basis.
Also note that using Bessel's inequality, if we have an orthonormal sequence we have
$\sum_{n} |\langle x,x_n\rangle|^2 \leq \| x\|^2=1$.
So $\lim _{n \rightarrow\infty} \langle x,x_n\rangle^2 =0$.
Hence $\lim _{n \rightarrow\infty} \langle x,x_n\rangle =0$, which tells us $x_n$ converges weakly to zero.
But I'm not sure if this helps us with the question...
Any hints or ideas will be appreciated!
Thank you

A: This is only possible if $x=0$.
Suppose that $(x_n)$ converges weakly to $x$ and is an orthonormal sequence.
Then you have already shown that
$$
\lim_{n\to\infty} \langle x,x_n\rangle =0
$$
holds. From the weak convergence $x_n \rightharpoonup x$
we conclude
$$
\|x\|^2 = \langle x,x\rangle = \lim_{n\to\infty} \langle x,x_n\rangle =0.
$$
Therefore, $x=0$.
Constructing an orthonormal sequence $(x_n)$ which converges weakly to $0$ can be done in the usual way.


text:
Q: How do I see the FPS of playback in VLC and other video players in windows? I play animated videos and notice a lag or frame drop.
I learned later that this is due to Japanese anime being not fully animated due to low budgets.
But I want to be sure. Nvidia Geforce FPS overlay is not working for Video players.
Is there a program to show FPS of video playback in VLC and other players?

A: Try Fraps. It works with video and graphic sources that don't work with other FPS overlay programs.

I tested it with VLC and the framerate is constant 24 FPS. It seems that the poor animation is the cause of my concern and not my PC.

A: The other answer was posted nearly a year before the release of VideoLAN 3.0.0 (2018-02-09).  According to this forum post...

Fraps doesn't work for me with vlc 3.0.x. No overlay, no recording, no screen capture.

...and my experience is the same with v3.0.16: there is no overlay and the CSV logs indicate something like 1 frame/second.  I tried the workaround posted in the reply...

... I got them to work together by changing video output module in VLC to 'OpenGL video output for Windows' (Preferences > show settings: All > Video > Output modules > Video output module)

...and while that did succeed in making Fraps's overlay appear, that alternately caused poor performance or screen artifacts.
Instead, on AlternativeTo I found a tool called FPS Monitor that lets you monitor various system components with a customizable screen overlay.  Even in trial mode I was able to use it to monitor the playback framerate in VLC.  The one thing that tripped me up, however, is that VLC media player must be started after FPS Monitor; it's not enough to just stop and restart video playback.  Other than that, I was able to get not only numbers but a live graph of the information I was looking for (Scenes → Recent scenes → BENCHMARK is a good preset to use).  Neat.


text:
Q: Regular expression not returning everything on pattern in python I'm using https://regexr.com/ for testing the regex pattern with the following,

but when I try to use the same pattern in python I got

how can I rewrite the python pattern so I can retrieve the "state of " as in the regexr site?

A: Put the whole string you want to capture into parentheses. Note that with multiple capture groups, the result will be a list of tuples (the first element of the tuple will be the first capture group):
import re
re.findall(r'state.*.(ny|new york)', 'consumption state of ny ')

['ny']
re.findall(r'(state.*.(ny|new york))', 'consumption state of ny ')

[('state of ny', 'ny')]

A: Assuming you want to match patterns such as "state of ny" or "state that is named new york", you should put the entire string you want to capture into parentheses and use a non-capturing group for the alternative.
re.findall(r'(state.*.(?:ny|new york))', " consuption state of ny  ")

Additionally, .*. could be written as .+ to be a little more concise.


text:
Q: Use DBCC with select I'm trying to get the MessageText field from DBCC output, but this returns syntax error
SELECT MessageText FROM (DBCC CHECKDB (test) WITH TABLERESULTS)

What should I use?
In SMSS it can detect and return the MessageText field only, how did microsoft do it?

A: To get back, directly in your program, the results of a DBCC command you need to subscribe to the InfoMessage event of the SqlConnection class.
void Main()
{
    string db = "Linqpadtest";
    List<string> messages = new List<string>();
    using(SqlConnection cnn = new SqlConnection("Data Source=;Initial Catalog=master;Integrated Security=True;"))
    {
        cnn.Open();
        cnn.InfoMessage += (s, e) =>
        {
            messages.Add(e.Message);
        };
        SqlCommand cmd = new SqlCommand($"DBCC CHECKDB ('{db}')", cnn);
        _ = cmd.ExecuteScalar();
        string result = string.Join(Environment.NewLine, messages);
        Console.WriteLine(result);
    }
}

A: When you specify WITH TABLERESULTS, the results come back as a table. However, it is difficult to access it via SQL, as it is similar to getting results from a stored procedure.
You could use INSERT...EXEC..., perhaps, but in C#, you can just use standard ADO reading mechanisms to get a specific column.
The easiest way to do this is with a DataReader:
using(var cnn = new SqlConnection(YourConnString))
using(var cmd = new SqlCommand("DBCC CHECKDB (test) WITH TABLERESULTS", cnn) {CommandTimeout = 3600});
{
    cnn.Open();
    using(var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
            Console.WriteLine(reader["MessageText"]);
    }
}

I have added CommandTimeout = 3600 because CHECKDB can take a long time.


text:
Q: Two Questions Involving Differential Equations Calculus Given the equation $x''(t)+k^2x(t)=0$, how do I find a correct solution to the equation? I tried letting $x(t) = c$, where c is a constant, so that $x'(t) = 0$. But the equation won't make sense since $x''(t)$ will also be 0, and there won't be a solution. I consulted with someone else and they said that it should be a sinusoidal equation - which I don't know how to obtain from this.

A: I'll just answer the first question for now. Your friend said it should be a sinusoid because the equation relates the derivative of a function to the function itself - think of how the second derivative of sine is a constant times sine itself.
More generally, it would be better to use an exponential (because by Euler's formula sines and cosines are linear combinations of exponentials). So assume your function has form $x(t)=ce^{lt}$ for some undetermined $c,l$. Substitute this into your equation to get $cl^2e^{lt}+k^2ce^{lt}=0$. You can cancel the exponentials here and just get an algebraic equation for $l$ in terms of $k$. So $l = \pm ik$. Since linear combinations of solutions to homogenous ODEs are also solutions, we have to add the solution with $l=ik$ and the solution with $l=-ik$. Our solution said nothing about $c$, in order to get this kind of information you would need some initial conditions. Hence your solution is $x(t) = c_1e^{ikt}+c_2e^{-ikt}$.


text:
Q: How to get the "fragment" part of an url in a nuxt middleware? I want to get the access_token in the url after a redirection from AWS COGNITO in a "implicit" oauth flow.
AWS Cognito redirect the browser to : https://mydomain/#access_token=xxxxx
I want to get the "access_token=xxxxx" part for storage, in a nuxt "middleware".
It doesn't seam to be in the "context.req" object. Where can I find it ?

A: The Implicit flow doesn't return an authorization code like the Authorization flow does. You'll get the access token directly in the response body.
Here is a link with more info.
Implicit Flow


text:
Q: htaccess redirect error - What's wrong? In localhost, I would like to make a redirect, but I don't understand what's wrong.
RewriteEngine on
RewriteCond %{REQUEST_URI} !/index.php$
RewriteCond %{REMOTE_HOST} !^127.0.0.1
RewriteRule $ namepage.php [R=302, L]

A: You can't have spaces inbetween flags, it gets parsed as a separate parameter for the RewriteRule directive:
RewriteRule $ namepage.php [R=302,L]


text:
Q: Why 'dict(Count(list)) does not work in python for windows? def codon_usage(seq, aminoacid):
    """Provides the frequency of each codon encoding a given aminoacid in a DNA sequence"""
    tmpList = []
    for i in range(0, len(seq) - 2, 3):
        if DNA_Codons[seq[i:i + 3]] == aminoacid:
                tmpList.append(seq[i:i + 3])

    freqDict = **dict(Counter**(tmpList))
    totalWight = sum(freqDict.values())
    for seq in freqDict:
        freqDict[seq] = round(freqDict[seq] / totalWight, 2)
    return freqDict

Hello, I was trying this code but I have a problem for making it run. 'dict(Counter(list)' is supposed to retrieve a dictionary where key is my sequence and the value is how many times that key appears. But, the error message is that 'count' variable is not defined. This code is from a video which uses Linux
Can someone help me?

A: You need to import Counter:
from collections import Counter


text:
Q: HTML5 Audio Player: How to select by HTML elements instead of div ID's? Making an html5 player, I'm moving away "from divs with id's" towards "simple html elements".
Old Situation (works)
<audio src="track1.mp3" id="audio"></audio>
<controls>
    <play id="play" style="display:none">PLAY</button>
    <pause id="pause" style="display:none">PAUSE</button>

</controls>

Javascript gets elements by divs with an id
var myAudio = document.getElementById('audio');
var play = document.getElementById('play');
var pause = document.getElementById('pause');
... etc

Desired Situation (doesn't work fully)
<audio src="track1.mp3"></audio>
<controls>
    <play style="display:none">PLAY</play>
    <pause style="display:none">PAUSE</pause>
    <progress><bar></bar></progress>
</controls>

Updated Javascript, after help of @grateful & @Nathan Montez works partially
var myAudio = document.getElementsByTagName('audio')[0];
var play = document.getElementsByTagName('play')[0];
var pause = document.getElementsByTagName('pause')[0];
... etc

In the new version the progress bar does not work! What have we overlooked? Thanks!

A: document.getElementsByTagName('audio') will return an array, even if it only has a length of 1. You need to do this:
document.getElementsByTagName('audio')[0];

A: Moving comment to an answer:
Remove the double quote from the  tag.
It is currently <progress"></progress>
It should read <progress></progress>
Update:
I think that the cause of your problem is that the elements are resolving to HTMLUnknownElements. Because of this, you may need to work with something like Google Polymer to provide the kind of functionality you are looking for. I don't think you can use Unknown Elements directly like this because they don't have the same API that the native HTMLElement objects do.


text:
Q: Como usar o passport.js em node para fazer login contra a base de dados Como usar o passport.js para controlar acesso usando a base de dados e o middleware do express.js.
Como fazer a lógica de login e como saber que a sessão já está autorizada cado o utilizador já tiver feito login?

A: O passport integra-se bem nos middlewares do express e tem métodos asíncronos para fazer a verificação de autenticidade do user/pass.
No meu setup uso node-mysql e verifico com username e password (em hash MD5), e dividi a parte do passport em 3 partes:

*

*configuração

*autenticação no momento do login

*verificação via middleware de req.user
Nota: Pelo que percebo o passport precisa do express-session que desde a versão 4 do expressjs é um módulo/middleware à parte.
como eu fiz:
Primeiro tratei da configuração do passport em todas as rotas de middleware. Isso inclui passar os middlewares para a rota onde tenho a parte segura do site: app.use('/admin', middleware.
Depois configurei também a parte de interação com a base de dados (MySql via node-mysql). Não includo a parte de iniciação da DB, mas junto no código a query que verifica o user/pass contra a base de dados usando o MD5 para gerar a hash da password.
Depois desta parte do login, que é diferente do middleware das páginas já com a autentificação feita, configurei o middleware que verifica se req.user está preenchido. O passport coloca nessa propriedade do request o user, e assim podemos saber que estamos numa sessão autorizada/autenticada.
O meu setup:
index.js
var express = require('express');
var passport = require('passport');
var session = require('express-session');

var app = express();
var sess = {
  secret: 'keyboard cat',
  cookie: {}
}

if (app.get('env') === 'production') {
  app.set('trust proxy', 1) // trust first proxy
  sess.cookie.secure = true // serve secure cookies
}

app.use('/admin',   session(sess));                         // enable sessions
app.use('/admin',   passport.initialize());                 // configuração do passport
app.use('/admin',   passport.session());                    // configuração do passport
app.use('/admin',   require('./routes/services/admin'));    // router para a zona que requer acesso

routes/services/admin.js
var md5 = require('md5');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var express = require('express');
var router = express.Router();

passport.use(new LocalStrategy(function(username, password, done) {
    // verificação de user/pass
    db.query('SELECT * FROM users WHERE username=? AND password=?', [username, md5(password)], function(err, rows){
        if (err) return done(err);
        var user = rows.length && rows[0].id; // podia passar mais info sobre o utilizador aqui
        done(null, user); // tudo ok! chamar a callback do passport
    });
}));

var authenticate = passport.authenticate('local', {
    // aqui pode configurar-se também sucessRedirect
    failureRedirect: '/admin/login',
    failureFlash: true
});

// configuração recomendada
passport.serializeUser(function(user, done) {
  done(null, user);
});
passport.deserializeUser(function(user, done) {
  done(null, user);
});

// middleware para verificar se a sessão está criada
function gateKeeper(req, res, next){
    if (req.user) next();
    else res.redirect('/admin/login');
}

// página de login
router.get('/login', function(req, res) {
    res.render('admin/login');
});

// tratar os dados de autenticação via POST com o middleware "authenticate"
router.post('/login', authenticate, function(req, res) {
    res.redirect('/admin/home');
});

// router para a parte segura, usando o middleware "gatekeeper"
router.get('/:page', gateKeeper, function(req, res) {
    res.send('Welcome to page ' + req.params.page); // resposta simplificada
});

Disclaimer:
Coloquei esta resposta depois de aprender à bruta como fazer. Se houver erros, maneiras melhores ou coisas que faltam: digam! Em forma de resposta nova ou comentário.
"Disclaimer" que dizer "para informação vou explicar algo para nõ pensarem mal de mim..." :)
Mais leitura (em inglês):

*

*http://toon.io/understanding-passportjs-authentication-flow/

*http://passportjs.org/docs/authenticate

*https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/

*https://www.youtube.com/watch?v=FgdEHhUR3ag


text:
Q: VBA : get Long limits programmatically Is there a way in VBA to programmatically get the limits (minimum value, maximum value) of a numeric type (Long for instance) ?
Something like the numeric_limits<long>::min() in C++.

A: No, but they're fixed size anyway, so you can infer them directly.
Here's some info on their sizes: http://msdn.microsoft.com/en-us/library/aa164754.aspx
From the article:

The Integer and Long data types can both hold positive or negative values. The difference between them is their size: Integer variables can hold values between -32,768 and 32,767, while Long variables can range from -2,147,483,648 to 2,147,483,647. Traditionally, VBA programmers have used integers to hold small numbers, because they required less memory. In recent versions, however, VBA converts all integer values to type Long, even if they are declared as type Integer. Therefore, there is no longer a performance advantage to using Integer variables; in fact, Long variables might be slightly faster because VBA does not have to convert them.

A: I don't think there's a function for that. I would create a library of const values for each number type then you could reference this.

A: For a programming platform with 32-Bit articuture: "Dim Item1 As Long", variable is 32-Bit in length. This means that each Long dimmed variable is 32-Bit. he maximum value it can contain (positive or negative) is a little over 2 billion.
    Sub sumall()
    Dim firstRow As long
   firstRow = 5
   Dim lastRow Aslong
   lastRow = 12
  Dim aRow As long
  Dim sumall As Variant
  Dim sumResult As Variant
  sumResult = 0
  Dim previousValue As Variant

  previousValue = -1
  For aRow = firstRow To lastRow
    If Cells(aRow, 2).Value <> previousValue Then
        sumResult = Cells(aRow, 2).Value
        previousValue = Cells(aRow, 2)
    End If
  Next aRow
sumall = sumResult
End Sub

Another option for the tasc would be to use scriptingDictionary to get unique values only:
                Sub sumall()
                Dim objDictionary As Object
                Dim firstRow As Long
                firstRow = 5
                Dim lastRow As Long
                lastRow = 12
                Dim aRow As Variant
                Dim varKey As Variant
                Dim sumResult As Variant

                Set objDictionary = CreateObject("Scripting.Dictionary")

                For aRow = firstRow To lastRow
                        If objDictionary.exists(Cells(aRow, 2).Value) = False Then
                        objDictionary.Add Cells(aRow, 2).Value, True
                        End If

                Next aRow
                sumResult = 0
                For Each varKey In objDictionary.keys
                sumResult = varKey + sumResult
                Next varKey

                End Sub

A: Sub highlong()
Dim x As Long
On Error GoTo Prt
Do While True
   x = x + 1
Loop
Prt:
   MsgBox (x)
End Sub

Whatever floats your boat.


text:
Q: Getting Sonarqube to show a code Coverage score for a simple Java/JUnit/Maven project with Jacoco plugin I'm practicing on a very small Java/JUnit/Maven project with the Jacoco plugin to practice with the Code Coverage feature of Sonarqube.
The core code for the example is small. Here is the class under test:
package com.somebody.sonarqube;

public class Calculator {

    // Method to add two numbers
    public int addNumbers(int one, int two) {
        return one + two;
    }

    // Method to subtract two numbers
    public int subtractNumbers(int one, int two) {
        return one - two;
    }
}

And here are the unit tests:
package com.somebody.sonarqube;

import static org.junit.Assert.*;

import org.junit.Test;

public class CalculatorTest {

    @Test
    public void testAddNumbers() {
        Calculator myCalc = new Calculator();
        assertEquals(10, myCalc.addNumbers(5, 5));
    }

    @Test
    public void testSubtractNumbers() {
        Calculator myCalc = new Calculator();
        assertEquals(5, myCalc.subtractNumbers(10, 5));
    }

}

The two methods in the class under test are covered by the two unit tests respectively, so as far as "Code Coverage" is concerned, that Sonarqube score should be 100%.
When trying to get this score after running my "clean test sonar:sonar" Maven build targets, I'm getting 0% instead:

So the part I'm having the most trouble with is getting the various components in the pom.xml file working together. At this time there's a warning at the <systemPropertyVariables> block at the bottom that reports Invalid plugin configuration: systemPropertyVariables. Here's the full pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.somebody.sonarqube</groupId>
   <artifactId>HelloSonarqube</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>HelloSonarqube</name>
   <description>Small example of Sonarqube and JUnit tests.</description>

   <properties>
      <maven.compiler.source>11</maven.compiler.source>
      <maven.compiler.target>11</maven.compiler.target>
   </properties>

   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.13.2</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.sonarsource.scanner.maven</groupId>
         <artifactId>sonar-maven-plugin</artifactId>
         <version>3.9.1.2184</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
         </plugin>
         <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.22.2</version>
         </plugin>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.9.0</version>
            <configuration>
               <release>11</release>
            </configuration>
         </plugin>
         <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.7</version>
            <executions>
               <execution>
                  <id>prepare-agent</id>
                  <goals>
                     <goal>prepare-agent</goal>
                  </goals>
               </execution>
               <execution>
                  <id>report</id>
                  <phase>prepare-package</phase>
                  <goals>
                     <goal>report</goal>
                  </goals>
               </execution>
               <execution>
                  <id>post-unit-test</id>
                  <phase>test</phase>
                  <goals>
                     <goal>report</goal>
                  </goals>
                  <configuration>
                     <dataFile>target/jacoco.exec</dataFile>
                     <outputDirectory>target/jacoco-ut</outputDirectory>
                  </configuration>
               </execution>
            </executions>
            <configuration>
               <systemPropertyVariables>
                  <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
               </systemPropertyVariables>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

I've tried a lot of variations to this, including changing JUnit 4 to version 5 (I'd be interested to hear about issues on this too). From my reading I generally understand that the Eclipse/JUnit lifecycle is not fully working harmoniously with the Maven lifecycle by default, hence it's missing something. The solutions I've seen/tried are quite specific to certain project setups, and  I have tried manually setting "arguments" and other changes. Would be really thrilled to see your opinions on this having spent a number of hours playing with different versions.

A: I was able to finally answer the question based upon a similar example I just found on this GitHub project:
https://github.com/SonarSource/sonar-scanning-examples/tree/master/sonarqube-scanner-maven/maven-basic
In short, they used "clean verify sonar:sonar" rather than "clean test sonar:sonar" Maven build targets. The change triggered the code coverage plugin that I was looking for to publish code coverage scores in the Sonarqube dashboard.
As an aside, the warning message I also shared regarding <systemPropertyVariables> was not critical to solving the problem, and I decided to go without that part of the code, and still get all the reports in the Sonarqube dashboard I was looking for.


text:
Q: create table syntax error in Microsoft Access? Here is my code, i'm trying to make multiple tables:
Create Table Order_t
(
Id AutoIncrement Not Null,
OrderDate DateTime Not Null,
CustId Int Not Null,
Primary Key(Id),
Foreign Key(CustId) References Customer_t(Id)
(;
Create Table PersonRole_t
(
PersonRoleID Autoincrement Not Null,
Person_ID int Not Null,
Primary Key(PersonRoleID, Person_ID),
Foreign Key(Person_ID) References Person_T(Person_ID)
(;
Create Table Product_t
(
Id Text(10) Not Null,
Name Text(30) Not Null,
Description Text(30),
Finish Text(30),
UnitPrice Currency Not Null,
Primary Key(Id)
) ;

Whenever I run it in Microsoft Access, I get an error in the CREATE TABLE statement (it highlights the PersonRole_T table definition). Not sure what to do, rather new to SQL.

A: Use CLOSE parenthesis at the end of CREATE Table statement instead of OPEN parenthesis
Create Table Order_t
(
Id AutoIncrement Not Null,
OrderDate DateTime Not Null,
CustId Int Not Null,
Primary Key(Id),
Foreign Key(CustId) References Customer_t(Id)
); -- Not (;

Create Table PersonRole_t
(
PersonRoleID Autoincrement Not Null,
Person_ID int Not Null,
Primary Key(PersonRoleID, Person_ID),
Foreign Key(Person_ID) References Person_T(Person_ID)
); -- Not (;

A: The table Person_T with a key of Person_ID needs to exist before the References Person_T(Person_ID) statement can execute. Based on your naming convention, I would guess the statement should rather be References Person_T(Id).
Consider changing your naming convention so that a data element does not change its name depending its location realtive to tables/views. Also consider whether the _t suffix is worth the bother.
@Prdp's point about the close parens is valid too.