mercredi 27 novembre 2019

If statement create array within an array

How if at all possible could an if statement add an array within an array.

example.

array(
  array(
    'name' => 'name',
    'type' => 'type',
    'label' => 'label',
  ),
  if( $a = $x ){
     array(
       'name' => 'name',
       'type' => 'type',
       'label' => 'label',
     ),
  }
  array(
    'name' => 'name',
    'type' => 'type',
    'label' => 'label',
  ),
)

I receive a parse error unexpected 'if' (T_IF), expecting ')'

Dynamic Menu with Submenu Vuejs and JSON

Hi guy's here's what I'm trying to do.

I want to create a vertical menu with sub menus on it. using this json code:

"response": {
        "data": [
            {
                "id": 1,
                "name": "AC Articles",
                "subname": {
                    "data": [
                        {
                            "id": 14,
                            "sub_category": "Window PC"
                        },
                        {
                            "id": 15,
                            "sub_category": "Mac PC"
                        }
                    ]
                }
            },
            {
                "id": 2,
                "name": "MyPage Articles",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 3,
                "name": "PC/Internet Optimization",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 4,
                "name": "Troubleshooting Guide",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 5,
                "name": "Others",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 6,
                "name": "Previous Announcements",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 7,
                "name": "Operational Update",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 8,
                "name": "LS Updates",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 9,
                "name": "Fees Articles",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 10,
                "name": "Teacher's Promotion Guide",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 11,
                "name": "Modified Mypage Unlocking Process",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 12,
                "name": "Training Specialization",
                "subname": {
                    "data": []
                }
            },
            {
                "id": 13,
                "name": "PHBee TESOL Common Concerns/Inquiries",
                "subname": {
                    "data": []
                }
            }
        ]
    }

so far here's what i have done

<ul class="nav flex-column">
            <li 
            v-for="list in categories"
            :key="list.id" 
            class="nav-item dropdown"
            >
              <a 
              v-if="list.subname"
              class="nav-link dropdown-toggle"
              data-toggle="dropdown"
              role="button" 
              aria-haspopup="true" 
              aria-expanded="false"
              ></a>
              <a 
              v-else
              class="nav-link"
              role="button" 
              ></a>
              <div v-for="sub in list.subname" :key="sub.id"  class="dropdown-menu">
                <a class="dropdown-item"></a>
              </div>
            </li>
          </ul>

I also want to check if there's a submenu on each menu, if there's a submenu it will create a dropdown else no dropdown for that menu

hope you guy's help me..

thank you

I'm having trouble understanding a syntax error in Python 3.7

I'm learning Python as a beginner (running Python 3.7 through Spyder), and I'm running into a syntax error that I cannot explain. I've checked it against several examples and against working code, and I still cannot understand what I have wrong in terms of syntax. The error occurs on the line that contains the code - if yn == 'Y':

import json     
import difflib   
from difflib import get_close_matches

content = json.load(open('data.json', 'r'))

def getDefinition(word):  

    word = word.lower()  
    if word in content:
        return content[word]
    elif len(get_close_matches(word, content.keys(), cutoff=0.8)) > 0:
        yn = input('Did you mean %s? Enter Y if yes, N if no.' % (get_close_matches(word, content.keys(), cutoff=0.8)[0])

Syntax error occurs on next line

        if yn == 'Y':
            return get_close_matches(word, content.keys(), cutoff=0.8)[0]
        elif yn == 'N':
            return 'Word does not exist.'
        else:
            return 'Did not understand entry.'
    else:
        return 'Word does not exist.'

word = input('Enter word: ')

output = getDefinition(word)

if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)

mardi 26 novembre 2019

PowerShell remove offline machines from a list

I have a script which I want to do a test-connection on a list of machines and then remove the offline machines from the list. This is what I have:

[System.Collections.ArrayList]$Systems = Get-Content -Path C:\temp\test.txt

