Задать вопрос
  • Почему бот выдает ошибку No such file or directory: 'temp/?

    @zeni1agent Автор вопроса
    Сергей Карбивничий,
    1 Я запускаю скрипт через консоль с помощью команды. python C:\persoml-master\tbot.py
    2 запускаю его в telegram с помощью команды /star бот возвращает мне Hey Start .
    3 после я отправляю файл test.jpg как фото
    4 бот вылетает с ошибкой. 'line 28 No such file or directory: 'temp/86f7181e-cef6-4809-b61c-e61df0f43fc9.png'.
    OC win10
    Python 3.7.6
  • Почему бот выдает ошибку No such file or directory: 'temp/?

    @zeni1agent Автор вопроса
    Я уже создавал не помогло.
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, К сожалению я сам решил написать код для работы с svg файлом. Я просто не понимаю в каком репозиторий вы говорите мне искать. на сайте svg-points я нашел только две ссылки на проекты в github это points library и Wilderness DOM node. вы говорили
    Зайдите на страницу репозитория svg-points на гитхабе, возьмите нужный вам скрипт, тот в котором объявляется функция toPoints

    Я скачивал архив с points library и Wilderness DOM node. и искал текстовым редактором слово toPoints но единственное что было в файлах это
    import { toPoints } from 'svg-points'.
    Что означает что он импортирует с какого то файла toPoints в файл decurve.js или index.js.
    А где сама toPoints в каком репозиторий и файле находится я не знаю.
    И спасибо что хотя бы вы тратите время что бы мне это объяснить.
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky,
    /* globals __DEV__ */
    
    import { toPath, toPoints } from 'svg-points'
    const attributeBlacklist = [
      'data-jsx-ext',
      'data-reactid'
    ]
    const nodeCoreProps = [
      {
        type: 'circle',
        coreProps: [ 'cx', 'cy', 'r' ]
      },
      {
        type: 'ellipse',
        coreProps: [ 'cx', 'cy', 'rx', 'ry' ]
      },
      {
        type: 'g',
        coreProps: []
      },
      {
        type: 'line',
        coreProps: [ 'x1', 'x2', 'y1', 'y2' ]
      },
      {
        type: 'path',
        coreProps: [ 'd' ]
      },
      {
        type: 'polygon',
        coreProps: [ 'points' ]
      },
      {
        type: 'polyline',
        coreProps: [ 'points' ]
      },
      {
        type: 'rect',
        coreProps: [ 'height', 'rx', 'ry', 'width', 'x', 'y' ]
      }
    ]
    const getNodeTypes = () => {
      const types = []
    
      for (let i = 0, l = nodeCoreProps.length; i < l; i++) {
        types.push(nodeCoreProps[ i ].type)
      }
    
      return types
    }
    const nodeTypes = getNodeTypes()
    
    const coreProps = type => {
      for (let i = 0, l = nodeCoreProps.length; i < l; i++) {
        if (nodeCoreProps[ i ].type === type) {
          return nodeCoreProps[ i ].coreProps
        }
      }
    
      return []
    }
    const frameShape = el => {
      if (validNode(el)) {
        const data = nodeData(el)
        const attributes = data.attributes
        const type = data.type
    
        if (type === 'g') {
          const childNodes = data.childNodes
          const childFrameShapes = []
    
          for (let i = 0, l = childNodes.length; i < l; i++) {
            const n = childNodes[ i ]
    
            if (validNodeType(childNodes[ i ].nodeName)) {
              childFrameShapes.push(frameShape(n))
            }
          }
    
          return { attributes, childFrameShapes }
        }
    
        return {
          attributes: removeCoreProps(type, attributes),
          points: toPoints(plainShapeObjectFromAttrs(type, attributes))
        }
      }
    }
    const groupNode = childFrameShapes => {
      const nodes = []
    
      for (let i = 0, l = childFrameShapes.length; i < l; i++) {
        nodes.push(node(childFrameShapes[ i ]))
      }
    
      const group = document.createElementNS('http://www.w3.org/2000/svg', 'g')
    
      for (let i = 0, l = nodes.length; i < l; i++) {
        group.appendChild(nodes[ i ])
      }
    
      return group
    }
    const node = frameShp => {
      if (validFrameShape(frameShp)) {
        const attributes = frameShp.attributes
    
        const el = frameShp.childFrameShapes
          ? groupNode(frameShp.childFrameShapes)
          : pathNode(frameShp.points)
        for (let attr in attributes) {
          el.setAttribute(attr, attributes[ attr ])
        }
        return el
      }
    }
    const nodeData = el => {
      const attributes = {}
    
      if (el.hasAttributes()) {
        const attrs = [ ...el.attributes ]
    
        for (let i = 0, l = attrs.length; i < l; i++) {
          const attr = attrs[ i ]
          const name = attr.name
    
          if (attributeBlacklist.indexOf(name) === -1) {
            attributes[ name ] = attr.value
          }
        }
      }
    
      return { attributes, childNodes: [ ...el.childNodes ], type: el.nodeName }
    }
    const pathNode = points => {
      const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
    
      path.setAttribute('d', toPath(points))
    
      return path
    }
    const plainShapeObject = el => {
      if (validNode(el)) {
        const data = nodeData(el)
        const attributes = data.attributes
        const type = data.type
        if (type === 'g') {
          const childNodes = data.childNodes
          const shapes = []
          for (var i = 0, l = childNodes.length; i < l; i++) {
            const n = childNodes[ i ]
            if (validNodeType(n.nodeName)) {
              shapes.push(plainShapeObject(n))
            }
          }
          return { ...attributes, type, shapes }
        }
        return {
          ...attributes,
          ...plainShapeObjectFromAttrs(type, attributes)
        }
      }
    }
    const plainShapeObjectFromAttrs = (type, attributes) => {
      const props = coreProps(type)
      const result = { type }
      for (let k in attributes) {
        if (props.indexOf(k) !== -1) {
          const v = attributes[ k ]
          const n = Number(v)
          result[ k ] = Number.isNaN(n) ? v : n
        }
      }
      return result
    }
    const removeCoreProps = (type, attributes) => {
      const props = coreProps(type)
      const result = {}
      for (let k in attributes) {
        if (props.indexOf(k) === -1) {
          result[ k ] = attributes[ k ]
        }
      }
      return result
    }
    const updateNode = (el, frameShp, changes = []) => {
      if (__DEV__) {
        if (!validNode(el)) {
          throw new TypeError(`The first argument of the updateNode function must be a valid DOM node`)
        }
        if (!validFrameShape(frameShp)) {
          throw new TypeError(`The second argument of the updateNode function must be a valid frameShape`)
        }
      }
      const shouldApplyChanges = changes.length === 0
      const currentAttributes = el.attributes
      const nextAttributes = frameShp.attributes
      const childFrameShapes = frameShp.childFrameShapes
      const changesKey = changes.push({ el, remove: [], update: {} }) - 1
      for (let k in currentAttributes) {
        if (typeof nextAttributes[ k ] === 'undefined') {
          changes[ changesKey ].remove.push(k)
        }
      }
      for (let k in nextAttributes) {
        const c = currentAttributes[ k ]
        const n = nextAttributes[ k ]
        if (typeof c === 'undefined' || c !== n) {
          changes[ changesKey ].update[ k ] = n
        }
      }
      if (!childFrameShapes) {
        const nextPath = toPath(frameShp.points)
        if (nextPath !== el.getAttribute('d')) {
          changes[ changesKey ].update.d = nextPath
        }
      } else {
        const allChildNodes = [ ...el.childNodes ]
        const childNodes = []
        for (let i = 0, l = allChildNodes.length; i < l; i++) {
          const n = allChildNodes[ i ]
          if (validNodeType(n.nodeName)) {
            childNodes.push(n)
          }
        }
        for (let i = 0, l = childFrameShapes.length; i < l; i++) {
          updateNode(childNodes[ i ], childFrameShapes[ i ], changes)
        }
      }
      if (shouldApplyChanges) {
        for (let i = 0, l = changes.length; i < l; i++) {
          const change = changes[ i ]
          const _el = change.el
          const remove = change.remove
          const update = change.update
          for (let _i = 0, _l = remove.length; _i < _l; _i++) {
            _el.removeAttribute(remove[ _i ])
          }
          for (let k in update) {
            _el.setAttribute(k, update[ k ])
          }
        }
      }
      return el
    }
    if (typeof attributes === 'undefined') {
          throw new TypeError(`frameShape must include an attributes property`)
        }
        if (typeof attributes !== 'object' || Array.isArray(attributes)) {
          throw new TypeError(`frameShape attributes property must be of type object`)
        }
        if (typeof childFrameShapes === 'undefined' && typeof points === 'undefined') {
          throw new TypeError(`frameShape must have either a points or childFrameShapes property`)
        }
        if (points && (!Array.isArray(points))) {
          throw new TypeError(`frameShape points property must be of type array`)
        }
        if (childFrameShapes) {
          if (!Array.isArray(childFrameShapes)) {
            throw new TypeError(`frameShape childFrameShapes property must be of type array`)
          }
          for (let i = 0, l = childFrameShapes.length; i < l; i++) {
            const childFrameShape = childFrameShapes[ i ]
            if (typeof childFrameShape !== 'object' || typeof childFrameShape.attributes !== 'object') {
              throw new TypeError(`frameShape childFrameShapes property must be array of frameShapes`)
            }
          }
        }
      }
      return true
    }
    const validNode = el => {
      if (__DEV__) {
        if (typeof el !== 'object' || !el.nodeName) {
          throw new TypeError(`el must be a DOM node`)
        }
    
        if (!validNodeType(el.nodeName)) {
          throw new TypeError(`el must be an SVG basic shape or group element`)
        }
      }
    
      return true
    }
    const validNodeType = nodeName => nodeTypes.indexOf(nodeName) !== -1
    export { frameShape, node, plainShapeObject, updateNode }

    Но в обеих случаях используется import { toPoints } from 'svg-points'.
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Вы имеете в веду эту библиотеку point
    Единственное что я нашел это в файле decurve
    /* globals test expect */
    import decurve from '../src/decurve'
    import { toPoints } from 'svg-points'
    
    test('`decurve` should not exceed call stack maximum when a curve is drawn to/from same location', () => {
      const d = 'M3337.1,5965.8c-26.4-9.2-64.5-15.1-87,4.6c3.7,0.8,7.5,1.9,11.1,3.3c2.9,1.1,4.7,4.3,4.4,8.2c-0.3,5-3.6,8.4-7.8,7.6c-3.3-0.6-6.4-1.9-9.7-2.4c-4.6-0.6-9.9,3.1-11.8,7.7c-2.1,5.3-0.5,12.5,3.8,16c3.5,2.8,7.8,3.4,11.8,1.8c3-1.2,6.2-2.9,8.3-5.2c3.9-4.3,7.9-5.5,13.3-3.1c5.2,2.4,9.4,0.3,13.8-2.9c7.6-5.5,9-5,10.7,4.5c1.5,8.3,3.9,16.2,7.7,23.7c0.6,1.1,2.6,1.6,4,2c0.4,0.1,1.6-0.9,1.7-1.6c1.6-10.7,2.9-21.4-0.7-32.1c-2.1-6.3-4-12.7-5.6-19.1c-0.3-1.1,1.2-2.7,2.1-3.8c0.4-0.5,1.7-0.6,2.4-0.3c3.8,1.6,7.7,3.3,11.3,5.3c4.1,2.3,4.4,6,1.3,10.3c-4.1,5.7-4.1,5.7,1.7,11.8l-0.1-0.1c-2.5,5.4-4.2,10.7-3.4,16.9c1.3,9.9,1.9,19.9,3.1,29.8c0.4,3.2,1.6,6.4,3.1,9.3c0.5,1,2.9,1.8,4.2,1.6c1.3-0.2,3.1-1.8,3.3-2.9c0.6-5,0.7-10,0.7-15c0-5.3,1.5-9.7,5.9-13c2.6-2,5-4.4,7.3-6.8c2.7-2.9,3.4-8.2,0.7-11.6c-4.7-6.2-7.8-12.8-7.3-20.7c0.1-0.8,0.5-2,1-2.2c1.5-0.4,3.8-1.1,4.5-0.4c7,7.1,13.8,14.4,20.3,21.9c2.1,2.4,3.7,5.4,4.8,8.4C3379.6,5993.2,3357.7,5972,3337.1,5965.8zM3258.8,6027.3c1-2.2,1.4-5.7,3.1-6.4c7.4-3.2,14.5-7.4,22.7-8.4c2.7-0.3,6.4,4.1,5.6,6.7c-2.3,7.4-7.7,11.4-14.5,10.6C3270,6029.1,3264.4,6028.1,3258.8,6027.3C3258.7,6027.2,3258.8,6027.3,3258.8,6027.3zM3349.6,6039.3c0.1,2.8-1,4.6-3.4,5.5c-3.1,1.2-6.6-1.3-6.2-4.6c0.3-2.7,2.1-4.1,4.6-4.5C3347,6035.4,3349.3,6037.2,3349.6,6039.3z'
      const shape = toPoints({ type: 'path', d })
      decurve(shape)
    })
    
    test('`decurve` should return same shape when shape has no curves', () => {
      const shape = [
        { x: 525.667, y: 321.333, moveTo: true },
        { x: 462.8335, y: 321.333 },
        { x: 400, y: 321.333 },
        { x: 274.333, y: 321.333 },
        { x: 274.333, y: 200 },
        { x: 274.333, y: 78.667 },
        { x: 399.9995, y: 78.667 },
        { x: 525.666, y: 78.667 },
        { x: 525.666, y: 200 },
        { x: 525.666, y: 321.333 },
        { x: 525.6665, y: 321.333 },
        { x: 525.667, y: 321.333 }
      ]
      expect(decurve(shape, 1)).toEqual(shape)
    })

    Или здесь dom
    index.js
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Нужно в браузере. просто решил попробовать сделать для начала хотя бы как вы писали в инструкций в комментарий 19 февраля. И я в предыдущем ответе написал что из этого у меня получилось.
    Если есть возможность выполнить код в браузере без установки npm и node.js
    То как мне это сделать?
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, у меня почему-то выводит ошибку

    C:\Users\use33>npm install svg-points
    npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\use33\package.json'
    npm notice created a lockfile as package-lock.json. You should commit this file.
    npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\use33\package.json'
    npm WARN use33 No description
    npm WARN use33 No repository field.
    npm WARN use33 No README data
    npm WARN use33 No license field.

    + svg-points@6.0.1
    added 1 package from 1 contributor and audited 1 package in 2.992s
    found 0 vulnerabilities


    import { toPoints } from 'svg-points';
    
    const data = {
      type: 'path',
      d: 'M20,20h50v20A2,2,0,0,1,80,35L90,30H50V50a5,5,45,1,0-5-10l-5-10Z'
    }
     
    const points = toPoints(data)
    
    console.log(points)



    C:\Users\use33>node "C:\Users\use33\Desktop\test\test.js"
    (node:23488) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
    C:\Users\use33\Desktop\test\test.js:1
    import { toPoints } from 'svg-points';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1067:16)
    at Module._compile (internal/modules/cjs/loader.js:1115:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
    at Module.load (internal/modules/cjs/loader.js:1000:32)
    at Function.Module._load (internal/modules/cjs/loader.js:899:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, А пользователь у которого не установлен node.js сможет запустить этот код?
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Я не совсем понял. Что именно вы имеет веду? То что я могу установить node.js и через него запустить код в браузере, но тогда пользователь у которого нет node.js не сможет его запустить. или то что я могу скопировать функций из node.js вставить их в мой js код и запустить их в браузере?
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Просто я планировал использовать этот код внутри браузера. а nodejs работает локально. Я могу что нибудь сделать что бы запустить код внутри браузера?
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Я слабо знаком с Node.js но похоже что она устанавливается отдельно на windows и работает внутри консоли. Могу ли я как то исполнить этот код внутри codepen?
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Я впервые вижу такой странный синтаксис
    npm install svg-points
    import { toPoints } from 'svg-points'
    const circle = {
      type: 'circle',
      cx: 50,
      cy: 50,
      r: 20
    }
     
    const points = toPoints(circle)
     
    console.log(points)

    Особенно первые две строки которые вызывают SyntaxError
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Да только я так и не понял часть с getPathDataTests
    getPathDataTests.forEach(function(test) {
            path.setAttribute("d", test.input);
            var pathData = path.getPathData();
    
            if (comparePathData(pathData, test.output)) {
              console.log('%c[PASSED]', 'color: white; background: green;', test.input + ' => ', test.output);
            }
            else {
              console.log('%c[FAILED]', 'color: white; background: red;', test.input + ' => ', test.output);
            }
          });

    Ведь код только проверяет что-то в comparePathData и возвращает тот же массив который был передан во внутрь функции. а результата перевода из path в массив он не показывает. в отличии от setPathDataTests где код проверяет совпадение двух строк.
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Просто я не совсем понимаю как с этим работать.
    <script src="https://raw.githubusercontent.com/jarek-foksa/path-data-polyfill/master/path-data-polyfill.js"></script>

    var path = 'M366.5,74.5c1.19,58.5-.19,314.24-.19,314.24V678.5H987V74H670.89Z';
    let logPathSegments = (path) => {
      for (let seg of path.getPathData()) {
        if (seg.type === "M") {
          let [x, y] = seg.values;
          console.log(`M ${x} ${y}`);
        }
        else if (seg.type === "L") {
          let [x, y] = seg.values;
          console.log(`L ${x} ${y}`);
        }
        else if (seg.type === "C") {
          let [x1, y1, x2, y2, x, y] = seg.values;
          console.log(`C ${x1} ${y1} ${x2}, ${y2}, ${x} ${y}`);
        }  
      }
    };

    <script src="https://raw.githubusercontent.com/adobe-webplatform/Snap.svg/master/demos/animated-game/js/snap.svg.js"></script>

    var myPath = s.path("M 18,0 4.5,9 13.5,9 9,18 0,36 18,36 36,0 z");
    var numberOfItems = myPath.node.pathSegList.numberOfItems; // handy for loops
    var firstCoordinate = myPath.node.pathSegList.getItem(0);
    console.log firstCoordinate.x;
    console.log firstCoordinate.y;
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    А есть какие нибудь примеры использования для решения вопроса? а то я не очень хорошо понимаю ваш ответ.
  • Как превратить svg файл в массив координат и обратно?

    @zeni1agent Автор вопроса
    Kovalsky, Я пытался разобраться с snapsvg. но не нашел того что мне нужно.
  • Как создать настоящий морф svg файла с помощью javascript?

    @zeni1agent Автор вопроса
    RAX7, Я уже создал то что мне нужно

    НО оно работает только с polygon и мне приходится прописывать координаты вручную
    А мне нужно загружать svg фалы из illustrator и из них делать морфы.
  • Как создать настоящий морф svg файла с помощью javascript?

    @zeni1agent Автор вопроса
    Kovalsky, Такое ворожение обычно используется в 3d графике. Обозначает заранее просчитанную физику(анимацию) без возможности ее редактировать. только перезаписать с начала и до конца.
    Возможно я его употребляю не совсем корректно.
    Но суть думаю одна и та же
  • Как создать настоящий морф svg файла с помощью javascript?

    @zeni1agent Автор вопроса
    Kovalsky, А где это найти? потому что я не могу вообще в гугле что либо найти по этой теме. Единственное что я нашел связное с morph. Это запеченные анимации которые действуют либо по нажатию клика либо используя ползунок который контролирует саму анимацию. И смешивать два разных morph невозможно. при попытке он просто резко переключается с одной анимации на другую.
  • Как создать настоящий морф svg файла с помощью javascript?

    @zeni1agent Автор вопроса
    Kovalsky, А чем он отличается от gsap, polymorph? Мне нужен morph а не запеченная в ползунок анимация.