问:
xcode: no such module 'Kingfisher'
I want run my app on emulator

But I get this error:

```<code>no such module 'Kingfisher'
</code>```

pod update, pod install, delete DerivedData folder, restart xcode, use xcworkspace, use xcodeproj and ... not solved my problem!

OS: 11.4
xcode: 12.4

My pod:

```<code>platform :ios, '11.0'

use_frameworks!

target 'Name' do
  pod 'QuickBlox'
  pod 'Quickblox-WebRTC'
  pod 'Alamofire'
  pod 'Kingfisher'
  pod 'NVActivityIndicatorView/Extended'
  pod 'PulsingHalo'
  pod 'ImageScrollView'
  pod 'Firebase/Core'
  pod 'Firebase/Messaging'
end
</code>```

答:
Adding this to podfile helps me</p>
```<code>post_install do |installer|
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
  end
end
</code>```

Title: xcode: no such module 'Kingfisher'

Body:
I want run my app on emulator

But I get this error:

no such module 'Kingfisher'

pod update, pod install, delete DerivedData folder, restart xcode, use xcworkspace, use xcodeproj and ... not solved my problem!

OS: 11.4
xcode: 12.4

My pod:

platform :ios, '11.0'

use_frameworks!

target 'Name' do
  pod 'QuickBlox'
  pod 'Quickblox-WebRTC'
  pod 'Alamofire'
  pod 'Kingfisher'
  pod 'NVActivityIndicatorView/Extended'
  pod 'PulsingHalo'
  pod 'ImageScrollView'
  pod 'Firebase/Core'
  pod 'Firebase/Messaging'
end

Body:
Adding this to podfile helps me

post_install do |installer|
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
  end
end


来源: stackexchange

问:
Background-colour of a column in excel is not changing
I am trying to change the colour of my column 'Speed' in excel wherever the value is 100 but it is not working just reading from the excel file and generating another excel file. Below is my code.

Excel-File has 6X Column 6X Rows (starting from 0) where row no 1 and 2 are blank and the
column names are ( Interface , Description, Encapsulation, IP ,Mask, Speed, Duplex)

```<code>import pandas as pd
import styleframe
import openpyxl
import numpy as np
import os

SPath=r'C:\Users\Excel-File'

File_List=os.listdir(SPath)
for X in File_List:

  SF=X
  df=pd.read_excel(os.path.join(SPath, SF))

  df.style.applymap([lambda x :'background-colour:green' if x is '100' else 'background-colour:red'],subset='Speed')
  df.style.to_excel('styled.xlsx',engine='openpyxl',index=False)
</code>```

enter image description here

答:
Use:</p>
```<code>#test data
df = pd.DataFrame({'Speed':[100,200,100], 'col':list('abc')})

 #assign output to styled variable
 #remove u from text colour
styled = df.style.applymap(lambda x :'background-color:green' if x == 100 else 'background-color:red',subset=['Speed'])

#write to file styled
styled.to_excel('styled.xlsx',engine='openpyxl',index=False)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to change the colour of my column 'Speed' in excel wherever the value is 100 but it is not working just reading from the excel file and generating another excel file. Below is my code.

Excel-File has 6X Column 6X Rows (starting from 0) where row no 1 and 2 are blank and the
column names are ( Interface , Description, Encapsulation, IP ,Mask, Speed, Duplex)

import pandas as pd
import styleframe
import openpyxl
import numpy as np
import os

SPath=r'C:\Users\Excel-File'

File_List=os.listdir(SPath)
for X in File_List:

  SF=X
  df=pd.read_excel(os.path.join(SPath, SF))

  df.style.applymap([lambda x :'background-colour:green' if x is '100' else 'background-colour:red'],subset='Speed')
  df.style.to_excel('styled.xlsx',engine='openpyxl',index=False)

enter image description here

Body:
Use:

#test data
df = pd.DataFrame({'Speed':[100,200,100], 'col':list('abc')})

 #assign output to styled variable
 #remove u from text colour
styled = df.style.applymap(lambda x :'background-color:green' if x == 100 else 'background-color:red',subset=['Speed'])

#write to file styled
styled.to_excel('styled.xlsx',engine='openpyxl',index=False)


问:
Sort a map within a map and convert to list within a list
Here's my data in Firebase:

```<code>prices
  price1
    priceAmount1: 10
    priceAmount2: 20
    priceAmount3: 30
  price2
    priceAmount1: 15
    priceAmount2: 5
    priceAmount3: 7
  price3
    priceAmount1: 2
    priceAmount2: 4
    priceAmount3: 6
</code>```

If I straight away retrieve it. Sometimes the ordering is price2, price3, price1. So I tried sorting it like this:

```<code>      var sortedKeys = prices!.price!.keys.toList()..sort();
      for (var it = 0; it < sortedKeys.length; it++) {
        print('${sortedKeys[it]}');
      }
</code>```

But since it becomes a list, I'm not able to access the map anymore. I wanted to sort the map within a map then store it in a list within a list. Please help. Thanks!

Edit:

```<code>final splayByPrice =
    SplayTreeMap<dynamic, dynamic>((a, b) => a.compareTo(b));

List<Map<dynamic, dynamic>> priceAmountMap = [
        {
          'priceAmount1': 10,
          'priceAmount2': 20,
          'priceAmount3': 30,
        },
        {
          'priceAmount1': 15,
          'priceAmount2': 5,
          'priceAmount3': 7,
        },
        {
          'priceAmount1': 2,
          'priceAmount2': 4,
          'priceAmount3': 6,
        }
      ];

      Map<dynamic, Map<dynamic, dynamic>> priceMap = {
        'price2': priceAmountMap[1],
        'price1': priceAmountMap[0],
        'price3': priceAmountMap[2],
      };

      priceMap.forEach((key, value) {
        splayByPrice.addAll(value);
      });

      priceMap.forEach((key, value) {
        print('$key \t $value');
      });
</code>```

What it prints, is still not sorted.

```<code>price2   {priceAmount1: 15, priceAmount2: 5, priceAmount3: 7}
price1   {priceAmount1: 10, priceAmount2: 20, priceAmount3: 30}
price3   {priceAmount1: 2, priceAmount2: 4, priceAmount3: 6}
</code>```

答:
Dart's default Map implementation is a LinkedHashMap that stores entries in order of insertion.

(You haven't provided code that clearly shows your data structure, so I'll use my own example.)

If you want the Map to be sorted by the keys' alphabetic order, then you could:

Create a new Map, adding items to it in the desired order:

var theMap = {
  4: 'four',
  7: 'seven',
  6: 'six',
  9: 'nine',
  5: 'five',
  1: 'one',
  8: 'eight',
  0: 'zero',
  3: 'three',
  2: 'two',
};

void main() {
  var sortedKeys = theMap.keys.toList()..sort();
  var sortedMap = {
    for (var key in sortedKeys)
      key: theMap[key]!,
  };
  print(sortedMap);
}
```
</li>
<li><p>Update the existing <code>Map</code>, removing and re-adding items in the desired order:</p>
<pre class="lang-dart prettyprint-override"><code>void main() {
  var sortedKeys = theMap.keys.toList()..sort();
  for (var key in sortedKeys) {
    var value = theMap[key]!;
    theMap.remove(key);
    theMap[key] = value;
  }
  print(theMap);
}
</code>```

Use a SplayTreeMap, which keeps entries sorted by a comparison rule.

import 'dart:collection';

void main() {
  var splayTreeMap = SplayTreeMap.of(theMap);
  print(splayTreeMap);
}
```

If you need to sort the data only once, I'd use one of the first two methods.  If you're frequently adding new entries, then I'd use a SplayTreeMap instead of a Map/LinkedHashMap so that entries are kept in a sorted order. (But note that lookups, insertions, and removals in a SplayTreeMap are O(log n) instead of O(1).)

Also, if you're sorting strings that contain numbers, you probably don't want to use the normal string sort.

Body:
Here's my data in Firebase:

prices
  price1
    priceAmount1: 10
    priceAmount2: 20
    priceAmount3: 30
  price2
    priceAmount1: 15
    priceAmount2: 5
    priceAmount3: 7
  price3
    priceAmount1: 2
    priceAmount2: 4
    priceAmount3: 6

If I straight away retrieve it. Sometimes the ordering is price2, price3, price1. So I tried sorting it like this:

      var sortedKeys = prices!.price!.keys.toList()..sort();
      for (var it = 0; it < sortedKeys.length; it++) {
        print('${sortedKeys[it]}');
      }

But since it becomes a list, I'm not able to access the map anymore. I wanted to sort the map within a map then store it in a list within a list. Please help. Thanks!

Edit:

final splayByPrice =
    SplayTreeMap<dynamic, dynamic>((a, b) => a.compareTo(b));

List<Map<dynamic, dynamic>> priceAmountMap = [
        {
          'priceAmount1': 10,
          'priceAmount2': 20,
          'priceAmount3': 30,
        },
        {
          'priceAmount1': 15,
          'priceAmount2': 5,
          'priceAmount3': 7,
        },
        {
          'priceAmount1': 2,
          'priceAmount2': 4,
          'priceAmount3': 6,
        }
      ];

      Map<dynamic, Map<dynamic, dynamic>> priceMap = {
        'price2': priceAmountMap[1],
        'price1': priceAmountMap[0],
        'price3': priceAmountMap[2],
      };

      priceMap.forEach((key, value) {
        splayByPrice.addAll(value);
      });

      priceMap.forEach((key, value) {
        print('$key \t $value');
      });

What it prints, is still not sorted.

price2   {priceAmount1: 15, priceAmount2: 5, priceAmount3: 7}
price1   {priceAmount1: 10, priceAmount2: 20, priceAmount3: 30}
price3   {priceAmount1: 2, priceAmount2: 4, priceAmount3: 6}

Body:
Dart's default Map implementation is a LinkedHashMap that stores entries in order of insertion.

(You haven't provided code that clearly shows your data structure, so I'll use my own example.)

If you want the Map to be sorted by the keys' alphabetic order, then you could:

Create a new Map, adding items to it in the desired order:

var theMap = {
  4: 'four',
  7: 'seven',
  6: 'six',
  9: 'nine',
  5: 'five',
  1: 'one',
  8: 'eight',
  0: 'zero',
  3: 'three',
  2: 'two',
};

void main() {
  var sortedKeys = theMap.keys.toList()..sort();
  var sortedMap = {
    for (var key in sortedKeys)
      key: theMap[key]!,
  };
  print(sortedMap);
}

Update the existing Map, removing and re-adding items in the desired order:

void main() {
  var sortedKeys = theMap.keys.toList()..sort();
  for (var key in sortedKeys) {
    var value = theMap[key]!;
    theMap.remove(key);
    theMap[key] = value;
  }
  print(theMap);
}

Use a SplayTreeMap, which keeps entries sorted by a comparison rule.

import 'dart:collection';

void main() {
  var splayTreeMap = SplayTreeMap.of(theMap);
  print(splayTreeMap);
}

If you need to sort the data only once, I'd use one of the first two methods.  If you're frequently adding new entries, then I'd use a SplayTreeMap instead of a Map/LinkedHashMap so that entries are kept in a sorted order. (But note that lookups, insertions, and removals in a SplayTreeMap are O(log n) instead of O(1).)

Also, if you're sorting strings that contain numbers, you probably don't want to use the normal string sort.


问:
Code syntax explaination help
I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:

```<code>public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class // Need help to interpret this method declaration
</code>```

I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!

Code:

```<code>public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class // Need help to interpret this method
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}
</code>```

答:
The static keyword in front means that you do not have to instantiate VisualTreeHelperExtensions in order to call the FindAncestor method.  You can say:

```<code>VisualTreeHelperExtensions.FindAncestor<MyClass>(myObj);
</code>```

Where myObj is a DependencyObject.  The where, as you said, makes sure that T (MyClass in this case) is indeed a class

For convenience, Methods like this can be declared like this:

```<code>public static T FindAncestor<T>(this DependencyObject dependencyObject)
  where T : class // Need help to interpret this method declaration
</code>```

Which would allow you to call the method like so:

```<code>myObj.FindAncestor<MyClass>();
</code>```

Effectively adding a method to your DependencyObject after the fact.

ContentLicense: CC BY-SA 3.0

Title: Code syntax explaination help

Body:
I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:

public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class // Need help to interpret this method declaration

I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!

Code:

public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class // Need help to interpret this method
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}

Body:
The static keyword in front means that you do not have to instantiate VisualTreeHelperExtensions in order to call the FindAncestor method.  You can say:

VisualTreeHelperExtensions.FindAncestor<MyClass>(myObj);

Where myObj is a DependencyObject.  The where, as you said, makes sure that T (MyClass in this case) is indeed a class

For convenience, Methods like this can be declared like this:

public static T FindAncestor<T>(this DependencyObject dependencyObject)
  where T : class // Need help to interpret this method declaration

Which would allow you to call the method like so:

myObj.FindAncestor<MyClass>();

Effectively adding a method to your DependencyObject after the fact.


问:
Linux: compute a single hash for a given folder & contents?
Surely there must be a way to do this easily!

I've tried the Linux command-line apps such as sha1sum and md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file.

I need to generate a single hash for the entire contents of a folder (not just the filenames).

I'd like to do something like

```<code>sha1sum /folder/of/stuff > singlehashvalue
</code>```

Edit: to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.

答:
You can try hashdir which is an open source command line tool written for this purpose.

hashdir /folder/of/stuff

It has several useful flags to allow you to specify the hashing algorithm, print the hashes of all children, as well as save and verify a hash.

```<code>hashdir:
  A command-line utility to checksum directories and files.

Usage:
  hashdir [options] [<item>...] [command]

Arguments:
  <item>    Directory or file to hash/check

Options:
  -t, --tree                                         Print directory tree
  -s, --save                                         Save the checksum to a file
  -i, --include-hidden-files                         Include hidden files
  -e, --skip-empty-dir                               Skip empty directories
  -a, --algorithm <md5|sha1|sha256|sha384|sha512>    The hash function to use [default: sha1]
  --version                                          Show version information
  -?, -h, --help                                     Show help and usage information

Commands:
  check <item>    Verify that the specified hash file is valid.
</code>```

OwnerDisplayName: Ben L

Body:
Surely there must be a way to do this easily!

I've tried the Linux command-line apps such as sha1sum and md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file.

I need to generate a single hash for the entire contents of a folder (not just the filenames).

I'd like to do something like

sha1sum /folder/of/stuff > singlehashvalue

Edit: to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.

LastEditorDisplayName: Ben L

Body:
You can try hashdir which is an open source command line tool written for this purpose.

hashdir /folder/of/stuff

It has several useful flags to allow you to specify the hashing algorithm, print the hashes of all children, as well as save and verify a hash.

hashdir:
  A command-line utility to checksum directories and files.

Usage:
  hashdir [options] [<item>...] [command]

Arguments:
  <item>    Directory or file to hash/check

Options:
  -t, --tree                                         Print directory tree
  -s, --save                                         Save the checksum to a file
  -i, --include-hidden-files                         Include hidden files
  -e, --skip-empty-dir                               Skip empty directories
  -a, --algorithm <md5|sha1|sha256|sha384|sha512>    The hash function to use [default: sha1]
  --version                                          Show version information
  -?, -h, --help                                     Show help and usage information

Commands:
  check <item>    Verify that the specified hash file is valid.


问:
BeautifulSoup (Python): how grab text-string next to a tag (that may or may not exist)?
I think my title explains it pretty well the problem I am facing. Let's look at a picture of the problem. (You can find the web-page at this adress, however it has probably changed).

I have highlighted the text that I want to grab in blue, this is the model-year 2008. Now, it is not necessary for the seller to submit the model-year, so this may or may not exist. But when it does exist it always follows the  tag with class ="fa fa-calender". My solution so far has been to grab all the text whitin
 ...
" (this then becomes a list) and then choose the second element, conditioned on that  ...  exists. Otherwise I do not grab anything.

Now, it seems as this does not work in general since that text that comes before the second element can be aranged into more than one element if has a whitespace in it. So, is there any way (any function) that can grab a text string that neighbours another tag as seen in my picture?

PS: if I have made myself unclear, I just want to fetch the year 2008 from the post on the web page if it exists.

Edit

In this situation my code erroneously gives my the word "Hjulvältar" (bulldozer in english) instead of the year 2008.

CODE

```<code>from bs4 import BeautifulSoup
from datetime import date
import requests

url_avvikande = ['bomliftar','teleskop-bomliftar','kompakta-sjalvgaende-bomlyftar','bandschaktare','reachstackers','staplare']
today = date.today().isoformat()

url_main = 'https://www.mascus.se'
produktgrupper = ['lantbruksmaskiner','transportfordon','skogsmaskiner','entreprenadmaskiner','materialhantering','gronytemaskiner']
kategorier = {
  'lantbruksmaskiner': ['traktorer','sjalvgaende-falthackar','skordetroskor','atv','utv:er','snoskotrar'],
  'transportfordon': ['fordonstruckar','elektriska-fordon','terrangfordon'],
  'skogsmaskiner': ['skog-skordare','skog-gravmaskiner','skotare','drivare','fallare-laggare','skogstraktorer','lunnare','terminal-lastare'],
  'entreprenadmaskiner': ['gravlastare','bandgravare','minigravare-7t','hjulgravare','midigravmaskiner-7t-12t','atervinningshanterare','amfibiska-gravmaskiner','gravmaskiner-med-frontskopa','gravmaskiner-med-lang-rackvidd','gravmaskiner-med-slapskopa','rivningsgravare','specialgravmaskiner','hjullastare','kompaktlastare','minilastmaskiner','bandlastare','teleskopiska-hjullastare','redaskapshallare','gruvlastare','truckar-och-lastare-for-gruvor','bergborriggar','teleskoplastare','dumprar','minidumprar','gruvtruckar','banddumprar','specialiserade-dragare','vaghyvlar','vattentankbilar','allterrangkranar','terrangkranar-grov-terrang','-bandgaende-kranar','saxliftar','bomliftar','teleskop-bomliftar','personhissar-och-andra-hissar','kompakta-sjalvgaende-bomlyftar','krossar','mobila-krossar','sorteringsverk','mobila-sorteringsverk','bandschaktare','asfaltslaggningsmaskiner','--asfaltskallfrasmaskiner','tvavalsvaltar','envalsvaltar','jordkompaktorer','pneumatiska-hjulvaltar','andra-valtar','kombirullar','borrutrustning-ytborrning','horisontella-borrutrustning','trenchers-skar-gravmaskin'],
  'materialhantering': ['dieseltruckar','eldrivna-gaffeltruckar','lpg-truckar','gaffeltruckar---ovriga','skjutstativtruck','sidlastare','teleskopbomtruckar','terminaltraktorer','reachstackers','ovriga-materialhantering-maskiner','staplare-led','staplare','plocktruck-laglyftande','plocktruck-hoglyftande','plocktruck-mediumlyftande','dragtruck','terrangtruck','4-vagstruck','smalgangstruck','skurborsttorkar','inomhus-sopmaskiner','kombinationsskurborstar'],
  'gronytemaskiner': ['kompakttraktorer','akgrasklippare','robotgrasklippare','nollsvangare','plattformsklippare','sopmaskiner','verktygsfraktare','redskapsbarare','golfbilar','fairway-grasklippare','green-grasklippare','grasmattevaltar','ovriga-gronytemaskiner']
  }

url = 'https://www.mascus.se'
mappar = ['Lantbruk', 'Transportfordon', 'Skogsmaskiner', 'Entreprenad',  'Materialhantering', 'Grönytemaskiner']
index = -1
status = True
for produktgrupp in kategorier:
  index += 1
  mapp = mappar[index]
  save_path = f'/home/protector.local/vika99/webscrape_mascus/Annonser/{mapp}'
  underkategorier = kategorier[produktgrupp]
  for underkategori in underkategorier:
        # OBS
        if underkategori != 'borrutrustning-ytborrning' and status:
              continue
        else:
              status = False
        # OBS
        if underkategori in url_avvikande:
              url = f'{url_main}/{produktgrupp}/{underkategori}'
        elif underkategori == 'gravmaskiner-med-frontskopa':
              url = f'{url_main}/{produktgrupp}/begagnat-{underkategori}'
        elif underkategori == 'borrutrustning-ytborrning':
              url = f'{url_main}/{produktgrupp}/begagnad-{underkategori}'
        else:
              url = f'{url_main}/{produktgrupp}/begagnade-{underkategori}'
        file_name = f'{save_path}/{produktgrupp}_{underkategori}_{today}.txt'
        sida = 1
        print(url)
        with open(file_name, 'w') as f:
              while True:
                    print(sida)
                    html_text = None
                    soup = None
                    links = None
                    while links == None:
                          html_text = requests.get(url).text
                          soup = BeautifulSoup(html_text, 'lxml')
                          links = soup.find('ul', class_ = 'page-numbers')
                    annonser = soup.find_all('li', class_ = 'col-row single-result')
                    for annons in annonser:
                          modell = annons.find('a', class_ = 'title-font').text
                          if annons.p.find('i', class_ = 'fa fa-calendar') != None:
                                tillverkningsar = annons.find('p', class_ = 'result-details').text.strip().split(" ")[1]
                          else:
                                tillverkningsar = 'Ej angiven'
                          try:
                                pris = annons.find('span', class_ = 'title-font no-ws-wrap').text
                          except AttributeError:
                                pris = annons.find('span', class_ = 'title-font no-price').text
                          f.write(f'{produktgrupp:<21}{underkategori:25}{modell:<70}{tillverkningsar:<13}{pris:>14}\n')
                    url_part = None
                    sida += 1
                    try:
                          url_part = links.find('a', text = f'{sida}')['href']
                    except TypeError:
                          print(f'Avläsning av underkategori klar.')
                          break
                    url = f'{url_main}{url_part}'
</code>```

答:
As you loop the listings you can test if that calendar icon class is present, if it is then grab the next_sibling

```<code>import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.mascus.se/entreprenadmaskiner/begagnade-pneumatiska-hjulvaltar')
soup = bs(r.content, 'lxml')
listings = soup.select('.single-result')

for listing in listings:

    calendar = listing.select_one('.fa-calendar')

    if calendar is not None:
        print(calendar.next_sibling)
    else:
        print('Not present')
</code>```

Body:
I think my title explains it pretty well the problem I am facing. Let's look at a picture of the problem. (You can find the web-page at this adress, however it has probably changed).

I have highlighted the text that I want to grab in blue, this is the model-year 2008. Now, it is not necessary for the seller to submit the model-year, so this may or may not exist. But when it does exist it always follows the  tag with class ="fa fa-calender". My solution so far has been to grab all the text whitin
 ...
" (this then becomes a list) and then choose the second element, conditioned on that  ...  exists. Otherwise I do not grab anything.