Foreach ($System in $Systems){

if ($false -eq (Test-Connection -CN $System -Count 1 -Quiet))

 {

 $Systems.Remove("$System")

 } 

 }

 $Systems ```

This fails with this error:

Collection was modified; enumeration operation may not execute. At C:\temp\test.ps1:3 char:10 + Foreach ($System in $Systems){ + ~~~~~~~ + CategoryInfo : OperationStopped: (:) [], InvalidOperationException + FullyQualifiedErrorId : System.InvalidOperationException

Any advice please?

JS inserting objects correctly

I am trying to make miny pocket pokemon game. Here is how I am storing the pokemon.

let Charmander = {
        "name": "Charmander",
        "type": "fire",
        "hp": "70",
        "weaknesses": ["ground", "rock", "water"],
    };
let Bulbasaur = {
        "name": "Bulbasaur",
        "type": ["Grass", "Poison"],
        "hp": "70",
        "weaknesses": ["Fire", "Flying", "Ice", "Psychic"],
    };
let Squirtle = {
        "name": "Squirtle",
        "type": "Water",
        "hp": "60",
        "weaknesses": ["Electric", "Grass"],
};

It then asks you to pick which starting pokemon you want.

let startingChoice = prompt("What is your starting Pokemon " + Charmander.name + ", " + Bulbasaur.name + ", " + Squirtle.name);

I then create an array for the first pokemon that can be picked

let firstPokemon = [ Charmander.name, Bulbasaur.name, Squirtle.name];

I thennnn check the result of what you have typed in to see if it is in there by doing this.

if(startingChoice == "Charmander"){

    pokeBox.push(Charmander);

} else if(startingChoice == "Bulbasaur"){
    pokeBox.push(Bulbasaur);
}else{
    pokeBox.push(Squirtle);
}



}else{
    console.log("Chupa");
}

As you can see above that is pretty inefficient. How can I make it so that when it gets put into your pokeBox it adds in all of the objects info without the need of all of the info statements.

This is the result of pokeBox Object { name: "Charmander", type: "fire", hp: "70", … } How can I make this more efficient?

ATS Proof: Why does this static if need greater than or equal to?

I was writing a proof of a*0=0 and I stumbled on some strangeness. Why does the sif a >= 0 on line 7 need to be a >=, and does not compile when its just sif > 0?

prfn mul_ax0_0 {a:int} () : MUL(a,0,0) =
let
    prfun auxnat {a:nat} .<a>. () : MUL(a,0,0) =
        sif a == 0 then MULbas()
        else MULind(auxnat{a-1}())
in
    sif a >= 0 then auxnat{a}() // line 7
    else MULneg(auxnat{~a}())
end

implement main0 () = ()

Intuitively, the a=0 should be handled fine by either path, yet only the first path works. Why?

Issue while writing complex if-else condition along in Python

I am having and API from which I retrieve data store into a dataframe using requests.get. The API gives two types response status code =200 and !=200. If the respnse.staus_code=200then I need populate the dataframe with values from response.text shown below else respnose.staus_code!=200then populate with "". I am not completly write the if -elif condition properly and attaching my imcomplete code below. Could you help

response.text

'{"results":[{"place":{"type":"coord","value":"44.164:28.641","lat":44.164,"lon":28.641,"tz":"Europe/Bucharest"},"measures":[{"ts":1575331200000,"date":"2019-12-03","temperature_2m":11.78,"temperature_2m_min":11.75,"temperature_2m_max":12.46,"windspeed":3.25,"direction":"SSW","wind_gust":5.43,"relative_humidity_2m":88,"sea_level_pressure":1014,"sky_cover":"cloudy","precipitation":0.0,"snow_depth":0,"thunderstorm":"N","fog":"M"}]},{"place":{"type":"coord","value":"53.546:9.98","lat":53.546,"lon":9.98,"tz":"Europe/Berlin"},"measures":[{"ts":1575331200000,"date":"2019-12-03","temperature_2m":-0.55,"temperature_2m_min":-0.8,"temperature_2m_max":-0.35,"windspeed":3.65,"direction":"WSW","wind_gust":8.62,"relative_humidity_2m":88,"sea_level_pressure":1025,"sky_cover":"mostly_clear","precipitation":0.0,"snow_depth":0,"thunderstorm":"N","fog":"M"}]}]}

The code to store into the dataframe

d = json.loads(response.text)

out = []
for x in d['results']:
    t = x['place']['type']
    v = x['place']['value']
    for y in x['measures']:
        y[t] = v
        out.append(y)

df = pd.DataFrame(out)

My code with if -elif condition( I need help in completing this one)

   df_results = pd.DataFrame( list(zip(Unique_Coords)), columns =['Unique_Coords'])
    today_date =date.today().strftime("%Y-%m-%d")
    shifted_date = date.today() + timedelta(days=7)
    shifted_date =shifted_date.strftime("%Y-%m-%d")
    results ={}
    df_results["date"] = ""
    df_results["direction"] = ""
    df_results["fog"] = ""
    df_results["precipitation"] = ""
    df_results["relative_humidity_2m"] = ""
    df_results["sea_level_pressure"] = ""
    df_results["snow_depth"] = ""
    df_results["temperature_2m"] = ""
    df_results["temperature_2m_max] = ""
    df_results["temperature_2m_min"] = ""
    df_results["thunderstorm"] = ""
    df_results["ts"] = ""
    df_results["wind_gust"] = ""
    df_results["windspeed"] = ""

    headers = { 'Authorization': 'Api-Key',}

    for i, row in df_results.iterrows():
        d_ = (('coords', str(row["Unique_Coords"])), ('fromDate', today_date), ('toDate', shifted_date))
        response = requests.get('https://example.com/weather/v2/forecasts', headers=headers, params=d_)
        if (response.status_code)!=200:
           df_results["date"].iloc[i] = ""
           df_results["direction"].iloc[i] = ""
           df_results["fog"].iloc[i] = ""
           df_results["precipitation"].iloc[i] = ""
           df_results["relative_humidity_2m"].iloc[i] = ""
           df_results["sea_level_pressure"].iloc[i] = ""
           df_results["snow_depth"].iloc[i] = ""
           df_results["temperature_2m'"].iloc[i] = ""
           df_results["temperature_2m_max"].iloc[i] = ""
           df_results["temperature_2m_min"].iloc[i] = ""
           df_results["thunderstorm"].iloc[i] = ""
           df_results["ts"].iloc[i] = ""
           df_results["wind_gust"].iloc[i] = ""
           df_results["windspeed"].iloc[i] = ""
        elif (response.status_code)==200:

How to write the condition for status_code 200?