Now, it seems as this does not work in general since that text that comes before the second element can be aranged into more than one element if has a whitespace in it. So, is there any way (any function) that can grab a text string that neighbours another tag as seen in my picture?

PS: if I have made myself unclear, I just want to fetch the year 2008 from the post on the web page if it exists.

Edit

In this situation my code erroneously gives my the word "Hjulvältar" (bulldozer in english) instead of the year 2008.

CODE

from bs4 import BeautifulSoup
from datetime import date
import requests

url_avvikande = ['bomliftar','teleskop-bomliftar','kompakta-sjalvgaende-bomlyftar','bandschaktare','reachstackers','staplare']
today = date.today().isoformat()

url_main = 'https://www.mascus.se'
produktgrupper = ['lantbruksmaskiner','transportfordon','skogsmaskiner','entreprenadmaskiner','materialhantering','gronytemaskiner']
kategorier = {
  'lantbruksmaskiner': ['traktorer','sjalvgaende-falthackar','skordetroskor','atv','utv:er','snoskotrar'],
  'transportfordon': ['fordonstruckar','elektriska-fordon','terrangfordon'],
  'skogsmaskiner': ['skog-skordare','skog-gravmaskiner','skotare','drivare','fallare-laggare','skogstraktorer','lunnare','terminal-lastare'],
  'entreprenadmaskiner': ['gravlastare','bandgravare','minigravare-7t','hjulgravare','midigravmaskiner-7t-12t','atervinningshanterare','amfibiska-gravmaskiner','gravmaskiner-med-frontskopa','gravmaskiner-med-lang-rackvidd','gravmaskiner-med-slapskopa','rivningsgravare','specialgravmaskiner','hjullastare','kompaktlastare','minilastmaskiner','bandlastare','teleskopiska-hjullastare','redaskapshallare','gruvlastare','truckar-och-lastare-for-gruvor','bergborriggar','teleskoplastare','dumprar','minidumprar','gruvtruckar','banddumprar','specialiserade-dragare','vaghyvlar','vattentankbilar','allterrangkranar','terrangkranar-grov-terrang','-bandgaende-kranar','saxliftar','bomliftar','teleskop-bomliftar','personhissar-och-andra-hissar','kompakta-sjalvgaende-bomlyftar','krossar','mobila-krossar','sorteringsverk','mobila-sorteringsverk','bandschaktare','asfaltslaggningsmaskiner','--asfaltskallfrasmaskiner','tvavalsvaltar','envalsvaltar','jordkompaktorer','pneumatiska-hjulvaltar','andra-valtar','kombirullar','borrutrustning-ytborrning','horisontella-borrutrustning','trenchers-skar-gravmaskin'],
  'materialhantering': ['dieseltruckar','eldrivna-gaffeltruckar','lpg-truckar','gaffeltruckar---ovriga','skjutstativtruck','sidlastare','teleskopbomtruckar','terminaltraktorer','reachstackers','ovriga-materialhantering-maskiner','staplare-led','staplare','plocktruck-laglyftande','plocktruck-hoglyftande','plocktruck-mediumlyftande','dragtruck','terrangtruck','4-vagstruck','smalgangstruck','skurborsttorkar','inomhus-sopmaskiner','kombinationsskurborstar'],
  'gronytemaskiner': ['kompakttraktorer','akgrasklippare','robotgrasklippare','nollsvangare','plattformsklippare','sopmaskiner','verktygsfraktare','redskapsbarare','golfbilar','fairway-grasklippare','green-grasklippare','grasmattevaltar','ovriga-gronytemaskiner']
  }

url = 'https://www.mascus.se'
mappar = ['Lantbruk', 'Transportfordon', 'Skogsmaskiner', 'Entreprenad',  'Materialhantering', 'Grönytemaskiner']
index = -1
status = True
for produktgrupp in kategorier:
  index += 1
  mapp = mappar[index]
  save_path = f'/home/protector.local/vika99/webscrape_mascus/Annonser/{mapp}'
  underkategorier = kategorier[produktgrupp]
  for underkategori in underkategorier:
        # OBS
        if underkategori != 'borrutrustning-ytborrning' and status:
              continue
        else:
              status = False
        # OBS
        if underkategori in url_avvikande:
              url = f'{url_main}/{produktgrupp}/{underkategori}'
        elif underkategori == 'gravmaskiner-med-frontskopa':
              url = f'{url_main}/{produktgrupp}/begagnat-{underkategori}'
        elif underkategori == 'borrutrustning-ytborrning':
              url = f'{url_main}/{produktgrupp}/begagnad-{underkategori}'
        else:
              url = f'{url_main}/{produktgrupp}/begagnade-{underkategori}'
        file_name = f'{save_path}/{produktgrupp}_{underkategori}_{today}.txt'
        sida = 1
        print(url)
        with open(file_name, 'w') as f:
              while True:
                    print(sida)
                    html_text = None
                    soup = None
                    links = None
                    while links == None:
                          html_text = requests.get(url).text
                          soup = BeautifulSoup(html_text, 'lxml')
                          links = soup.find('ul', class_ = 'page-numbers')
                    annonser = soup.find_all('li', class_ = 'col-row single-result')
                    for annons in annonser:
                          modell = annons.find('a', class_ = 'title-font').text
                          if annons.p.find('i', class_ = 'fa fa-calendar') != None:
                                tillverkningsar = annons.find('p', class_ = 'result-details').text.strip().split(" ")[1]
                          else:
                                tillverkningsar = 'Ej angiven'
                          try:
                                pris = annons.find('span', class_ = 'title-font no-ws-wrap').text
                          except AttributeError:
                                pris = annons.find('span', class_ = 'title-font no-price').text
                          f.write(f'{produktgrupp:<21}{underkategori:25}{modell:<70}{tillverkningsar:<13}{pris:>14}\n')
                    url_part = None
                    sida += 1
                    try:
                          url_part = links.find('a', text = f'{sida}')['href']
                    except TypeError:
                          print(f'Avläsning av underkategori klar.')
                          break
                    url = f'{url_main}{url_part}'

Body:
As you loop the listings you can test if that calendar icon class is present, if it is then grab the next_sibling

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.mascus.se/entreprenadmaskiner/begagnade-pneumatiska-hjulvaltar')
soup = bs(r.content, 'lxml')
listings = soup.select('.single-result')

for listing in listings:

    calendar = listing.select_one('.fa-calendar')

    if calendar is not None:
        print(calendar.next_sibling)
    else:
        print('Not present')


问:
Is it Safe to Say That Non-Stationary Series Can Not Be Simulated Using R
I am performing an experiment using classes of ARIMA models which I have to simulate for instance AR, MA, ARMA and possibly ARIMA using arima.sim() function in R. I am able to AR, MA, ARMA but ARIMA seems impossible as the coefficient of AR must be greater than 1 ($|\phi| > 1$) for the series to be non-stationary.

Simulate MA of 10 sample size with a coefficient of 0.8

```<code>set.seed(837530)
ma1 <- arima.sim(n = 10, model = list(ma = c(0.8), order = c(0, 0, 1)), sd = 1)
forecast::auto.arima(ma1, ic = "aicc")
</code>```

Simulate MA of 10 sample size with coefficients of 0.4 and 0.4

```<code>set.seed(181917)
ma2 <- arima.sim(n = 10, model = list(ma = c(0.4, 0.4), order = c(0, 0, 2)), sd = 1)
forecast::auto.arima(ma2, ic = "aicc")
</code>```

Simulate ARMA of 10 sample size with coefficients of 0.4 and 0.4

```<code>set.seed(455287)
arma11 <- arima.sim(n = 10, model = list(ar = c(0.4), ma = c(0.4), order = c(1, 0, 1)), sd = 1)
forecast::auto.arima(arma11, ic = "aicc")
</code>```

My attempt to simulate from ARIMA

```<code>arima111 <- arima.sim(n = 10, model = list(ar = c(1.1), ma = c(0.3), order = c(1, 1, 1)), sd = 1)
Error in arima.sim(n = 10, model = list(ar = c(1.1), ma = c(0.3), order = c(1,  :
  'ar' part of model is not stationary
</code>```

WHAT I WANT

Can it be said in a public domain that it is not possible to simulate a series from ARIMA distribution? (having $\phi$ value as the estimate of AR parameter and $\theta$ asthe estimate of `MA parameter).

If it is possible, please demonstrate it for me using arima.sim() function or through any other way using R.

答:
It is possible to simulate a nonstationary process using arima.sim. From ?arima:

For ARIMA models with differencing, the differenced series follows a zero-mean ARMA model.

Hence, in the call arima.sim(model = list(order, ar, ma), n) with order = c(p, d, q), ar and ma specify parameters of an ARMA(p, q) model for a d-order differenced time series, not an undifferenced time series.

Stationarity of the the differenced time series is enforced with the following constraint on ar, which you can find in the body of arima.sim:

    p <- length(model$ar)
    if (p) {
        minroots <- min(Mod(polyroot(c(1, -model$ar))))
        if (minroots <= 1)
            stop("'ar' part of model is not stationary")
    }
```
<p>In other words, the roots of the polynomial whose coefficients are <code>c(1, -ar)</code> are required to lie outside of the unit circle. (The very same constraint is stated here.)</p>
<p>Stationarity of the differenced time series <em>does not</em> imply stationarity of the undifferenced time series. In fact, the undifferenced time series is never stationary. <code>?arima.sim</code> gives an example:</p>
<pre class="lang-r prettyprint-override"><code>ts.sim <- arima.sim(list(order = c(1, 1, 0), ar = 0.7), n = 200)
ts.plot(ts.sim)
</code>```

But it is better to compare collections of simulations:

set.seed(1L)
X <- replicate(50L, arima.sim(list(order = c(1, 0, 0), ar = 0.7), n = 200))
Y <- replicate(50L, arima.sim(list(order = c(1, 1, 0), ar = 0.7), n = 200))

par(mfrow = c(1L, 2L))
matplot(X, type = "l", main = "AR(1) = ARIMA(1, 0, 0)")
matplot(Y, type = "l", main = "ARIMA(1, 1, 0)")
```
<p><img src="https://i.stack.imgur.com/Vc7fj.png" alt="enter image description here" /></p>
<p>If you insist on <em>p</em>-values, then you can perform Dickey-Fuller tests:</p>
<pre class="lang-r prettyprint-override"><code>apply(X, 2L, function(x) tseries::adf.test(x, k = 0)$p.value)
##  [1] 0.9263981 0.9900000 0.9900000 0.2561765 0.9218488
##  [6] 0.9900000 0.1816286 0.9900000 0.9900000 0.9372659
## [11] 0.6991314 0.9018098 0.8618604 0.9390623 0.6203794
## [16] 0.9740316 0.9002020 0.8196272 0.6657746 0.9593784
## [21] 0.9900000 0.9900000 0.8572043 0.1337945 0.9817778
## [26] 0.9900000 0.9900000 0.9816193 0.9562682 0.9900000
## [31] 0.4298187 0.9550181 0.7608263 0.9900000 0.9455187
## [36] 0.7616230 0.9412379 0.9588200 0.9354637 0.9900000
## [41] 0.9900000 0.9628406 0.9818668 0.9203677 0.9804385
## [46] 0.9900000 0.9900000 0.9807893 0.9048136 0.9822757

apply(X, 2L, function(x) tseries::adf.test(diff(x), k = 0)$p.value)
##  [1] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [11] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [21] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [31] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [41] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01

apply(Y, 2L, function(x) tseries::adf.test(x, k = 0)$p.value)
##  [1] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [11] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [21] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [31] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [41] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
</code>```

(These p-values are computed by linear interpolation on a very coarse grid. You should take 0.01 to mean some number between 0 and 0.01, and 0.99 to mean some number between 0.99 and 1.)

Body:
I am performing an experiment using classes of ARIMA models which I have to simulate for instance AR, MA, ARMA and possibly ARIMA using arima.sim() function in R. I am able to AR, MA, ARMA but ARIMA seems impossible as the coefficient of AR must be greater than 1 ($|\phi| > 1$) for the series to be non-stationary.

Simulate MA of 10 sample size with a coefficient of 0.8

set.seed(837530)
ma1 <- arima.sim(n = 10, model = list(ma = c(0.8), order = c(0, 0, 1)), sd = 1)
forecast::auto.arima(ma1, ic = "aicc")

Simulate MA of 10 sample size with coefficients of 0.4 and 0.4

set.seed(181917)
ma2 <- arima.sim(n = 10, model = list(ma = c(0.4, 0.4), order = c(0, 0, 2)), sd = 1)
forecast::auto.arima(ma2, ic = "aicc")

Simulate ARMA of 10 sample size with coefficients of 0.4 and 0.4

set.seed(455287)
arma11 <- arima.sim(n = 10, model = list(ar = c(0.4), ma = c(0.4), order = c(1, 0, 1)), sd = 1)
forecast::auto.arima(arma11, ic = "aicc")

My attempt to simulate from ARIMA

arima111 <- arima.sim(n = 10, model = list(ar = c(1.1), ma = c(0.3), order = c(1, 1, 1)), sd = 1)
Error in arima.sim(n = 10, model = list(ar = c(1.1), ma = c(0.3), order = c(1,  :
  'ar' part of model is not stationary

WHAT I WANT

Can it be said in a public domain that it is not possible to simulate a series from ARIMA distribution? (having $\phi$ value as the estimate of AR parameter and $\theta$ asthe estimate of `MA parameter).

If it is possible, please demonstrate it for me using arima.sim() function or through any other way using R.

Body:
It is possible to simulate a nonstationary process using arima.sim. From ?arima:

For ARIMA models with differencing, the differenced series follows a zero-mean ARMA model.

Hence, in the call arima.sim(model = list(order, ar, ma), n) with order = c(p, d, q), ar and ma specify parameters of an ARMA(p, q) model for a d-order differenced time series, not an undifferenced time series.

Stationarity of the the differenced time series is enforced with the following constraint on ar, which you can find in the body of arima.sim:

    p <- length(model$ar)
    if (p) {
        minroots <- min(Mod(polyroot(c(1, -model$ar))))
        if (minroots <= 1)
            stop("'ar' part of model is not stationary")
    }

In other words, the roots of the polynomial whose coefficients are c(1, -ar) are required to lie outside of the unit circle. (The very same constraint is stated here.)

Stationarity of the differenced time series does not imply stationarity of the undifferenced time series. In fact, the undifferenced time series is never stationary. ?arima.sim gives an example:

ts.sim <- arima.sim(list(order = c(1, 1, 0), ar = 0.7), n = 200)
ts.plot(ts.sim)

But it is better to compare collections of simulations:

set.seed(1L)
X <- replicate(50L, arima.sim(list(order = c(1, 0, 0), ar = 0.7), n = 200))
Y <- replicate(50L, arima.sim(list(order = c(1, 1, 0), ar = 0.7), n = 200))

par(mfrow = c(1L, 2L))
matplot(X, type = "l", main = "AR(1) = ARIMA(1, 0, 0)")
matplot(Y, type = "l", main = "ARIMA(1, 1, 0)")

If you insist on p-values, then you can perform Dickey-Fuller tests:

apply(X, 2L, function(x) tseries::adf.test(x, k = 0)$p.value)
##  [1] 0.9263981 0.9900000 0.9900000 0.2561765 0.9218488
##  [6] 0.9900000 0.1816286 0.9900000 0.9900000 0.9372659
## [11] 0.6991314 0.9018098 0.8618604 0.9390623 0.6203794
## [16] 0.9740316 0.9002020 0.8196272 0.6657746 0.9593784
## [21] 0.9900000 0.9900000 0.8572043 0.1337945 0.9817778
## [26] 0.9900000 0.9900000 0.9816193 0.9562682 0.9900000
## [31] 0.4298187 0.9550181 0.7608263 0.9900000 0.9455187
## [36] 0.7616230 0.9412379 0.9588200 0.9354637 0.9900000
## [41] 0.9900000 0.9628406 0.9818668 0.9203677 0.9804385
## [46] 0.9900000 0.9900000 0.9807893 0.9048136 0.9822757

apply(X, 2L, function(x) tseries::adf.test(diff(x), k = 0)$p.value)
##  [1] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [11] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [21] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [31] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [41] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01

apply(Y, 2L, function(x) tseries::adf.test(x, k = 0)$p.value)
##  [1] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [11] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [21] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [31] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01
## [41] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01

(These p-values are computed by linear interpolation on a very coarse grid. You should take 0.01 to mean some number between 0 and 0.01, and 0.99 to mean some number between 0.99 and 1.)


问:
How to import qt projects in visual c++ 2010?
I developed an application using qtCreator and I figured out that I need to import the project in visual studio. I tried to run the visual studio add-in (1.1.9) but it didn't work. Knowing that I have visual c++ express edition 2010

Are there any workarounds?

答:
I solved the problem using Qt Add-in a detailed solution can be found at
http://www.holoborodko.com/pavel/2011/02/01/how-to-compile-qt-4-7-with-visual-studio-2010/</p>


答:
Convert Using For Each

input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
obj = {}
const convertUsingForEach = (arr) => {
    let arrCount = 0;
    arr.forEach(i => {
        if (Array.isArray(i)) {
            arrCount++;
            i.forEach(j => {
                if (!obj[`array${arrCount}`]) {
                    obj[`array${arrCount}`] = {};
                }
                obj[`array${arrCount}`][j] = j;
            });
        } else {
            obj[i] = i;
        }
    })
}
convertUsingForEach(input);
console.log(obj);```
</div>
</div>
</p>
<p>Convert Using Reduce</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
let obj = {}
const convertUsingReduce = (arr) => {
    let arrCount = 0;
    return arr.reduce((a, b) => {
        if (Array.isArray(b)) {
            a[`array${++arrCount}`] = convertUsingReduce(b);
        } else {
            a[b] = b;
        };
        return a;
    }, {})
};
obj = convertUsingReduce(input);
console.log(obj);</code>```

Title: nested array to object javascript

Body:
convert to object

[1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12]

Output want

{
  1: 1,
  2: 2,
  'array1': {
    4: 4,
    5: 5,
    6: 6
  },
  7: 7,
  8: 8,
  'array2': {
    9: 9,
    0: 0
  },
  11: 11,
  12: 12
}

but output get {
1: 1,
11: 11,
12: 12,
2: 2,
7: 7,
8: 8
}

my code

input = [1,2,[4,5,6],7,8,[9,0],11,12];
obj = {}

const convert = (arr) =>{
for (i = 0; i < arr.length; i++){
    if(!Array.isArray(arr[i])){
        obj[arr[i]] = arr[i];
    }

 }}
    convert(input);
    console.log(obj);

Body:
Convert Using For Each

input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
obj = {}
const convertUsingForEach = (arr) => {
    let arrCount = 0;
    arr.forEach(i => {
        if (Array.isArray(i)) {
            arrCount++;
            i.forEach(j => {
                if (!obj[`array${arrCount}`]) {
                    obj[`array${arrCount}`] = {};
                }
                obj[`array${arrCount}`][j] = j;
            });
        } else {
            obj[i] = i;
        }
    })
}
convertUsingForEach(input);
console.log(obj);

Convert Using Reduce

const input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
let obj = {}
const convertUsingReduce = (arr) => {
    let arrCount = 0;
    return arr.reduce((a, b) => {
        if (Array.isArray(b)) {
            a[`array${++arrCount}`] = convertUsingReduce(b);
        } else {
            a[b] = b;
        };
        return a;
    }, {})
};
obj = convertUsingReduce(input);
console.log(obj);


问:
Nested cases Isar
I'm having some issues trying to do exercise 4.5 of 'Concrete Semantics' in Isar:

```<code>inductive S :: "alpha list ⇒ bool" where
 Sε : "S []" |
 aSb : "S m ⟹ S (a#m @ [b])" |
 SS : "S l ⟹ S r ⟹ S (l @ r)"

inductive T :: "alpha list ⇒ bool" where
 Tε : "T []" |
 TaTb : "T l ⟹ T r ⟹ T (l @ a#(r @ [b]))"

lemma TS: "T w ⟹ S w"
proof (induction w rule: T.induct)
  case Tε
  show ?case by (simp add:Sε)
  case (TaTb l r) show ?case using TaTb.IH(1) (* This being S l, which allows us to case-split on l using S.induct *)
  proof (cases "l" rule: S.induct)
    case Sε
    then show ?case by (simp add: TaTb.IH(2) aSb)
  next case (aSb m)
</code>```

I'm getting Illegal schematic variable(s) in case "aSb"⌂
Also I find suspicious that in Sε I cannot refer to ?case, I get Unbound schematic variable: ?case. I'm thinking that maybe the problem is that I have a cases in an induction?

答:
As summarized by the comments, you have two problems:

cases "l" rule: S.induct makes little sense and you should either use a nested induction induction l rule: S.induct or a case distinction cases l rule: S.cases

In cases you should use ?thesis instead of cases as the Isabelle/jEdit outline tells you (you can click on that thing to insert it into the buffer!). That way you would also have given a name to all variable in the case TaTb.

So you probably want something like:

```<code>lemma TS: "T w ⟹ S w"
proof (induction w rule: T.induct)
  case Tε
  show ?case by (simp add:Sε)
next
  case (TaTb l r a b) show ?case using TaTb.IH(1)
  proof (cases "l" rule: S.cases)
    case Sε
    then show ?thesis sorry
  next
    case (aSb m a b)
    then show ?thesis sorry
  next
    case (SS l r)
    then show ?thesis sorry
  qed
qed
</code>```

Title: Nested cases Isar

Body:
I'm having some issues trying to do exercise 4.5 of 'Concrete Semantics' in Isar:

inductive S :: "alpha list ⇒ bool" where
 Sε : "S []" |
 aSb : "S m ⟹ S (a#m @ [b])" |
 SS : "S l ⟹ S r ⟹ S (l @ r)"

inductive T :: "alpha list ⇒ bool" where
 Tε : "T []" |
 TaTb : "T l ⟹ T r ⟹ T (l @ a#(r @ [b]))"

lemma TS: "T w ⟹ S w"
proof (induction w rule: T.induct)
  case Tε
  show ?case by (simp add:Sε)
  case (TaTb l r) show ?case using TaTb.IH(1) (* This being S l, which allows us to case-split on l using S.induct *)
  proof (cases "l" rule: S.induct)
    case Sε
    then show ?case by (simp add: TaTb.IH(2) aSb)
  next case (aSb m)

I'm getting Illegal schematic variable(s) in case "aSb"⌂
Also I find suspicious that in Sε I cannot refer to ?case, I get Unbound schematic variable: ?case. I'm thinking that maybe the problem is that I have a cases in an induction?

Body:
As summarized by the comments, you have two problems:

cases "l" rule: S.induct makes little sense and you should either use a nested induction induction l rule: S.induct or a case distinction cases l rule: S.cases

In cases you should use ?thesis instead of cases as the Isabelle/jEdit outline tells you (you can click on that thing to insert it into the buffer!). That way you would also have given a name to all variable in the case TaTb.

So you probably want something like:

lemma TS: "T w ⟹ S w"
proof (induction w rule: T.induct)
  case Tε
  show ?case by (simp add:Sε)
next
  case (TaTb l r a b) show ?case using TaTb.IH(1)
  proof (cases "l" rule: S.cases)
    case Sε
    then show ?thesis sorry
  next
    case (aSb m a b)
    then show ?thesis sorry
  next
    case (SS l r)
    then show ?thesis sorry
  qed
qed


问:
ERR_CONNECTION_REFUSED occurs when accessing a public IP address in EC2
I have created an infrastructure (application) using AWS, Docker (docker-compose), and Rails.

After launching the container in EC2 and starting the rails server, I get "ERR_CONNECTION_REFUSED" when I access the public IP address.

I would like to know how to display the application screen.

My directory structure looks like:

```<code>kthr01/
  docker-compose.yml
  Dockerfile
  start.sh
  src/
    app/
     bin/
     ....
</code>```

Dockerfile

```<code>FROM ruby:2.7

ENV RAILS_ENV=production

RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
  && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list \
  && apt-get update -qq \
  && apt-get install -y nodejs yarn \
  && apt-get install -y vim
WORKDIR /app
COPY ./src /app
RUN bundle config --local set path 'vendor/bundle' \
  && bundle install

COPY start.sh /start.sh
RUN chmod 744 /start.sh
CMD ["sh", "/start.sh"]

</code>```

docker-compose.yml

```<code>version: '3'
services:
  db:
    image: mysql:8.0
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - ./src/db/mysql_data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - ./src:/app
    ports:
      - "3000:3000"
    depends_on:
      - db
</code>```

start.sh

```<code>#!/bin/sh

if [ "${RAILS_ENV}" = "production" ]
then
    bundle exec rails assets:precompile
fi
bundle exec rails s -p ${PORT:-3000} -b 0.0.0.0
</code>```

I have a screen shot of the AWS console showing the EC2 security group setup:

To run this:

Verify that the container is created in the local environment and appears correctly on localhost:3000

↓

Connect to EC2 via ssh

↓

git clone

↓

docker-compose build

↓

```<code>docker-compose up
...
web_1  | => Booting Puma
web_1  | => Rails 6.1.4.4 application starting in production
web_1  | => Run `bin/rails server --help` for more startup options
web_1  | Puma starting in single mode...
web_1  | * Puma version: 5.6.1 (ruby 2.7.5-p203) ("Birdie's Version")
web_1  | *  Min threads: 5
web_1  | *  Max threads: 5
web_1  | *  Environment: production
web_1  | *          PID: 1
web_1  | * Listening on http://0.0.0.0:3000
web_1  | Use Ctrl-C to stop
</code>```

↓

Access the public IP address of EC2

↓

ERR_CONNECTION_REFUSED is displayed

答:
Based on the comments.

The issue was blocked port 3000 in a security group. The solution was to allow that port.

Body:
I have created an infrastructure (application) using AWS, Docker (docker-compose), and Rails.

After launching the container in EC2 and starting the rails server, I get "ERR_CONNECTION_REFUSED" when I access the public IP address.

I would like to know how to display the application screen.

My directory structure looks like:

kthr01/
  docker-compose.yml
  Dockerfile
  start.sh
  src/
    app/
     bin/
     ....

Dockerfile

FROM ruby:2.7

ENV RAILS_ENV=production

RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
  && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list \
  && apt-get update -qq \
  && apt-get install -y nodejs yarn \
  && apt-get install -y vim
WORKDIR /app
COPY ./src /app
RUN bundle config --local set path 'vendor/bundle' \
  && bundle install

COPY start.sh /start.sh
RUN chmod 744 /start.sh
CMD ["sh", "/start.sh"]

docker-compose.yml

version: '3'
services:
  db:
    image: mysql:8.0
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - ./src/db/mysql_data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - ./src:/app
    ports:
      - "3000:3000"
    depends_on:
      - db

start.sh

#!/bin/sh

if [ "${RAILS_ENV}" = "production" ]
then
    bundle exec rails assets:precompile
fi
bundle exec rails s -p ${PORT:-3000} -b 0.0.0.0

I have a screen shot of the AWS console showing the EC2 security group setup:

To run this:

Verify that the container is created in the local environment and appears correctly on localhost:3000

↓

Connect to EC2 via ssh

↓

git clone

↓

docker-compose build

↓

docker-compose up
...
web_1  | => Booting Puma
web_1  | => Rails 6.1.4.4 application starting in production
web_1  | => Run `bin/rails server --help` for more startup options
web_1  | Puma starting in single mode...
web_1  | * Puma version: 5.6.1 (ruby 2.7.5-p203) ("Birdie's Version")
web_1  | *  Min threads: 5
web_1  | *  Max threads: 5
web_1  | *  Environment: production
web_1  | *          PID: 1
web_1  | * Listening on http://0.0.0.0:3000
web_1  | Use Ctrl-C to stop

↓

Access the public IP address of EC2

↓

ERR_CONNECTION_REFUSED is displayed


问:
Word split in oracle
i have a table

Create table emp_details(eno number,ename varchar2(22));
```

having values below

eno
ename

1
suresh kumar

2
ram kumar

now i want to split the ename as two columns by using the space.

eno
ename
col1
col2

1
suresh kumar
suresh
kumar

2
ram kumar
ram
kumar

答:
You can use regular expressions if the data set is not relatively huge

WITH emp_details(eno,ename) AS
(
 SELECT 1, 'suresh kumar'    FROM dual UNION ALL
 SELECT 2, 'ram kumar'       FROM dual
)
SELECT eno,
       REGEXP_SUBSTR(ename,'[^ ]+') AS name,
       REGEXP_SUBSTR(ename,'[^ ]+$') AS surname
  FROM emp_details
```
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ENO</th>
<th>NAME</th>
<th>SURNAME</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>suresh</td>
<td>kumar</td>
</tr>
<tr>
<td>2</td>
<td>ram</td>
<td>kumar</td>
</tr>
</tbody>
</table>
</div>
<p>But if there can be people with names <em>more than one word</em> in the data set, then rather prefer using</p>
<pre class="lang-sql prettyprint-override"><code>WITH emp_details(eno,ename) AS
(
 SELECT 1, 'suresh kumar'    FROM dual UNION ALL
 SELECT 2, 'ram kumar'       FROM dual UNION ALL
 SELECT 3, 'ram sahil kumar' FROM dual
)
SELECT eno,
       REGEXP_REPLACE(ename, '^(.*) .*$', '\1') AS name,
       REGEXP_SUBSTR(ename,'[^ ]+$') AS surname
  FROM emp_details
</code>```

ENO
NAME
SURNAME

1
suresh
kumar

2
ram
kumar

3
ram sahil
kumar

Demo

Title: Word split in oracle

Body:
i have a table

Create table emp_details(eno number,ename varchar2(22));

having values below

eno
ename

1
suresh kumar

2
ram kumar

now i want to split the ename as two columns by using the space.

eno
ename
col1
col2

1
suresh kumar
suresh
kumar

2
ram kumar
ram
kumar

Body:
You can use regular expressions if the data set is not relatively huge

WITH emp_details(eno,ename) AS
(
 SELECT 1, 'suresh kumar'    FROM dual UNION ALL
 SELECT 2, 'ram kumar'       FROM dual
)
SELECT eno,
       REGEXP_SUBSTR(ename,'[^ ]+') AS name,
       REGEXP_SUBSTR(ename,'[^ ]+$') AS surname
  FROM emp_details

ENO
NAME
SURNAME

1
suresh
kumar

2
ram
kumar

But if there can be people with names more than one word in the data set, then rather prefer using

WITH emp_details(eno,ename) AS
(
 SELECT 1, 'suresh kumar'    FROM dual UNION ALL
 SELECT 2, 'ram kumar'       FROM dual UNION ALL
 SELECT 3, 'ram sahil kumar' FROM dual
)
SELECT eno,
       REGEXP_REPLACE(ename, '^(.*) .*$', '\1') AS name,
       REGEXP_SUBSTR(ename,'[^ ]+$') AS surname
  FROM emp_details

ENO
NAME
SURNAME

1
suresh
kumar

2
ram
kumar

3
ram sahil
kumar

Demo


问:
Perform dragdrop implementation after DoDragDrop method is called？WPF
I've been struggling with this for quite a while

My wpf application contains a list view, populated with file-names, which are located on a server.

I'm trying to implement drag and drop functionality, so the user can drag files from my application into his/her's local computer.

In order to do this, first i'm downloading the files into a temporary location, and then calling my application's DoDragDrop() method.

The problem is that I want to perform the download process only after the DoDragDrop method is called.

I've tried every event related to drag drop methods (GiveFeedback, ItemDrag, etc...) but nothing works

so basically what I need is an event, raised after the DoDragDrop is done

any ideas?

答: The current scheme is to drag a file with a special suffix, and then turn on global file monitoring to obtain the drag location of the file through monitoring.</p>


问:
How do I turn off the "Evaluating: plt.show() did not finish after 3.00s seconds." warning in the VsCode debugger?
I often debug my python code by plotting NumPy arrays in the vscode debugger.
Often I spend more than 3s looking at a plot. When I do vscode prints the extremely
long warning below. It's very annoying because I then have to scroll up a lot
all the time to see previous debugging outputs. Where is this PYDEVD_WARN_EVALUATION_TIMEOUT
variable? How do I turn this off?

I included the warning below for completeness, thanks a lot for your help!

Evaluating: plt.show() did not finish after 3.00s seconds.
This may mean a number of things:

This evaluation is really slow and this is expected.
In this case it's possible to silence this error by raising the timeout, setting the
PYDEVD_WARN_EVALUATION_TIMEOUT environment variable to a bigger value.

The evaluation may need other threads running while it's running:
In this case, it's possible to set the PYDEVD_UNBLOCK_THREADS_TIMEOUT
environment variable so that if after a given timeout an evaluation doesn't finish,
other threads are unblocked or you can manually resume all threads.

Alternatively, it's also possible to skip breaking on a particular thread by setting a
pydev_do_not_trace = True attribute in the related threading.Thread instance
(if some thread should always be running and no breakpoints are expected to be hit in it).

The evaluation is deadlocked:
In this case you may set the PYDEVD_THREAD_DUMP_ON_WARN_EVALUATION_TIMEOUT
environment variable to true so that a thread dump is shown along with this message and
optionally, set the PYDEVD_INTERRUPT_THREAD_TIMEOUT to some value so that the debugger
tries to interrupt the evaluation (if possible) when this happens.

答:
based on here, you can simply set the timeout parameter of debug configuration(launch.json). for example, sth like this:</p>
```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "timeout": 10,
            "program": "${workspaceFolder}/src/manage.py",
            "args": [
                "runserver"
            ],
            "django": true
        }
    ]
}
</code>```

Body:
based on here, you can simply set the timeout parameter of debug configuration(launch.json). for example, sth like this:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "timeout": 10,
            "program": "${workspaceFolder}/src/manage.py",
            "args": [
                "runserver"
            ],
            "django": true
        }
    ]
}


问:
extract bit in Ruby Integers
I need to get the n-th bit of an Integer, either signed or unsigned, in Ruby.

```<code>x = 123 # that is 1111011
n = 2   # bit 2 is ...0
</code>```

The following piece of code doesn't work in the general case:

```<code>x.to_s(2)[-(n+1)] #0 good! but...
</code>```

because of negative numbers not represented as 2-complement:

```<code>-123.to_s(2) # "-1111011"
</code>```

So how to proceed?

Title: extract bit in Ruby Integers

Body:
I need to get the n-th bit of an Integer, either signed or unsigned, in Ruby.

x = 123 # that is 1111011
n = 2   # bit 2 is ...0

The following piece of code doesn't work in the general case:

x.to_s(2)[-(n+1)] #0 good! but...

because of negative numbers not represented as 2-complement:

-123.to_s(2) # "-1111011"

So how to proceed?

Body:
x = 123 # that is 1111011
n = 2   # bit 2 is ...0

x[n]    # => 0

-123[2] # => 1


问:
Location of Rotated Point
Question: How do I get the location of a point after rotation?

Goal: I want to create a triangle given two angles. The user can manipulate two angles (a0,b0) and the program will determine the third vertex based on the intersection of the two sides.

Explanation: To find the point of intersection of the two sides, I need four points: the endpoints for l1 and l2. To keep track of the points, I created vertices=[]. But the array doesn't update the location of the points after the user rotates the sides and changes (a0,b0).

Thus, when I retrieve my points, two of them are in their initialized position, and have not been updated after the user rotates the sides. I've searched for this problem online, but to no avail. Any help is appreciated.

MWE:

let angle = 0;
let sides = [];
let vertices = [];
function setup(){
  createCanvas(600, 400);
  angleMode(DEGREES);

  angleOne = createSlider(0, 180, 100);
  angleOne.position(10,10);
  angleOne.style('width', '80px');

  angleTwo = createSlider(0, 180, 100);
  angleTwo.position(10,30);
  angleTwo.style('width', '80px');
}

function draw(){
  background(255);

  let angOne = angleOne.value();
  let angTwo = angleTwo.value();

  strokeWeight(0);
  textSize(15);
  text(angOne, 90, 17);
  text(angTwo, 90, 37);

  let v1 = createVector(width/2 - 50, height/2);
  let v2 = createVector(width/2 + 50, height/2);

  sides[0] = new Side(v1.x, v1.y, v2.x, v2.y);
  sides[0].show();

  vertices[0] = new Vertex(v1.x, v1.y);
  vertices[0].show();

  vertices[1] = new Vertex(v2.x, v2.y);
  vertices[1].show();

  /** ROTATE TIME **/
  push();
  translate(v1.x, v1.y);
  rotate(-1*angOne);
  translate(-v1.x, -v1.y);

  sides[1] = new Side(v1.x, v1.y, v2.x, v2.y);
  sides[1].show();

  vertices[2] = new Vertex(v2.x, v2.y);
  vertices[2].show();

  pop();

  /** ROTATE TIME **/
  push();
  translate(v2.x, v2.y);
  rotate(angTwo);
  translate(-v2.x, -v2.y);

  sides[2] = new Side(v1.x, v1.y, v2.x, v2.y);
  sides[2].show();

  vertices[3] = new Vertex(v1.x, v1.y);
  vertices[3].show();

  pop();

  // const x1 = sides[0].a.x;
  // const y1 = sides[0].a.y;
  // const x2 = sides[1].a.x;
  // const y2 = sides[1].a.y;
  //
  // const x3 = p3.x;
  // const y3 = p3.y;
  // const x4 = p4.x;
  // const y4 = p4.y;

}

class Side {
  constructor(x1, y1, x2, y2){
    this.a = createVector(x1, y1);
    this.b = createVector(x2, y2);
  }

  show() {
    stroke(0);
    strokeWeight(4);
    line(this.a.x, this.a.y, this.b.x, this.b.y);
  }
}

class Vertex {
  constructor(x1, y1){
    this.a = createVector(x1, y1);
  }

  show() {
    stroke(255,0,0);
    strokeWeight(20);
    point(this.a.x, this.a.y);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script>

    <title>Billiards #2</title>
  </head>
  <body>
  </body>
</html></code>```

答:
In a word: trigonometry. Instead of using the rotate() function to rotate the drawing frame of reference, use trig to calculate the various vertex positions. Here's code with comments which hopefully explain how this is done:

let angle = 0;
let sides = [];
let vertices = [];

const len = 100;

function setup() {
  createCanvas(600, 400);
  angleMode(DEGREES);

  angleOne = createSlider(0, 180, 45);
  angleOne.position(10, 10);
  angleOne.style('width', '80px');

  angleTwo = createSlider(0, 180, 100);
  angleTwo.position(10, 30);
  angleTwo.style('width', '80px');

  // Initial vertice & side setup (these don't change)
  let v1 = createVector(width / 2 - len / 2, height / 2);
  let v2 = createVector(width / 2 + len / 2, height / 2);

  sides[0] = new Side(v1.x, v1.y, v2.x, v2.y);

  vertices[0] = new Vertex(v1.x, v1.y);
  vertices[1] = new Vertex(v2.x, v2.y);
}

function draw() {
  background(255);

  let angOne = angleOne.value();
  let angTwo = angleTwo.value();

  strokeWeight(0);
  textSize(15);
  text(angOne, 90, 17);
  text(angTwo, 90, 37);

  // Calculate vertices 2 and 3 based on angles
  // We can use trigonometry to find the x and y component of a vector of known length based on the angle from some refference.
  // In this case our reference will be in the positive X direction.
  // The sine of an angle is, given a right triangle, equal to the ratio of the opposite side from that angle and the hypotenuse of the triangle, so that corresponds to our Y component.
  // The cosine is the ratio of the adjacent side over the hypotenuse, so that represents our X component
  let v2Offset = createVector(
    len * cos(-angOne),
    len * sin(-angOne)
  );
  // Our reference vector for this is in the negative X direction and we are rotating clockwise instead of counter clockwise, hence the different signs
  let v3Offset = createVector(-len * cos(angTwo), -len * sin(angTwo));

  // Add our offsets to the origins in order to calculate the actual positions for these vertices.
  vertices[2] = new Vertex(
    vertices[0].a.x + v2Offset.x,
    vertices[0].a.y + v2Offset.y
  );
  vertices[3] = new Vertex(
    vertices[1].a.x + v3Offset.x,
    vertices[1].a.y + v3Offset.y
  );

  // Update the sides
  sides[1] = new Side(
    vertices[0].a.x,
    vertices[0].a.y,
    vertices[2].a.x,
    vertices[2].a.y
  );

  sides[3] = new Side(
    vertices[1].a.x,
    vertices[1].a.y,
    vertices[3].a.x,
    vertices[3].a.y
  );

  // Now that are vertices are all computed properly finding the intersection of these two lines is a simple matter:

  // Calculate the slopes
  const m1 = (vertices[2].a.y - vertices[0].a.y) / (vertices[2].a.x - vertices[0].a.x);

  const m2 = (vertices[3].a.y - vertices[1].a.y) / (vertices[3].a.x - vertices[1].a.x);

  // Calculate the y-offset relative to vertices[0]
  const b2 = (vertices[1].a.x - vertices[0].a.x) * -m2;

  // y1 = m1 * x
  // y2 = m2 * x + b2
  // Find the x where y1 = y2
  // m1 * x = m2 * x + b2
  // m1 * x - m2 * x = b2
  // x * (m1 - m2) = b2
  // x = b2 / (m1 - m2)

  const xInt = b2 / (m1 - m2)
  const yInt = xInt * m1;
  // Note xInt and yInt are relative to vertices[0]

  // draw all the things
  sides.forEach(s => s.show());
  vertices.forEach(v => v.show());

  stroke(0, 255, 0);
  strokeWeight(20);
  point(vertices[0].a.x + xInt, vertices[0].a.y + yInt);
}

class Side {
  constructor(x1, y1, x2, y2) {
    this.a = createVector(x1, y1);
    this.b = createVector(x2, y2);
  }

  show() {
    stroke(0);
    strokeWeight(4);
    line(this.a.x, this.a.y, this.b.x, this.b.y);
  }
}

class Vertex {
  constructor(x1, y1) {
    this.a = createVector(x1, y1);
  }

  show() {
    stroke(255, 0, 0);
    strokeWeight(20);
    point(this.a.x, this.a.y);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script></code>```

Title: Location of Rotated Point

Body:
Question: How do I get the location of a point after rotation?

Goal: I want to create a triangle given two angles. The user can manipulate two angles (a0,b0) and the program will determine the third vertex based on the intersection of the two sides.

Explanation: To find the point of intersection of the two sides, I need four points: the endpoints for l1 and l2. To keep track of the points, I created vertices=[]. But the array doesn't update the location of the points after the user rotates the sides and changes (a0,b0).

Thus, when I retrieve my points, two of them are in their initialized position, and have not been updated after the user rotates the sides. I've searched for this problem online, but to no avail. Any help is appreciated.

MWE:

let angle = 0;
let sides = [];
let vertices = [];
function setup(){
  createCanvas(600, 400);
  angleMode(DEGREES);

  angleOne = createSlider(0, 180, 100);
  angleOne.position(10,10);
  angleOne.style('width', '80px');

  angleTwo = createSlider(0, 180, 100);
  angleTwo.position(10,30);
  angleTwo.style('width', '80px');
}

function draw(){
  background(255);

  let angOne = angleOne.value();
  let angTwo = angleTwo.value();

  strokeWeight(0);
  textSize(15);
  text(angOne, 90, 17);
  text(angTwo, 90, 37);

  let v1 = createVector(width/2 - 50, height/2);
  let v2 = createVector(width/2 + 50, height/2);

  sides[0] = new Side(v1.x, v1.y, v2.x, v2.y);
  sides[0].show();

  vertices[0] = new Vertex(v1.x, v1.y);
  vertices[0].show();

  vertices[1] = new Vertex(v2.x, v2.y);
  vertices[1].show();

  /** ROTATE TIME **/
  push();
  translate(v1.x, v1.y);
  rotate(-1*angOne);
  translate(-v1.x, -v1.y);

  sides[1] = new Side(v1.x, v1.y, v2.x, v2.y);
  sides[1].show();

  vertices[2] = new Vertex(v2.x, v2.y);
  vertices[2].show();

  pop();

  /** ROTATE TIME **/
  push();
  translate(v2.x, v2.y);
  rotate(angTwo);
  translate(-v2.x, -v2.y);

  sides[2] = new Side(v1.x, v1.y, v2.x, v2.y);
  sides[2].show();

  vertices[3] = new Vertex(v1.x, v1.y);
  vertices[3].show();

  pop();

  // const x1 = sides[0].a.x;
  // const y1 = sides[0].a.y;
  // const x2 = sides[1].a.x;
  // const y2 = sides[1].a.y;
  //
  // const x3 = p3.x;
  // const y3 = p3.y;
  // const x4 = p4.x;
  // const y4 = p4.y;

}

class Side {
  constructor(x1, y1, x2, y2){
    this.a = createVector(x1, y1);
    this.b = createVector(x2, y2);
  }

  show() {
    stroke(0);
    strokeWeight(4);
    line(this.a.x, this.a.y, this.b.x, this.b.y);
  }
}

class Vertex {
  constructor(x1, y1){
    this.a = createVector(x1, y1);
  }

  show() {
    stroke(255,0,0);
    strokeWeight(20);
    point(this.a.x, this.a.y);
  }
}

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <title>Billiards #2</title>

Body:
In a word: trigonometry. Instead of using the rotate() function to rotate the drawing frame of reference, use trig to calculate the various vertex positions. Here's code with comments which hopefully explain how this is done:

let angle = 0;
let sides = [];
let vertices = [];

const len = 100;

function setup() {
  createCanvas(600, 400);
  angleMode(DEGREES);

  angleOne = createSlider(0, 180, 45);
  angleOne.position(10, 10);
  angleOne.style('width', '80px');

  angleTwo = createSlider(0, 180, 100);
  angleTwo.position(10, 30);
  angleTwo.style('width', '80px');

  // Initial vertice & side setup (these don't change)
  let v1 = createVector(width / 2 - len / 2, height / 2);
  let v2 = createVector(width / 2 + len / 2, height / 2);

  sides[0] = new Side(v1.x, v1.y, v2.x, v2.y);

  vertices[0] = new Vertex(v1.x, v1.y);
  vertices[1] = new Vertex(v2.x, v2.y);
}

function draw() {
  background(255);

  let angOne = angleOne.value();
  let angTwo = angleTwo.value();

  strokeWeight(0);
  textSize(15);
  text(angOne, 90, 17);
  text(angTwo, 90, 37);

  // Calculate vertices 2 and 3 based on angles
  // We can use trigonometry to find the x and y component of a vector of known length based on the angle from some refference.
  // In this case our reference will be in the positive X direction.
  // The sine of an angle is, given a right triangle, equal to the ratio of the opposite side from that angle and the hypotenuse of the triangle, so that corresponds to our Y component.
  // The cosine is the ratio of the adjacent side over the hypotenuse, so that represents our X component
  let v2Offset = createVector(
    len * cos(-angOne),
    len * sin(-angOne)
  );
  // Our reference vector for this is in the negative X direction and we are rotating clockwise instead of counter clockwise, hence the different signs
  let v3Offset = createVector(-len * cos(angTwo), -len * sin(angTwo));

  // Add our offsets to the origins in order to calculate the actual positions for these vertices.
  vertices[2] = new Vertex(
    vertices[0].a.x + v2Offset.x,
    vertices[0].a.y + v2Offset.y
  );
  vertices[3] = new Vertex(
    vertices[1].a.x + v3Offset.x,
    vertices[1].a.y + v3Offset.y
  );

  // Update the sides
  sides[1] = new Side(
    vertices[0].a.x,
    vertices[0].a.y,
    vertices[2].a.x,
    vertices[2].a.y
  );

  sides[3] = new Side(
    vertices[1].a.x,
    vertices[1].a.y,
    vertices[3].a.x,
    vertices[3].a.y
  );

  // Now that are vertices are all computed properly finding the intersection of these two lines is a simple matter:

  // Calculate the slopes
  const m1 = (vertices[2].a.y - vertices[0].a.y) / (vertices[2].a.x - vertices[0].a.x);

  const m2 = (vertices[3].a.y - vertices[1].a.y) / (vertices[3].a.x - vertices[1].a.x);

  // Calculate the y-offset relative to vertices[0]
  const b2 = (vertices[1].a.x - vertices[0].a.x) * -m2;

  // y1 = m1 * x
  // y2 = m2 * x + b2
  // Find the x where y1 = y2
  // m1 * x = m2 * x + b2
  // m1 * x - m2 * x = b2
  // x * (m1 - m2) = b2
  // x = b2 / (m1 - m2)

  const xInt = b2 / (m1 - m2)
  const yInt = xInt * m1;
  // Note xInt and yInt are relative to vertices[0]

  // draw all the things
  sides.forEach(s => s.show());
  vertices.forEach(v => v.show());

  stroke(0, 255, 0);
  strokeWeight(20);
  point(vertices[0].a.x + xInt, vertices[0].a.y + yInt);
}

class Side {
  constructor(x1, y1, x2, y2) {
    this.a = createVector(x1, y1);
    this.b = createVector(x2, y2);
  }

  show() {
    stroke(0);
    strokeWeight(4);
    line(this.a.x, this.a.y, this.b.x, this.b.y);
  }
}

class Vertex {
  constructor(x1, y1) {
    this.a = createVector(x1, y1);
  }

  show() {
    stroke(255, 0, 0);
    strokeWeight(20);
    point(this.a.x, this.a.y);
  }
}

<script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script>


问:
Publish message to connected clients from Web API through SignalR
Currently I had my server side web application to create a client to call my web API endpoint, it publish message back to web application (client) appropriately.

I have the idea, is that be possible to trigger the web API endpoint using Postman, then all connected client will receive message that this task is executing.

My endpoint

```<code>public class DailyPostingController : ControllerBase
{
    private readonly IMapper _mapper;
    private readonly IDailyPostingService _DailyPostingService;
    private readonly ILogger<DailyPostingController> _logger;

    public DailyPostingController(IMapper mapper,
        IDailyPostingService DailyPostingService,
        ILogger<DailyPostingController> logger)
    {
        _mapper = mapper;
        _DailyPostingService = DailyPostingService;
        _logger = logger;
    }

    [Authorize(Policy = Permissions.DailyPosting.Execute)]
    [HttpPost("Execute")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<int> Execute(OperatingCentreQueryModel ocQueryModel)
    {
        _logger.LogDebug("Executing Daily posting for date#"
            + ocQueryModel.ProcessDate.ToString("dd/mmm/yyy"));

        //How to trigger the hub to tell connected clients this process is started?
        var res = await _DailyPostingService.Execute(ocQueryModel);
        //How to trigger the hub to tell connected clients this process was done?
        return res;
    }
}
</code>```

My hub

```<code>public class NotificationHub : Hub<INotificationHub>
{
    private readonly UsersState _usersState;
    private readonly ProcessState _processState;
    private readonly ILogger<NotificationHub> _logger;

    public NotificationHub(UsersState usersState, ProcessState processState,
        ILogger<NotificationHub> logger)
    {
        _usersState = usersState;
        _processState = processState;
        _logger = logger;
    }

    public async Task SendMessage(string user, string message)
    {
        await Clients.All.ReceiveMessage(user, message);
    }

    public async Task SendMessageToCaller(string user, string message)
    {
        await Clients.Caller.ReceiveMessage(user, message);
    }

    public async Task SendMessageToGroup(string user, string group, string message)
    {
        await Clients.Group(group).ReceiveMessage(user, message);
    }

    public override Task OnConnectedAsync()
    {
        LogDebug($"({Context.ConnectionId}) connected to notification hub.");
        return base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        LogDebug($"({Context.ConnectionId}) disconnected to notification hub.");
        _usersState.RemoveConnectionId(Context.ConnectionId,
            async (user) =>
            {
                await RemoveUser(user);
                await RemoveUserProcess(user);
            });

        await base.OnDisconnectedAsync(exception);
    }

    private void LogDebug(string msg)
    {
        _logger.LogDebug("*** " + msg);
    }
</code>```

答: The docs describe how to do this https://learn.microsoft.com/aspnet/core/signalr/hubcontext?view=aspnetcore-6.0</p>

Body:
Currently I had my server side web application to create a client to call my web API endpoint, it publish message back to web application (client) appropriately.

I have the idea, is that be possible to trigger the web API endpoint using Postman, then all connected client will receive message that this task is executing.

My endpoint

public class DailyPostingController : ControllerBase
{
    private readonly IMapper _mapper;
    private readonly IDailyPostingService _DailyPostingService;
    private readonly ILogger<DailyPostingController> _logger;

    public DailyPostingController(IMapper mapper,
        IDailyPostingService DailyPostingService,
        ILogger<DailyPostingController> logger)
    {
        _mapper = mapper;
        _DailyPostingService = DailyPostingService;
        _logger = logger;
    }

    [Authorize(Policy = Permissions.DailyPosting.Execute)]
    [HttpPost("Execute")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<int> Execute(OperatingCentreQueryModel ocQueryModel)
    {
        _logger.LogDebug("Executing Daily posting for date#"
            + ocQueryModel.ProcessDate.ToString("dd/mmm/yyy"));

        //How to trigger the hub to tell connected clients this process is started?
        var res = await _DailyPostingService.Execute(ocQueryModel);
        //How to trigger the hub to tell connected clients this process was done?
        return res;
    }
}

My hub

public class NotificationHub : Hub<INotificationHub>
{
    private readonly UsersState _usersState;
    private readonly ProcessState _processState;
    private readonly ILogger<NotificationHub> _logger;

    public NotificationHub(UsersState usersState, ProcessState processState,
        ILogger<NotificationHub> logger)
    {
        _usersState = usersState;
        _processState = processState;
        _logger = logger;
    }

    public async Task SendMessage(string user, string message)
    {
        await Clients.All.ReceiveMessage(user, message);
    }

    public async Task SendMessageToCaller(string user, string message)
    {
        await Clients.Caller.ReceiveMessage(user, message);
    }

    public async Task SendMessageToGroup(string user, string group, string message)
    {
        await Clients.Group(group).ReceiveMessage(user, message);
    }

    public override Task OnConnectedAsync()
    {
        LogDebug($"({Context.ConnectionId}) connected to notification hub.");
        return base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        LogDebug($"({Context.ConnectionId}) disconnected to notification hub.");
        _usersState.RemoveConnectionId(Context.ConnectionId,
            async (user) =>
            {
                await RemoveUser(user);
                await RemoveUserProcess(user);
            });

        await base.OnDisconnectedAsync(exception);
    }

    private void LogDebug(string msg)
    {
        _logger.LogDebug("*** " + msg);
    }


问:
How should I call a Dialogflow CX Messenger script from Google Tag Manager?
I have setup my Dialogflow CX and Messenger on my web site and I want to execute commands with Google Tag manager.

Basically what I want to do is that if a user scrolls more than 75% of a page, vertically, GTM should trigger this example ( taken from https://cloud.google.com/dialogflow/cx/docs/concept/integration/dialogflow-messenger#rendercustomcard )

```<code>    const dfMessenger = document.querySelector('df-messenger');
const payload = [
  {
    "type": "info",
    "title": "Info item title",
    "subtitle": "Info item subtitle",
    "image": {
      "src": {
        "rawUrl": "https://example.com/images/logo.png"
      }
    },
    "actionLink": "https://example.com"
  }];
dfMessenger.renderCustomCard(payload);
</code>```

This code snippet works fine if I embed it in my web page, and also in when GTM triggers and embeds the tag after a scroll the snippet. But when I try the other types of cards, List type is what I would like to use in my case, I the following in my browsers console "DfMessenger: Could not render undefined".

Any clue if this is due to me triggering things from GTM or any ideas what I could test?

答:
Posting this answer from @Per Olsson as a wikianswer:

I figured out what was wrong with const dfMessenger = document.querySelector('df-messenger') dfMessenger.addEventListener('df-request-sent', function (event) { console.log(event) and compared with the objects and found a misspelled wording. Everything works but you have to be really careful with spelling. I still think the documentation is a bit poor though, but that is not for this forum.

Body:
I have setup my Dialogflow CX and Messenger on my web site and I want to execute commands with Google Tag manager.

Basically what I want to do is that if a user scrolls more than 75% of a page, vertically, GTM should trigger this example ( taken from https://cloud.google.com/dialogflow/cx/docs/concept/integration/dialogflow-messenger#rendercustomcard )

    const dfMessenger = document.querySelector('df-messenger');
const payload = [
  {
    "type": "info",
    "title": "Info item title",
    "subtitle": "Info item subtitle",
    "image": {
      "src": {
        "rawUrl": "https://example.com/images/logo.png"
      }
    },
    "actionLink": "https://example.com"
  }];
dfMessenger.renderCustomCard(payload);

This code snippet works fine if I embed it in my web page, and also in when GTM triggers and embeds the tag after a scroll the snippet. But when I try the other types of cards, List type is what I would like to use in my case, I the following in my browsers console "DfMessenger: Could not render undefined".

Any clue if this is due to me triggering things from GTM or any ideas what I could test?


问:
Gatsby V4: How to implement gatsby-plugin-react-i18next for client only routes
I'm trying to implement client routes in Gatsby together with gatsby-plugin-react-i18next for two languages. I followed officel Gataby documentation and there is no client only path implementation explained.

Below is the code i implemeted.

```<code>gatsby-node.js
   function langPrefix(page) {
      return page.context.language === page.context.i18n.defaultLanguage &&
        !page.context.i18n.generateDefaultLanguagePage
        ? ''
        : `/${page.context.language}`
    }

    exports.onCreatePage = ({ page, actions }) => {
      const { createPage } = actions
      // Removing the ^ skips an optional /:lang prefix
      if (page.path.match(/\/app/)) {
        // adding lang if it's not the default page.
        page.matchPath = `${langPrefix(page)}/app/*`
        createPage(page)
      }
    }
</code>```

Appjs

```<code> src/app/app.js
    function App() {
      return (
        <>
          <Router basepath="/:lang/app">
            <PrivateRoute path="/accounthome" component={AccountHome} location=""/>
          </Router>
          <Router basepath="/app">
            <PrivateRoute path="/accounthome" component={AccountHome} location=""/>
          </Router>
        </>)
    }
    export default App
</code>```

Gatsby config

```<code>{
      resolve: `gatsby-plugin-react-i18next`,
      options: {
        localeJsonSourceName: `locale`, // name given to `gatsby-source-filesystem` plugin.
        languages: ["en", "fr"],
        defaultLanguage: `en-us`,
        fallbackLanguage: `en-us`,
        // if you are using Helmet, you must include siteUrl, and make sure you add http:https
        siteUrl: `https://my.costco.com/`,
        ns: langTranslationConfig,
        // you can pass any i18next options
        i18nextOptions: {
          interpolation: {
            escapeValue: false // not needed for react as it escapes by default
          },
          nsSeparator: false
        },
        pages: [
          {
            matchPath: '/:lang/app/accounthome',
            getLanguageFromPath: true,
            excludeLanguages: ['en-ca']
          },
          {
            matchPath: '/preview',
            languages: ['en']
          }
        ]
      }
    }
</code>```

Router path : http://localhost:8000/en-us/app/accounthome
When am accessing this rote in browser This code show Gatsby.js development 404 page not found. Any pointer what am missing and am not sure how to access the translation contents in client only route page example account home page. Do i need to write the graph query in account home page or i dont need to ?

答:
I think your regex is leaking your code. I guess it should look like:

```<code>  if (page.path.match(/^\/app/)) {
    page.matchPath = `${langPrefix(page)}/app/*`
    createPage(page)
  }
</code>```

Either way, check the created page list by accessing the 404 page in development mode. By default, there should be a list of all created pages. Check the paths there to see if you can spot any mistakes or trailing slash issues.

The problem here is that your page is not being generated properly, that's why it throws a 404, so checking the created pages may help you to spot the mistake or at least, a thread to pull.

After a few research I've seen that you are basing your approach in: Gatsby can't find client routes when using gatsby-plugin-react-i18next

In their case, the langPrefix function is only prefixing the language to the page slug if it's the default one:

```<code>function langPrefix(page) {
  return page.context.language === page.context.i18n.defaultLanguage &&
    !page.context.i18n.generateDefaultLanguagePage
    ? ''
    : `/${page.context.language}`
}
</code>```

In your case, I'm not sure the plugin supports en-us (it's en-US according to https://github.com/microapps/gatsby-plugin-react-i18next/issues/100) and I think that's the reason why there's a leak in your page creation. Try using en instead of en-us or directly looking for en-US paths.

Body:
I'm trying to implement client routes in Gatsby together with gatsby-plugin-react-i18next for two languages. I followed officel Gataby documentation and there is no client only path implementation explained.

Below is the code i implemeted.

gatsby-node.js
   function langPrefix(page) {
      return page.context.language === page.context.i18n.defaultLanguage &&
        !page.context.i18n.generateDefaultLanguagePage
        ? ''
        : `/${page.context.language}`
    }

    exports.onCreatePage = ({ page, actions }) => {
      const { createPage } = actions
      // Removing the ^ skips an optional /:lang prefix
      if (page.path.match(/\/app/)) {
        // adding lang if it's not the default page.
        page.matchPath = `${langPrefix(page)}/app/*`
        createPage(page)
      }
    }

Appjs

 src/app/app.js
    function App() {
      return (
        <>
          <Router basepath="/:lang/app">
            <PrivateRoute path="/accounthome" component={AccountHome} location=""/>
          </Router>
          <Router basepath="/app">
            <PrivateRoute path="/accounthome" component={AccountHome} location=""/>
          </Router>
        </>)
    }
    export default App

Gatsby config

{
      resolve: `gatsby-plugin-react-i18next`,
      options: {
        localeJsonSourceName: `locale`, // name given to `gatsby-source-filesystem` plugin.
        languages: ["en", "fr"],
        defaultLanguage: `en-us`,
        fallbackLanguage: `en-us`,
        // if you are using Helmet, you must include siteUrl, and make sure you add http:https
        siteUrl: `https://my.costco.com/`,
        ns: langTranslationConfig,
        // you can pass any i18next options
        i18nextOptions: {
          interpolation: {
            escapeValue: false // not needed for react as it escapes by default
          },
          nsSeparator: false
        },
        pages: [
          {
            matchPath: '/:lang/app/accounthome',
            getLanguageFromPath: true,
            excludeLanguages: ['en-ca']
          },
          {
            matchPath: '/preview',
            languages: ['en']
          }
        ]
      }
    }

Router path : http://localhost:8000/en-us/app/accounthome
When am accessing this rote in browser This code show Gatsby.js development 404 page not found. Any pointer what am missing and am not sure how to access the translation contents in client only route page example account home page. Do i need to write the graph query in account home page or i dont need to ?

Body:
I think your regex is leaking your code. I guess it should look like:

  if (page.path.match(/^\/app/)) {
    page.matchPath = `${langPrefix(page)}/app/*`
    createPage(page)
  }

Either way, check the created page list by accessing the 404 page in development mode. By default, there should be a list of all created pages. Check the paths there to see if you can spot any mistakes or trailing slash issues.

The problem here is that your page is not being generated properly, that's why it throws a 404, so checking the created pages may help you to spot the mistake or at least, a thread to pull.

After a few research I've seen that you are basing your approach in: Gatsby can't find client routes when using gatsby-plugin-react-i18next

In their case, the langPrefix function is only prefixing the language to the page slug if it's the default one:

function langPrefix(page) {
  return page.context.language === page.context.i18n.defaultLanguage &&
    !page.context.i18n.generateDefaultLanguagePage
    ? ''
    : `/${page.context.language}`
}

In your case, I'm not sure the plugin supports en-us (it's en-US according to https://github.com/microapps/gatsby-plugin-react-i18next/issues/100) and I think that's the reason why there's a leak in your page creation. Try using en instead of en-us or directly looking for en-US paths.


问:
How can I use gvim to add a carriage return (aka ENTER) to a pattern?
What's the vi/gvim syntax to replace a pattern with a pattern that includes <ENTER>?  I know this is possible but never felt like diving too deep in the documentation to know how to do it.

Something like this:

```<code> :s/\(word\)/\1<ENTER>/
</code>```

But correctly :)

Thanks

答:
Use the "escape" encoding:

```<code>:s/\(word\)/\1\r/
</code>```

See the Vim documentation for pattern whitespace escapes.

OwnerDisplayName: Oscar Reyes

ContentLicense: CC BY-SA 2.5

Body:
What's the vi/gvim syntax to replace a pattern with a pattern that includes <ENTER>?  I know this is possible but never felt like diving too deep in the documentation to know how to do it.

Something like this:

 :s/\(word\)/\1<ENTER>/

But correctly :)

Thanks

LastEditorDisplayName: Chad Birch

Body:
Use the "escape" encoding:

:s/\(word\)/\1\r/

See the Vim documentation for pattern whitespace escapes.

OwnerDisplayName: dwc

LastEditorDisplayName: dwc


问:
I have this div with absolute positioning and another positioned div inside with width:100%. Why doesn't it fill up its parent?
I have a div that is as high as the window and about 4 times as wide (it is stretched horizontally by elements inside it).

And then this other
 inside it, which is supposed to be as wide width:100% as its parent (it's for a background picture).

However, the child
 is only as wide as the window and doesn't quite fill up its parent. This happens in all browsers I've tried.

Why is that, and how can I fix it ?

Source :

```<code><style>
.parent
{
width:100%;
height:100%;
overflow-x:scroll;
overflow-y:hidden;
position:absolute;
top:0;
left:0;
background-color:#999;
}

.child
{
width:100%;
height:200px;
position:absolute;
bottom:0;
left:0;
background-color:#000;
color:#fff;
}

.stretcher
{
width:10000px;
height:32px;
position:absolute;
}
</style>

<div class="parent">
  <div class="child">this should stretch as much as its parent !</div>
  <div class="stretcher">this is some content that defines the page's width</div>
</div>
</code>```

JSFiddle

答:
I'm not sure why the child
 doesn't fill the parent, but in order for it to work you need to wrap the .stretcher
 around both the parent and child
.

Source:

```<code>    <style>
        .parent {
            width:100%;
            height:100%;
            overflow-x:scroll;
            overflow-y:hidden;
            position:absolute;
            top:0;
            left:0;
            background-color:#999;
            }

        .child {
            width:100%;
            height:200px;
            position:absolute;
            bottom:0;
            background-color:#000;
            color:#fff;
            }

        .stretcher {
            width:10000px;
            height:100%;
            position:absolute;
            }
</code>```

```<code>    <div class="stretcher">
        <div class="parent"><p>this is some content that defines the page's width</p>
            <div class="child">this should stretch as much as its parent !</div>
        </div>
    </div>
</code>```

Body:
I have a div that is as high as the window and about 4 times as wide (it is stretched horizontally by elements inside it).

And then this other
 inside it, which is supposed to be as wide width:100% as its parent (it's for a background picture).

However, the child
 is only as wide as the window and doesn't quite fill up its parent. This happens in all browsers I've tried.

Why is that, and how can I fix it ?

Source :

this should stretch as much as its parent !

this is some content that defines the page's width

JSFiddle

Body:
I'm not sure why the child <div> doesn't fill the parent, but in order for it to work you need to wrap the .stretcher <div> around both the parent and child <div>.

Source:

    <style>
        .parent {
            width:100%;
            height:100%;
            overflow-x:scroll;
            overflow-y:hidden;
            position:absolute;
            top:0;
            left:0;
            background-color:#999;
            }

        .child {
            width:100%;
            height:200px;
            position:absolute;
            bottom:0;
            background-color:#000;
            color:#fff;
            }

        .stretcher {
            width:10000px;
            height:100%;
            position:absolute;
            }

    <div class="stretcher">
        <div class="parent"><p>this is some content that defines the page's width</p>
            <div class="child">this should stretch as much as its parent !</div>
        </div>
    </div>