问:
How to add .a libraries on flutter plugin via podspec
I am trying to include .a files on the iOS side of the plugin. Below is my file structure.

Now when I try to add .a files via vendored_libraries on podspec, pod install is successfully completed. And when I compile the code, I get Library Not Found  -lAccuraFace

I tried to add the .a file on the Link Binary With Libraries section on the build phase on the Pod target. It's still the same, how can I define the podspec in such a way that the .a file is included and linked automatically.

Here is my podspec file for the plugin

```<code>Pod::Spec.new do |s|
  s.name             = 'accuraemirates'
  s.version          = '0.0.1'
  s.summary          = 'A new Flutter plugin.'
  s.description      = <<-DESC
A new Flutter plugin.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.dependency 'Flutter'
  s.public_header_files = 'Classes/*{.h}'
  s.private_header_files = 'Classes/CodeScan/**/*{.h,.cpp,.a}'
  s.platform = :ios, '8.0'
  s.preserve_paths = 'opencv2.framework'
  s.xcconfig = {
    'OTHER_LDFLAGS' => '-framework opencv2 -lAccuraFace',
  }
  s.ios.vendored_frameworks = 'opencv2.framework', "CoreVideo.framework", "Foundation.framework", "CoreGrpahics.framework",
  "Accelerate.framework", "CoreMedia.framework", "CoreImage.framework", "QuartzCore.framework", "AudioToolbox.framework", "CoreData.framework", "SystemConfiguration.framework"
  s.ios.vendored_libraries = 'Classes/Framework/*{.a}', "libz.1.dylib", "c++", "stdc++"

  # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
  s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
  s.swift_version = '5.0'
end
</code>```

Here is the root podfile

```<code>ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def parse_KV_file(file, separator='=')
  file_abs_path = File.expand_path(file)
  if !File.exists? file_abs_path
    return [];
  end
  generated_key_values = {}
  skip_line_start_symbols = ["#", "/"]
  File.foreach(file_abs_path) do |line|
    next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
    plugin = line.split(pattern=separator)
    if plugin.length == 2
      podname = plugin[0].strip()
      path = plugin[1].strip()
      podpath = File.expand_path("#{path}", file_abs_path)
      generated_key_values[podname] = podpath
    else
      puts "Invalid plugin specification: #{line}"
    end
  end
  generated_key_values
end

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  # Flutter Pod

  copied_flutter_dir = File.join(__dir__, 'Flutter')
  copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework')
  copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec')
  unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path)
    # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet.
    # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration.
    # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist.

    generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig')
    unless File.exist?(generated_xcode_build_settings_path)
      raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first"
    end
    generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path)
    cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR'];

    unless File.exist?(copied_framework_path)
      FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir)
    end
    unless File.exist?(copied_podspec_path)
      FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir)
    end
  end

  # Keep pod path relative so it can be checked into Podfile.lock.
  pod 'Flutter', :path => 'Flutter'

  # Plugin Pods

  # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
  # referring to absolute paths on developers' machines.
  system('rm -rf .symlinks')
  system('mkdir -p .symlinks/plugins')
  plugin_pods = parse_KV_file('../.flutter-plugins')
  plugin_pods.each do |name, path|
    symlink = File.join('.symlinks', 'plugins', name)
    File.symlink(path, symlink)
    pod name, :path => File.join(symlink, 'ios')
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end
</code>```

Is it not possible to add/link .a libraries from podspec file on a flutter plugin.

答:
Finally found the issue..

```<code>Pod::Spec.new do |s|
  # other obvious values
  s.source_files = 'Classes//*{.h,.a,.swift,.mm,.m,.hpp}'
  s.resources = 'Resources//'
  s.static_framework = true
  s.public_header_files = "Classes/VideoCamera/VideoCameraWrapperDelegate.h", "Classes/VideoCamera/VideoCameraWrapper.h",'Classes/.h',
  s.private_header_files = 'Classes/CodeScan//{.h,.cpp,.hpp}'
  s.platform = :ios, '8.0'
  s.preserve_paths = 'opencv2.framework', 'Classes/Framework/.a'

  s.xcconfig = {
     # here on LDFLAG, I had to set -l and then the library name (without lib prefix although the file name has it).
    'OTHER_LDFLAGS' => '-framework opencv2 -lc++ -lAccuraFace -lAccuraEmirate -lDocRecog -lz',
    'USER_HEADER_SEARCH_PATHS' => '"${PROJECT_DIR}/.."/',
    "LIBRARY_SEARCH_PATHS" => '"${PROJECT_DIR}/.."/*',
  }
  s.vendored_frameworks = 'opencv2.framework' # Various framworks you need
  # Here the name of the library can include lib as the file name has it too.
  s.vendored_libraries = 'AccuraFace','libAccuraEmirate','libDocRecog'
end
</code>```

Notice two values here OTHER_LDFLAGS and vendored_libraries. Although I have same file, they need names with and without lib prefix. Weird but worked.

Body:
I am trying to include .a files on the iOS side of the plugin. Below is my file structure.

Now when I try to add .a files via vendored_libraries on podspec, pod install is successfully completed. And when I compile the code, I get Library Not Found  -lAccuraFace

I tried to add the .a file on the Link Binary With Libraries section on the build phase on the Pod target. It's still the same, how can I define the podspec in such a way that the .a file is included and linked automatically.

Here is my podspec file for the plugin

Pod::Spec.new do |s|
  s.name             = 'accuraemirates'
  s.version          = '0.0.1'
  s.summary          = 'A new Flutter plugin.'
  s.description      = <<-DESC
A new Flutter plugin.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.dependency 'Flutter'
  s.public_header_files = 'Classes/*{.h}'
  s.private_header_files = 'Classes/CodeScan/**/*{.h,.cpp,.a}'
  s.platform = :ios, '8.0'
  s.preserve_paths = 'opencv2.framework'
  s.xcconfig = {
    'OTHER_LDFLAGS' => '-framework opencv2 -lAccuraFace',
  }
  s.ios.vendored_frameworks = 'opencv2.framework', "CoreVideo.framework", "Foundation.framework", "CoreGrpahics.framework",
  "Accelerate.framework", "CoreMedia.framework", "CoreImage.framework", "QuartzCore.framework", "AudioToolbox.framework", "CoreData.framework", "SystemConfiguration.framework"
  s.ios.vendored_libraries = 'Classes/Framework/*{.a}', "libz.1.dylib", "c++", "stdc++"

  # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
  s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
  s.swift_version = '5.0'
end

Here is the root podfile

ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def parse_KV_file(file, separator='=')
  file_abs_path = File.expand_path(file)
  if !File.exists? file_abs_path
    return [];
  end
  generated_key_values = {}
  skip_line_start_symbols = ["#", "/"]
  File.foreach(file_abs_path) do |line|
    next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
    plugin = line.split(pattern=separator)
    if plugin.length == 2
      podname = plugin[0].strip()
      path = plugin[1].strip()
      podpath = File.expand_path("#{path}", file_abs_path)
      generated_key_values[podname] = podpath
    else
      puts "Invalid plugin specification: #{line}"
    end
  end
  generated_key_values
end

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  # Flutter Pod

  copied_flutter_dir = File.join(__dir__, 'Flutter')
  copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework')
  copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec')
  unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path)
    # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet.
    # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration.
    # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist.

    generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig')
    unless File.exist?(generated_xcode_build_settings_path)
      raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first"
    end
    generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path)
    cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR'];

    unless File.exist?(copied_framework_path)
      FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir)
    end
    unless File.exist?(copied_podspec_path)
      FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir)
    end
  end

  # Keep pod path relative so it can be checked into Podfile.lock.
  pod 'Flutter', :path => 'Flutter'

  # Plugin Pods

  # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
  # referring to absolute paths on developers' machines.
  system('rm -rf .symlinks')
  system('mkdir -p .symlinks/plugins')
  plugin_pods = parse_KV_file('../.flutter-plugins')
  plugin_pods.each do |name, path|
    symlink = File.join('.symlinks', 'plugins', name)
    File.symlink(path, symlink)
    pod name, :path => File.join(symlink, 'ios')
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

Is it not possible to add/link .a libraries from podspec file on a flutter plugin.

Body:
Finally found the issue..

Pod::Spec.new do |s|
  # other obvious values
  s.source_files = 'Classes//*{.h,.a,.swift,.mm,.m,.hpp}'
  s.resources = 'Resources//'
  s.static_framework = true
  s.public_header_files = "Classes/VideoCamera/VideoCameraWrapperDelegate.h", "Classes/VideoCamera/VideoCameraWrapper.h",'Classes/.h',
  s.private_header_files = 'Classes/CodeScan//{.h,.cpp,.hpp}'
  s.platform = :ios, '8.0'
  s.preserve_paths = 'opencv2.framework', 'Classes/Framework/.a'

  s.xcconfig = {
     # here on LDFLAG, I had to set -l and then the library name (without lib prefix although the file name has it).
    'OTHER_LDFLAGS' => '-framework opencv2 -lc++ -lAccuraFace -lAccuraEmirate -lDocRecog -lz',
    'USER_HEADER_SEARCH_PATHS' => '"${PROJECT_DIR}/.."/',
    "LIBRARY_SEARCH_PATHS" => '"${PROJECT_DIR}/.."/*',
  }
  s.vendored_frameworks = 'opencv2.framework' # Various framworks you need
  # Here the name of the library can include lib as the file name has it too.
  s.vendored_libraries = 'AccuraFace','libAccuraEmirate','libDocRecog'
end

Notice two values here OTHER_LDFLAGS and vendored_libraries. Although I have same file, they need names with and without lib prefix. Weird but worked.


来源: stackexchange

问:
Selenium NoSuchElementException when the element does exist
I am working on a discord bot that uses selenium to grab a zoom link off of an instagram account. It has been working perfectly until just today when it started giving the error selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]"}. I have no idea why this is. I have checked that the Xpath is correct and added a sleep function to allow it time to load. So far the only thing that has worked has been changing the browser that it uses from Chrome to Firefox, however this was done on my local machine and can't be done in the actual code because I have it deployed to heroku with a headless chrome browser running and I don't want to go through the trouble of trying to get Firefox to work since it took me over an hour to get chrome working.

Here is the relevant code:

```<code>@client.command()
async def zoom(ctx):
    await ctx.send("Retrieving current zoom link from instagram...\nPlease wait...")
    chrome_options = webdriver.ChromeOptions()
    chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("--no-sandbox")
    driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)
    url = "https://instagram.com/profile/"
    driver.get(url)    # load instagram page
    time.sleep(5)
    link = driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]').get_attribute("innerHTML")  # Get zoom link

    await ctx.send("Here is the current zoom link:\nhttps://" + link)

    driver.quit()
</code>```

Here is the whole error traceback:

```<code>2020-06-02T03:45:55.540096+00:00 app[worker.1]: Traceback (most recent call last):
2020-06-02T03:45:55.540174+00:00 app[worker.1]: File "main.py", line 48, in zoom
2020-06-02T03:45:55.540177+00:00 app[worker.1]: link = driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]').get_attribute("innerHTML")  # Get zoom link
2020-06-02T03:45:55.540204+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
2020-06-02T03:45:55.540206+00:00 app[worker.1]: return self.find_element(by=By.XPATH, value=xpath)
2020-06-02T03:45:55.540264+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
2020-06-02T03:45:55.540265+00:00 app[worker.1]: 'value': value})['value']
2020-06-02T03:45:55.540305+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
2020-06-02T03:45:55.540305+00:00 app[worker.1]: self.error_handler.check_response(response)
2020-06-02T03:45:55.540306+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
2020-06-02T03:45:55.540306+00:00 app[worker.1]: raise exception_class(message, screen, stacktrace)
2020-06-02T03:45:55.540375+00:00 app[worker.1]: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]"}
2020-06-02T03:45:55.540377+00:00 app[worker.1]: (Session info: headless chrome=83.0.4103.61)
</code>```

Any help is greatly appreciated, I really need to get this bot back up and running again.
Thanks in advance!

答:
You have not used the escaped characters in the double quotation in the id;

try;

```<code>//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a[1]
</code>```

instead of;

```<code>//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a discord bot that uses selenium to grab a zoom link off of an instagram account. It has been working perfectly until just today when it started giving the error selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]"}. I have no idea why this is. I have checked that the Xpath is correct and added a sleep function to allow it time to load. So far the only thing that has worked has been changing the browser that it uses from Chrome to Firefox, however this was done on my local machine and can't be done in the actual code because I have it deployed to heroku with a headless chrome browser running and I don't want to go through the trouble of trying to get Firefox to work since it took me over an hour to get chrome working.

Here is the relevant code:

@client.command()
async def zoom(ctx):
    await ctx.send("Retrieving current zoom link from instagram...\nPlease wait...")
    chrome_options = webdriver.ChromeOptions()
    chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("--no-sandbox")
    driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)
    url = "https://instagram.com/profile/"
    driver.get(url)    # load instagram page
    time.sleep(5)
    link = driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]').get_attribute("innerHTML")  # Get zoom link

    await ctx.send("Here is the current zoom link:\nhttps://" + link)

    driver.quit()

Here is the whole error traceback:

2020-06-02T03:45:55.540096+00:00 app[worker.1]: Traceback (most recent call last):
2020-06-02T03:45:55.540174+00:00 app[worker.1]: File "main.py", line 48, in zoom
2020-06-02T03:45:55.540177+00:00 app[worker.1]: link = driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]').get_attribute("innerHTML")  # Get zoom link
2020-06-02T03:45:55.540204+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
2020-06-02T03:45:55.540206+00:00 app[worker.1]: return self.find_element(by=By.XPATH, value=xpath)
2020-06-02T03:45:55.540264+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
2020-06-02T03:45:55.540265+00:00 app[worker.1]: 'value': value})['value']
2020-06-02T03:45:55.540305+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
2020-06-02T03:45:55.540305+00:00 app[worker.1]: self.error_handler.check_response(response)
2020-06-02T03:45:55.540306+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
2020-06-02T03:45:55.540306+00:00 app[worker.1]: raise exception_class(message, screen, stacktrace)
2020-06-02T03:45:55.540375+00:00 app[worker.1]: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]"}
2020-06-02T03:45:55.540377+00:00 app[worker.1]: (Session info: headless chrome=83.0.4103.61)

Any help is greatly appreciated, I really need to get this bot back up and running again.
Thanks in advance!

Body:
You have not used the escaped characters in the double quotation in the id;

try;

//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a[1]

instead of;

//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]


问:
Use variable as entity table name
Is there a way to dynmaically define the table name so I do not have to do multiple calls if the table I'm accessing is different for different conditions? I don't want to have an if/else for every table I am accessing if I can use a variable name instead.</p>

```<code>using (Entity ctx = new Entity())
{
    dbTableVal = "EntityTables";
    var query = from d in dbTableVal
                where d == "Yes"
                select d;
}
</code>```

答: I guess no, because the table itself also defines the type of returned IQueryable<T>. It is even not possible with ESQL (which has string syntax) to define generic query where you don't know the type of result set.

ContentLicense: CC BY-SA 3.0

Title: Use variable as entity table name

Body:
Is there a way to dynmaically define the table name so I do not have to do multiple calls if the table I'm accessing is different for different conditions? I don't want to have an if/else for every table I am accessing if I can use a variable name instead.

using (Entity ctx = new Entity())
{
    dbTableVal = "EntityTables";
    var query = from d in dbTableVal
                where d == "Yes"
                select d;
}


问:
Converting Postman Request to RabbitMQ
I have a POST request that I use in Postman to change the state of a device and when I do the request directly through Postman it seems to work but I haven't been able to make it work with RabbitMQ.

This is my postman:

```<code>http://fakesite:123/api/exchanges/%2F/SOCKET_PROXY_EXCHANGE/publish

{
    "vhost": "/",
    "name": "SOCKET_PROXY_EXCHANGE",
    "properties": {
        "delivery_mode": 1,
        "headers": {}
    },
    "routing_key":"fakeid.test",
    "delivery_mode": "1",
    "payload": "{\"id\":\"fakeid\",\"status\":\"ON\"}",
    "headers": {},
    "props": {},
    "payload_encoding": "string"
}
</code>```

And this is my RabbitMQ Request

```<code>        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(fakesite);
        factory.setUsername(fakeusr);
        factory.setPassword(fakepass);
        factory.setVirtualHost("/");
        factory.setPort(123);

        String routingKey = "fakeid.test";
        String testQ = "testQ" + routingKey;
        String payload = "{\"id\":\"fakeid\",\"status\":\"ON\"}";

        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            HashMap<String, Object> customProperties = new HashMap<>();
            customProperties.put("content_type", "text/plain");
            channel.queueDeclare(testQ, false, false, false, null);
            channel.basicPublish("SOCKET_PROXY_EXCHANGE", testQ, null, payload.getBytes());
            channel.queueDelete(testQ);
            channel.close();
            connection.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

Any ideas on why is not working, I am really new to RabbitMQ and I cannot see were I made a mistake.

答:
Your Routing Key variable is routingKey= fakeid.test and queue variable will be testQ= testQfakeid.test

A method syntax,

```<code> void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
</code>```

And You are using

```<code> channel.basicPublish("SOCKET_PROXY_EXCHANGE", testQ, null, payload.getBytes());
</code>```

It should be

```<code> channel.basicPublish("SOCKET_PROXY_EXCHANGE", routingKey, null, payload.getBytes());
</code>```

a routing key, not a queue.

When we publish we just need routing key and exchange name, based on what we bind with that exchange it will route to that queue based on Exchange Type

RabbitMQ Queue, Exchange, and bind between them can be done by using Rabbitmq management console  or code through.

How to create queue, exchange and bind them through code,

```<code>            String exchangeName= "SOCKET_PROXY_EXCHANGE";

            channel.queueDeclare(testQ, false, false, false, null);
            channel.exchangeDeclare(exchangeName, "direct", true);
            channel.queueBind(testQ, exchangeName, routingKey);
            channel.basicPublish(exchangeName, routingKey, null, payload.getBytes());
          //  channel.queueDelete(testQ);
            channel.close();
</code>```

You can refer RabbitMQ Exchange, Queue, and binding between them, Exchange type from their documents.

Title: Converting Postman Request to RabbitMQ

Body:
I have a POST request that I use in Postman to change the state of a device and when I do the request directly through Postman it seems to work but I haven't been able to make it work with RabbitMQ.

This is my postman:

http://fakesite:123/api/exchanges/%2F/SOCKET_PROXY_EXCHANGE/publish

{
    "vhost": "/",
    "name": "SOCKET_PROXY_EXCHANGE",
    "properties": {
        "delivery_mode": 1,
        "headers": {}
    },
    "routing_key":"fakeid.test",
    "delivery_mode": "1",
    "payload": "{\"id\":\"fakeid\",\"status\":\"ON\"}",
    "headers": {},
    "props": {},
    "payload_encoding": "string"
}

And this is my RabbitMQ Request

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(fakesite);
        factory.setUsername(fakeusr);
        factory.setPassword(fakepass);
        factory.setVirtualHost("/");
        factory.setPort(123);

        String routingKey = "fakeid.test";
        String testQ = "testQ" + routingKey;
        String payload = "{\"id\":\"fakeid\",\"status\":\"ON\"}";

        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            HashMap<String, Object> customProperties = new HashMap<>();
            customProperties.put("content_type", "text/plain");
            channel.queueDeclare(testQ, false, false, false, null);
            channel.basicPublish("SOCKET_PROXY_EXCHANGE", testQ, null, payload.getBytes());
            channel.queueDelete(testQ);
            channel.close();
            connection.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Any ideas on why is not working, I am really new to RabbitMQ and I cannot see were I made a mistake.

Body:
Your Routing Key variable is routingKey= fakeid.test and queue variable will be testQ= testQfakeid.test

A method syntax,

 void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)

And You are using

 channel.basicPublish("SOCKET_PROXY_EXCHANGE", testQ, null, payload.getBytes());

It should be

 channel.basicPublish("SOCKET_PROXY_EXCHANGE", routingKey, null, payload.getBytes());

a routing key, not a queue.

When we publish we just need routing key and exchange name, based on what we bind with that exchange it will route to that queue based on Exchange Type

RabbitMQ Queue, Exchange, and bind between them can be done by using Rabbitmq management console  or code through.

How to create queue, exchange and bind them through code,

            String exchangeName= "SOCKET_PROXY_EXCHANGE";

            channel.queueDeclare(testQ, false, false, false, null);
            channel.exchangeDeclare(exchangeName, "direct", true);
            channel.queueBind(testQ, exchangeName, routingKey);
            channel.basicPublish(exchangeName, routingKey, null, payload.getBytes());
          //  channel.queueDelete(testQ);
            channel.close();

You can refer RabbitMQ Exchange, Queue, and binding between them, Exchange type from their documents.


问:
How to retrive/display column names and its data based on dynamic query in spring data jpa?
How to retrieve/display column names and its data based on dynamic query in spring data jpa?

Example dynamic query be like
Select empid, empname, address from emp (or)
Select productiD, pname, price, pquantity from Product

I don't want to map entity just need to display data?

答:
For a completely dynamic query Spring Data JPA doesn't offer any special support, so in order to integrate it into your repository you'll need to define a custom method.

Since you only want a Map anyway the easiest way might be to use a SQL query, execute it with a JdbcTemplate and have a simple ResultSetExtractor that inserts the values from the ResultSet into a Map.

If you want to utilise the mapping information of JPA you might construct a query using the Criteria API where you explicitly specify all the columns you want and specify Tuple as target type.


问:
How to check if a image has any text or not?
I'm looking for a simple solution that would return a boolean if ANY kind of English text is present in an image file. I wish to use this to detect memes. For example, the following file should be detected as an image with text.

I've come across elaborate machine learning techniques using OpenCV but I haven't been able to fully implement it. Is there any quicker, simpler, and just as effective solution for this?

I look forward to your valuable feedback!

答:
We can use pytesseract python package for get text form the images. You can easily install like pip install pytesseract

Here is the example code:

```<code>import cv2
import pytesseract
image = cv2.imread('test.jpeg')
text = pytesseract.image_to_string(image)
print(text)
</code>```

Here is my sample image

So, the output should be like

```<code>IS BITCOIN
GOING TO
$20.000
BY CHRISTMAS?
</code>```

Body:
We can use pytesseract python package for get text form the images. You can easily install like pip install pytesseract

Here is the example code:

import cv2
import pytesseract
image = cv2.imread('test.jpeg')
text = pytesseract.image_to_string(image)
print(text)

Here is my sample image

So, the output should be like

IS BITCOIN
GOING TO
$20.000
BY CHRISTMAS?


问:
Should child class override the constructors if they have identical parameter as the parent class?
I am using VC++.

I define a parent class:

```<code>class A
{
   A();
   A(int a);

   virtual ~A();

   virtual void DoSomething();
}
</code>```

Then define a child class:

```<code>class B: public A
{
   virtual void DoSomething();
}
</code>```

In class B, only a new version of DoSomething is introduced. All other functions, including the constructors and destructor are same as A.

For example, both the following constructor are OK for B:

```<code>B MyB;
B MyB(1);
</code>```

In such a case, need I create the constructors B() and B(int a)?

I try to obmit the constructors & destructor in B(), hoping it can inherit from A, but the compiler will report error for:

```<code>B MyB(1);
</code>```

答:
The default constructor B::B() would be implicitly-defined, while B::B(int) won't. You can define one explicitly, or apply using for inheriting constructor (since C++11).

If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.

```<code>class B : public A
{
   using A::A;
   virtual void DoSomething();
}
</code>```

Body:
I am using VC++.

I define a parent class:

class A
{
   A();
   A(int a);

   virtual ~A();

   virtual void DoSomething();
}

Then define a child class:

class B: public A
{
   virtual void DoSomething();
}

In class B, only a new version of DoSomething is introduced. All other functions, including the constructors and destructor are same as A.

For example, both the following constructor are OK for B:

B MyB;
B MyB(1);

In such a case, need I create the constructors B() and B(int a)?

I try to obmit the constructors & destructor in B(), hoping it can inherit from A, but the compiler will report error for:

B MyB(1);

Body:
The default constructor B::B() would be implicitly-defined, while B::B(int) won't. You can define one explicitly, or apply using for inheriting constructor (since C++11).

If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.

class B : public A
{
   using A::A;
   virtual void DoSomething();
}


问:
Why String.toDouble() will increase decimal places?
I have a server returning a value (in JSON) which contains a number with decimal places, e.g. 203.14.

Since in my app I need to do some calculation, I have to convert it to Double.

However when it is converted to Double, it's value becomes 203.13999938964844.

For some business logic reason, when I display this value, I need to round down this number to 2 decimal places.

So now it becomes 203.13, which is 0.01 smaller than the value server returns.

How can I preserve 203.14 when I convert "203.14" to Double?

Update:

I just found that the reason is because the model class used float to accept the server value, but then later converted to Double. If day one the model class uses double to accept the value, then the problem above will not exist.

答:
Try using this rounding method after initializing the Double:

```<code>fun Double.round(decimals: Int): Double {
    var multiplier = 1.0
    repeat(decimals) { multiplier *= 10 }
    return round(this * multiplier) / multiplier
}
</code>```

You can use it like this:

```<code>3.14159265359.round(2)
</code>```

Body:
Try using this rounding method after initializing the Double:

fun Double.round(decimals: Int): Double {
    var multiplier = 1.0
    repeat(decimals) { multiplier *= 10 }
    return round(this * multiplier) / multiplier
}

You can use it like this:

3.14159265359.round(2)


问:
How to use MotionLayout like TransitionManager?
Tutoiral I see with MotionLayout have things in common and that is it focused on either an onClick or onSwipe to trigger MotionLayout Transition. I was wondering how to Transition from something like State A to State B with other trigger like instead of onClick it would trigger onNavDestinationChanged something like:

```<code>navController.addNavigationChangeListener { motionLayout.transtionToAnotherState() }
</code>```

Something similar to TransitionManager where if I want to go from Scene A to Scene B I just do:

```<code>TransitionManager.beginDelayedTransition(rootLayout)
// Do someLayout changes
</code>```

1) Is something similar doable with MotionLayout?
2) If yes can anyone guide me?

Thank you very much.

答:
There is no 100% same way to do it, but you can get similar result if you know your original and final states.

```<code>setTransition(R.id.stateA, R.id.stateB);
setTransitionDuration(durationMs); // optional
transitionToEnd(); // here may be transitionToStart to goto state A from B
</code>```

If you don't know your current state you can read it from TransitionView itself:

```<code>getCurrentState();
</code>```

but be aware, if you are in the middle of transition it will return -1

Body:
Tutoiral I see with MotionLayout have things in common and that is it focused on either an onClick or onSwipe to trigger MotionLayout Transition. I was wondering how to Transition from something like State A to State B with other trigger like instead of onClick it would trigger onNavDestinationChanged something like:

navController.addNavigationChangeListener { motionLayout.transtionToAnotherState() }

Something similar to TransitionManager where if I want to go from Scene A to Scene B I just do:

TransitionManager.beginDelayedTransition(rootLayout)
// Do someLayout changes

1) Is something similar doable with MotionLayout?
2) If yes can anyone guide me?

Thank you very much.

Body:
There is no 100% same way to do it, but you can get similar result if you know your original and final states.

setTransition(R.id.stateA, R.id.stateB);
setTransitionDuration(durationMs); // optional
transitionToEnd(); // here may be transitionToStart to goto state A from B

If you don't know your current state you can read it from TransitionView itself:

getCurrentState();

but be aware, if you are in the middle of transition it will return -1


答:
If I understand your requirement correct, you wants the first row only (based on ID) among all rows with same value in the column Value. If it is correct, you can use ROW_NUMBER for achieving your requirement as below-

DEMO HERE

```<code>SELECT ID,Value,Amount,A_ID
FROM
(
    SELECT *,
    ROW_NUMBER() OVER(PARTITION BY Value ORDER BY ID) RN
    FROM Table_B
)A
WHERE RN = 1
ORDER BY ID
</code>```

Now you can join the output with your Table_A to pick other necessary data.

In case you have multiple dates and you need to keep first record per date, the row_number generation will be as below. Other part of query will be just as it is now.

```<code>ROW_NUMBER() OVER(PARTITION BY CAST(Date AS Date),Value ORDER BY ID) RN
</code>```

Title: Fetch specific distinct columns from SQL Server

Body:
I have 2 tables:

Table A:

ID | Date      | Uploaded Date
---+-----------+--------------
16 | 05/01/2020| 05/05/2020 12:36 PM
18 | 05/01/2020| 05/05/2020 12:20 PM

Table B:

ID | Value | Amount  | A_ID
---+-------+---------+-----
1  | 3     | 76.295  | 16
2  | 2     | 93.465  | 16
3  | 5     | 82.396  | 16
4  | 8     | 62.2736 | 16
5  | 9     | 50.71   | 16
6  | 3     | 75.869  | 18
7  | 2     | 93.465  | 18
8  | 5     | 82.396  | 18
9  | 8     | 62.2736 | 18
10 | 9     | 50.71   | 18

I am trying to write a select statement which fetches unique data based on condition.

What I am looking for is unique record based on value column. FYR - below output:

Date       | Amount  | Value
---+-------+---------+------
05/01/2020 | 76.295  | 3
05/01/2020 | 93.465  | 2
05/01/2020 | 82.396  | 5
05/01/2020 | 62.2736 | 8
05/01/2020 | 50.71   | 9

Below are few queries that I have tried:

select Date, Amount, Value
from A
left join B on A.ID = B.A_ID  order by Uploaded Date desc

After executing above query I get the below data:

Date       | Amount  | Value
---+-------+---------+------
05/01/2020 | 76.295  | 3
05/01/2020 | 93.465  | 2
05/01/2020 | 82.396  | 5
05/01/2020 | 62.2736 | 8
05/01/2020 | 50.71   | 9
05/01/2020 | 75.869  | 3
05/01/2020 | 93.465  | 2
05/01/2020 | 82.396  | 5
05/01/2020 | 62.2736 | 8
05/01/2020 | 50.71   | 9

I tried distinct query:

select distinct Date, Amount, Value
from A
left join B on a.ID = b.A_ID order by uploaded date desc

but it stills return me duplicate data:

Date       | Amount  | Value
---+-------+---------+------
05/01/2020 | 76.295  | 3
05/01/2020 | 93.465  | 2
05/01/2020 | 82.396  | 5
05/01/2020 | 62.2736 | 8
05/01/2020 | 50.71   | 9
05/01/2020 | 75.869  | 3

Table with Multiple records.

ID | Date      | Uploaded Date
---+-----------+--------------
16 | 05/01/2020| 05/05/2020 12:36 PM
18 | 05/01/2020| 05/05/2020 12:20 PM
19 | 05/02/2020| 05/05/2020 12:43 PM
20 | 05/03/2020| 06/05/2020 11:57 AM
21 | 05/04/2020| 06/05/2020 11:57 AM

ID | Value | Amount  | A_ID
---+-------+---------+-----
1  | 3     | 76.295  | 16
2  | 2     | 93.465  | 16
3  | 3     | 82.396  | 16
4  | 8     | 62.2736 | 16
5  | 3     | 50.71   | 19
6  | 3     | 50.51   | 20
7  | 4     | 52.71   | 21
8  | 4     | 55.11   | 20

In this case the o/p I am hoping for :

Date       | Amount  | Value
---+-------+---------+------
05/01/2020 | 76.295  | 3
05/01/2020 | 93.465  | 2
05/01/2020 | 62.2736 | 8
05/02/2020 | 50.71   | 3
05/03/2020 | 50.51   | 3
05/03/2020 | 55.11   | 4
05/04/2020 | 52.71   | 4

Body:
If I understand your requirement correct, you wants the first row only (based on ID) among all rows with same value in the column Value. If it is correct, you can use ROW_NUMBER for achieving your requirement as below-

DEMO HERE

SELECT ID,Value,Amount,A_ID
FROM
(
    SELECT *,
    ROW_NUMBER() OVER(PARTITION BY Value ORDER BY ID) RN
    FROM Table_B
)A
WHERE RN = 1
ORDER BY ID

Now you can join the output with your Table_A to pick other necessary data.

In case you have multiple dates and you need to keep first record per date, the row_number generation will be as below. Other part of query will be just as it is now.

ROW_NUMBER() OVER(PARTITION BY CAST(Date AS Date),Value ORDER BY ID) RN


问:
What's the difference between ES6 Map and WeakMap?
Looking this and this MDN pages it seems like the only difference between Maps and WeakMaps is a missing "size" property for WeakMaps. But is this true? What's the difference between them?</p>

答:
From Javascript.info

Map -- If we use an object as the key in a regular Map, then while the Map exists, that object exists as well. It occupies memory and may not be garbage collected.

```<code>let john = { name: "John" };
let array = [ john ];
john = null; // overwrite the reference

// john is stored inside the array, so it won't be garbage-collected
// we can get it as array[0]
</code>```

Similar to that, if we use an object as the key in a regular Map, then while the Map exists, that object exists as well. It occupies memory and may not be garbage collected

```<code>let john = { name: "John" };
let map = new Map();
map.set(john, "...");
john = null; // overwrite the reference

// john is stored inside the map,
// we can get it by using map.keys()
</code>```

WeakMap -- Now, if we use an object as the key in it, and there are no other references to that object – it will be removed from memory (and from the map) automatically.

```<code>let john = { name: "John" };
let weakMap = new WeakMap();
weakMap.set(john, "...");
john = null; // overwrite the reference

// john is removed from memory!
</code>```

Body:
From Javascript.info

Map -- If we use an object as the key in a regular Map, then while the Map exists, that object exists as well. It occupies memory and may not be garbage collected.

let john = { name: "John" };
let array = [ john ];
john = null; // overwrite the reference

// john is stored inside the array, so it won't be garbage-collected
// we can get it as array[0]

Similar to that, if we use an object as the key in a regular Map, then while the Map exists, that object exists as well. It occupies memory and may not be garbage collected

let john = { name: "John" };
let map = new Map();
map.set(john, "...");
john = null; // overwrite the reference

// john is stored inside the map,
// we can get it by using map.keys()

WeakMap -- Now, if we use an object as the key in it, and there are no other references to that object – it will be removed from memory (and from the map) automatically.

let john = { name: "John" };
let weakMap = new WeakMap();
weakMap.set(john, "...");
john = null; // overwrite the reference

// john is removed from memory!


问:
Question on "smart" replacing in mathematica
How do I tell mathematica to do this replacement smartly? (or how do I get smarter at telling mathematica to do what i want)

```<code>expr = b + c d + ec + 2 a;
expr /. a + b :> 1

Out = 2 a + b + c d + ec
</code>```

I expect the answer to be a + cd + ec + 1. And before someone suggests, I don't want to do a :> 1 - b, because for aesthetic purposes, I'd like to have both a and b in my equation as long as the a+b = 1 simplification cannot be made.

In addition, how do I get it to replace all instances of 1-b, -b+1 or -1+b, b-1 with a or -a respectively and vice versa?

Here's an example for this part:

```<code>expr = b + c (1 - a) + (-1 + b)(a - 1) + (1 -a -b) d + 2 a
</code>```

答:
For the first case, you might consider:

```<code>expr = b + c d + ec + 2 a

PolynomialReduce[expr, {a + b - 1}, {b, a}][[2]]
</code>```

For the second case, consider:

```<code>expr = b + c (1 - a) + (-1 + b) (a - 1) + (1 - a - b) d + 2 a;

PolynomialReduce[expr, {x + b - 1}][[2]]

(% /. x -> 1 - b) == expr // Simplify
</code>```

and:

```<code>PolynomialReduce[expr, {a + b - 1}][[2]]

Simplify[% == expr /. a -> 1 - b]
</code>```

Body:
How do I tell mathematica to do this replacement smartly? (or how do I get smarter at telling mathematica to do what i want)

expr = b + c d + ec + 2 a;
expr /. a + b :> 1

Out = 2 a + b + c d + ec

I expect the answer to be a + cd + ec + 1. And before someone suggests, I don't want to do a :> 1 - b, because for aesthetic purposes, I'd like to have both a and b in my equation as long as the a+b = 1 simplification cannot be made.

In addition, how do I get it to replace all instances of 1-b, -b+1 or -1+b, b-1 with a or -a respectively and vice versa?

Here's an example for this part:

expr = b + c (1 - a) + (-1 + b)(a - 1) + (1 -a -b) d + 2 a

Body:
For the first case, you might consider:

expr = b + c d + ec + 2 a

PolynomialReduce[expr, {a + b - 1}, {b, a}][[2]]

For the second case, consider:

expr = b + c (1 - a) + (-1 + b) (a - 1) + (1 - a - b) d + 2 a;

PolynomialReduce[expr, {x + b - 1}][[2]]

(% /. x -> 1 - b) == expr // Simplify

and:

PolynomialReduce[expr, {a + b - 1}][[2]]

Simplify[% == expr /. a -> 1 - b]


问:
How to filter from joined table in sqlalchemy?

Hello everyone, I'm very new with sqlalchemy and I try to do a searching module from any field that I input from the user by the below code.

```<code>    filters = []

    if 'inputVendorName' in inputfield:
        filters.append(Vendors.vendor_name.contains(inputfield['inputVendorName']))

    if 'inputProductName' in inputfield:
        filters.append(Product.product_name.contains(inputfield['inputProductName']))

    if 'inputCustomerName' in inputfield:
        filters.append(Customers.customer_name.contains(inputfield['inputCustomerName']))

    if 'inputSalePrice' in inputfield:
        filters.append(Sales.price.contains(inputfield['inputSalePrice']))

    # jointable --> how to join table
    results = jointable.query.filter(db.or_(*filters)).all()

</code>```

Begin with fiters is a list that contains any input value from the user, and I want to use these values in a list to filter from my join table.

For example, the user has input some product_name and I want to use this product_name to filter and get any record value in Products table that matches to product_name and also gets the other record from another table (Vendors, Sales, Customers) that related to this 'product_name'.

So how can I do that?

答:
Here's a piece of code that runs a query, based on a set of 'dynamic' filters. </p>

```<code>filters = []

# this is an example:
inputfield = {
    "inputVendorName": "J",
    "inputProductName": "Pen",
    "MinPrice": 10
}

if 'inputVendorName' in inputfield:
    filters.append(Vendor.vendor_name.contains(inputfield["inputVendorName"]))

if  'inputProductName' in inputfield:
    filters.append(Product.product_name.contains(inputfield["inputProductName"]))

if 'MinPrice' in inputfield:
    filters.append(Sale.price > inputfield["MinPrice"])

base_query = session.query(Customer, Product, Vendor, Sale).filter(
    Sale.customer_id == Customer.customer_id, Vendor.vendor_id == Product.vendor_id, Sale.product_id == Product.product_id)

for res in base_query.filter(*filters).all():
    print(res)
</code>```

Body:
Hello everyone, I'm very new with sqlalchemy and I try to do a searching module from any field that I input from the user by the below code.

    filters = []

    if 'inputVendorName' in inputfield:
        filters.append(Vendors.vendor_name.contains(inputfield['inputVendorName']))

    if 'inputProductName' in inputfield:
        filters.append(Product.product_name.contains(inputfield['inputProductName']))

    if 'inputCustomerName' in inputfield:
        filters.append(Customers.customer_name.contains(inputfield['inputCustomerName']))

    if 'inputSalePrice' in inputfield:
        filters.append(Sales.price.contains(inputfield['inputSalePrice']))

    # jointable --> how to join table
    results = jointable.query.filter(db.or_(*filters)).all()

Begin with fiters is a list that contains any input value from the user, and I want to use these values in a list to filter from my join table.

For example, the user has input some product_name and I want to use this product_name to filter and get any record value in Products table that matches to product_name and also gets the other record from another table (Vendors, Sales, Customers) that related to this 'product_name'.

So how can I do that?

Body:
Here's a piece of code that runs a query, based on a set of 'dynamic' filters.

filters = []

# this is an example:
inputfield = {
    "inputVendorName": "J",
    "inputProductName": "Pen",
    "MinPrice": 10
}

if 'inputVendorName' in inputfield:
    filters.append(Vendor.vendor_name.contains(inputfield["inputVendorName"]))

if  'inputProductName' in inputfield:
    filters.append(Product.product_name.contains(inputfield["inputProductName"]))

if 'MinPrice' in inputfield:
    filters.append(Sale.price > inputfield["MinPrice"])

base_query = session.query(Customer, Product, Vendor, Sale).filter(
    Sale.customer_id == Customer.customer_id, Vendor.vendor_id == Product.vendor_id, Sale.product_id == Product.product_id)

for res in base_query.filter(*filters).all():
    print(res)


问:
Empty Object Repository List in RAD Studio 10.3
I've installed new version of RAD Studio 10.3 a couple days ago on my system Windows 10 Pro 64bit. It required to login with admin rights, i did it.
Then I started RAD Studio from non-administrative account, and when IDE started, I clicked "File - New", and all default items from object repository were lost.
There was no items like "Console application", or "Windows Application". Only folder "Other - Unit Test", with three items: "Code Template", "Project Group", "Text File".

Then I restarted RAD Studio from an administrative account. All items were in list: Console Application, Windows Application, FireMonkey Application.
Then I restarted again from non-administrative account. And no items again.

I searched in web for that problem, it seems it doesn't load items from object repository, when logged in from non-administrative account. But what is the reason? I gave full read/write access in every folder of "Environment Variables" for all user.

答:
The problem solved.
I've executed regedit.exe, and deleted branch HKEY_CURRENT_USER\Software\Embarcadero\BDS\20.0

I could rename it, but I had no important settings saved, so I deleted it.

And then I've restarted RAD Studio from non-administrative account. Regedit branch was recreated, and everything became fine. Standart project items appeared.
I think that issue was because of first launch of RAD Studio was by admin account. And it created some wrong paths (which exactly, I didn't find).

Now everything is okay.


问:
$(document).ready() doesn't run after f:ajax rendering
I have some jQuery code that runs on every $(document).ready() event.
I also have some <f:ajax> tags that do re-rendering of some parts of the page.

I noticed that when I rerender a component, the $(document).ready() doesn't get called.

Is there a way to run javascript code after every <f:ajax> rerendering?
(I can technically use the onevent tag but that's the unfavourable solution to me since I will have to call the function on every <f:ajax>)

Just for illustration, this is the jQuery Code:

```<code>$(document).ready(function() { ...CODE... }
</code>```

And the JSF code:

```<code><f:ajax event="click" render=":someComponentID"/>
</code>```

Thanks!

UPDATE This question might be a duplicate of this one. I'm looking into it.

UPDATE2
This is easily solvable using the JSF Javascript event binding:

```<code>jsf.ajax.addOnEvent(function(data){
  if (data.status === 'success') {
    // Do stuff here
  }
}
</code>```

Read more about it under the JSF 2 reference

答:
Use events and listeners..

Have a read at Ajax tag events and listeners

Body:
I have some jQuery code that runs on every $(document).ready() event.
I also have some <f:ajax> tags that do re-rendering of some parts of the page.

I noticed that when I rerender a component, the $(document).ready() doesn't get called.

Is there a way to run javascript code after every <f:ajax> rerendering?
(I can technically use the onevent tag but that's the unfavourable solution to me since I will have to call the function on every <f:ajax>)

Just for illustration, this is the jQuery Code:

$(document).ready(function() { ...CODE... }

And the JSF code:

<f:ajax event="click" render=":someComponentID"/>

Thanks!

UPDATE This question might be a duplicate of this one. I'm looking into it.

UPDATE2
This is easily solvable using the JSF Javascript event binding:

jsf.ajax.addOnEvent(function(data){
  if (data.status === 'success') {
    // Do stuff here
  }
}

Read more about it under the JSF 2 reference


问:
adding background colour to webpage
new to ASP.net core, how do I add background colour to the page using the cshtml? I am using the automatically generated page but this is invariable white with black text and it doesn't seem to like the use of  inline.</p>

答:
In .net  core application,there is a default layout in  shared/_layout.cshtml.And each view will use the layout.And in _layout.cshtml,we often reference site.css in .So if you want to change the background color of  all the pages,you can change the style in site.css.Also, you can change the style in _layout.cshtml by.

For example,I change the background color of  body:

In site.css:

```<code>body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
  background-color:red;
}
</code>```

In _layout.cshtml:

```<code><style>
    body {
    background-color:red;
    }
</style>
</code>```

Result:

Title: adding background colour to webpage

Body:
In .net  core application,there is a default layout in  shared/_layout.cshtml.And each view will use the layout.And in _layout.cshtml,we often reference site.css in <head></head>.So if you want to change the background color of  all the pages,you can change the style in site.css.Also, you can change the style in _layout.cshtml by.

For example,I change the background color of  body:

In site.css:

body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
  background-color:red;
}

In _layout.cshtml:

<style>
    body {
    background-color:red;
    }
</style>

Result:


问:
How to programmatically return back to home in autodesk forge viewer?
I have a viewer where I zoom in and focus on an object by it's dbID with the following script.

```<code>viewer.fitToView([dbId]);
let color = new THREE.Vector4(0, 0, 0.5, 0.5);
window.viewer.setThemingColor(item.link,color)
</code>```

I can clear the theming colors with clearThemingColors() call. But for now, I use the home icon at the top to return to the home position. Is there a way to do this programmatically.

Body:
I have a viewer where I zoom in and focus on an object by it's dbID with the following script.

viewer.fitToView([dbId]);
let color = new THREE.Vector4(0, 0, 0.5, 0.5);
window.viewer.setThemingColor(item.link,color)

I can clear the theming colors with clearThemingColors() call. But for now, I use the home icon at the top to return to the home position. Is there a way to do this programmatically.

Body:
viewer.utilities.goHome();

Ref: https://forge.autodesk.com/en/docs/viewer/v2/reference/javascript/viewingutilities/#gohome


问:
What is the correct way to invoke this Scala method on main?
Me and my mates have to do a presentation on functional programming and we are trying to present standard deviation with FP, since they are beasts, they did the Scheme code for it. Meanwhile, I'm trying to convert that code into Scala since Sacla will be easier for introduction bcoz everyone in class is familiar with Java.

```<code>def soma(lista: List[Double]): Double={
 if(lista.isEmpty){
  return 0
 }else{
  return lista.head+soma(lista.tail)
 }
}
</code>```

When I try to invoke it with soma(nameOfTheList), the program simply does nothing, it gives me no error message or output. I tried the main as follows:

```<code>    def main(args: Array[String]){
  val nums: List[Double] = List(1, 2, 3, 4)
  println(soma(nums))
}
</code>```

The idea is to use lists heavily but not use anything ready-made other than car/cdr or head/tail.

答:
I have run the same method and it worked fine.

```<code>object Main {
  def main(args: Array[String]): Unit = {
    def soma(lista: List[Double]): Double={
      if(lista.isEmpty){
        return 0
      }else{
        return lista.head+soma(lista.tail)
      }
    }

    val nums: List[Double] = List(1, 2, 3, 4)
    println(soma(nums))
  }
}
</code>```

Hope it will help.

Body:
Me and my mates have to do a presentation on functional programming and we are trying to present standard deviation with FP, since they are beasts, they did the Scheme code for it. Meanwhile, I'm trying to convert that code into Scala since Sacla will be easier for introduction bcoz everyone in class is familiar with Java.

def soma(lista: List[Double]): Double={
 if(lista.isEmpty){
  return 0
 }else{
  return lista.head+soma(lista.tail)
 }
}

When I try to invoke it with soma(nameOfTheList), the program simply does nothing, it gives me no error message or output. I tried the main as follows:

    def main(args: Array[String]){
  val nums: List[Double] = List(1, 2, 3, 4)
  println(soma(nums))
}

The idea is to use lists heavily but not use anything ready-made other than car/cdr or head/tail.

Body:
I have run the same method and it worked fine.

object Main {
  def main(args: Array[String]): Unit = {
    def soma(lista: List[Double]): Double={
      if(lista.isEmpty){
        return 0
      }else{
        return lista.head+soma(lista.tail)
      }
    }

    val nums: List[Double] = List(1, 2, 3, 4)
    println(soma(nums))
  }
}

Hope it will help.


问:
Docker React App: 404s will fallback to /
I am building an React Javascript App with npm and want to deploy it on docker.

When I run the App locally with:

```<code>npm start
</code>```

It all works just fine.
But then when I build a Docker Image and test it I get follwing error:

```<code>$ docker run react-app

> keycloak-react@0.1.0 start /
> react-scripts start

ℹ ｢wds｣: Project is running at http://172.17.0.2/
ℹ ｢wds｣: webpack output is served from
ℹ ｢wds｣: Content not from webpack is served from /public
ℹ ｢wds｣: 404s will fallback to /
Starting the development server...
</code>```

The Dockerfile looks like:

```<code>FROM node:latest
COPY ./keycloak-react .
RUN npm install typescript
RUN npm install node-sass
RUN npm install sass
RUN npm install fibers
RUN npm install
EXPOSE 3000
CMD [ "npm", "start", "run", "--host", "0.0.0.0"]
</code>```

I don't know what to do any ideas ?

答:
I added -i -t flags in the docker run command and it worked fine for me

-i leaves the stdin of the container opened

-t assigns a pseudo-tty (for interactive session with shell)

My command was:

```<code>docker container run -i -t image_name
</code>```

I think

```<code>docker run -i -t image_name
</code>```

will work as well (don't know the real difference between the 2)

Body:
I am building an React Javascript App with npm and want to deploy it on docker.

When I run the App locally with:

npm start

It all works just fine.
But then when I build a Docker Image and test it I get follwing error:

$ docker run react-app

> keycloak-react@0.1.0 start /
> react-scripts start

ℹ ｢wds｣: Project is running at http://172.17.0.2/
ℹ ｢wds｣: webpack output is served from
ℹ ｢wds｣: Content not from webpack is served from /public
ℹ ｢wds｣: 404s will fallback to /
Starting the development server...

The Dockerfile looks like:

FROM node:latest
COPY ./keycloak-react .
RUN npm install typescript
RUN npm install node-sass
RUN npm install sass
RUN npm install fibers
RUN npm install
EXPOSE 3000
CMD [ "npm", "start", "run", "--host", "0.0.0.0"]

I don't know what to do any ideas ?

Body:
I added -i -t flags in the docker run command and it worked fine for me

-i leaves the stdin of the container opened

-t assigns a pseudo-tty (for interactive session with shell)

My command was:

docker container run -i -t image_name

I think

docker run -i -t image_name

will work as well (don't know the real difference between the 2)


答:
This is the code you want:

```<code>object TestApp extends App {
  def soma(lista: List[Double]): Double = {
    @annotation.tailrec
    def loop(list: List[Double], res: Double): Double =
      list match {
        case hd :: tail => loop(tail, res + hd)
        case _ => res
      }

    loop(lista, 0.0)
  }

  val nums: List[Double] = List(1, 2, 3, 4)

  println(soma(nums))
}
</code>```

But I suggest learning a bit more Scala (and FP) before giving talks about it.

Title: What is the correct way to invoke this Scala method on main?

Body:
This is the code you want:

object TestApp extends App {
  def soma(lista: List[Double]): Double = {
    @annotation.tailrec
    def loop(list: List[Double], res: Double): Double =
      list match {
        case hd :: tail => loop(tail, res + hd)
        case _ => res
      }

    loop(lista, 0.0)
  }

  val nums: List[Double] = List(1, 2, 3, 4)

  println(soma(nums))
}

But I suggest learning a bit more Scala (and FP) before giving talks about it.


问:
Syntax error help
I seem to have a syntax error and can't see it myself, could someone run over it for me please?

Thanks.

```<code><script>
    var acurl_<?php echo $request_data['friendship_id']; ?> = "sn-include/create_bond_accept.php?friendship_id=<?php echo $request_data['friendship_id']; ?>&friend_id=<?php echo $fromuser['id']; ?>";
</script>
</code>```

答:
Use here doc instead:

```<code><?php
echo <<<JS
<script>
    var acurl_{$request_data['friendship_id']} = "sn-include/create_bond_accept.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>

<script>
    var dnurl_{$request_data['friendship_id']} = "sn-include/create_bond_deny.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>
JS;
?>
</code>```

See http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Title: Syntax error help

Body:
Use here doc instead:

<?php
echo <<<JS
<script>
    var acurl_{$request_data['friendship_id']} = "sn-include/create_bond_accept.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>

<script>
    var dnurl_{$request_data['friendship_id']} = "sn-include/create_bond_deny.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>
JS;
?>

See http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc


问:
vuejs init data function(methods) in created() or computed property
I was making a simple table and started thinking which one is better or more accurate way to write. I know it's better to use created hook but.. I just want to get ideas what you guys think about it.

We have to display live data (update cycle is 1 sec), but It's very changeable. So I called a initData() function in computed property but my senior used created() hook.

me:
1. methods:  { initData() {axios.get().then() }}
2. call it in computed property(cuz it's updated every sec):

```<code>getInitData() { this.initData() return this.data}
</code>```

my senior:
1. methods: same
2. call it in created hook(cuz it's init): created() {this.initData()}
3. return it in computed property(cuz it's updated every sec):

```<code> getInitData() { return this.data}
</code>```

So... What do you think that the performance difference between these 2 cases?

答:
If you make reactive property change in computed, it will create an infinite loop

Change this.data ---> computed property recalculated --> change this.data

In computed, reactive data get cached and triggers DOM change whenever it gets changed. Now imagine this case when you change a this.data once you received API response, as soon as this.data gets changes it will trigger computed property, again you will create a network request and again change this.data and computed property. It will create an infinite loop

Whereas in created hook it behaves as a simple method and only triggers when your component gets created, which means the first time you will get your data and mutate this.data. It will not trigger again at any case until you recreate your component

Body:
I was making a simple table and started thinking which one is better or more accurate way to write. I know it's better to use created hook but.. I just want to get ideas what you guys think about it.

We have to display live data (update cycle is 1 sec), but It's very changeable. So I called a initData() function in computed property but my senior used created() hook.

me:
1. methods:  { initData() {axios.get().then() }}
2. call it in computed property(cuz it's updated every sec):

getInitData() { this.initData() return this.data}

my senior:
1. methods: same
2. call it in created hook(cuz it's init): created() {this.initData()}
3. return it in computed property(cuz it's updated every sec):

 getInitData() { return this.data}

So... What do you think that the performance difference between these 2 cases?


问:
Mat-icon shows text Angular Material
I'm using mat-icon and on some browsers, the mat-icon shows the text instead of the actual icon or it can show the text until the icon is being imported. I tried to import:

@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
@import '~@angular/material/prebuilt-themes/indigo-pink.css';

to my style.css but it didn't solve the issue. Is there a way to prevent showing the text until icon loaded or even not showing text at all?

```<code>import {
  MatButtonModule,
  MatCardModule,
  MatCheckboxModule,
  MatChipsModule,
  MatDialogModule,
  MatGridListModule,
  MatIconModule,
  MatInputModule,
  MatListModule,
  MatMenuModule,
  MatOptionModule,
  MatProgressBarModule,
  MatProgressSpinnerModule,
  MatRadioModule,
  MatRippleModule,
  MatSelectModule,
  MatSidenavModule,
  MatStepperModule,
  MatTabsModule,
  MatToolbarModule,
  MatFormFieldModule,
  MatAutocompleteModule
} from '@angular/material';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';
import { UniquePipe } from './pipes/unique/unique.pipe';
import { ConfirmCountryComponent } from './dialogs/confirm-country/confirm-country.component';
import { AutocompleteComponent } from './components/autocomplete/autocomplete.component';
import { ConfirmCountryService } from './dialogs/confirm-country/confirm-country.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatAutocompleteModule,
    MatButtonModule,
    MatProgressSpinnerModule
  ],
  exports: [
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRippleModule,
    MatIconModule,
    MatSidenavModule,
    MatToolbarModule,
    MatMenuModule,
    MatButtonModule,
    MatListModule,
    MatIconModule,
    MatInputModule,
    MatOptionModule,
    MatSelectModule,
    MatGridListModule,
    MatDialogModule,
    MatStepperModule,
    MatCheckboxModule,
    MatCardModule,
    MatRadioModule,
    MatChipsModule,
    MatTabsModule,
    MatAutocompleteModule,
    MatFormFieldModule,
    ScrollDispatchModule,
    UniquePipe
  ],
  entryComponents: [XXX],
  providers: [XXX],
  declarations: [XXX, XXX, XXX],
  schemas: [XXX]
})
export class AngularMaterialModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AngularMaterialModule,
    };
  }
}```
```

答:
Add the following to your index.html:

```<code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</code>```

instead of this:

```<code>@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
</code>```

Title: Mat-icon shows text Angular Material

Body:
I'm using mat-icon and on some browsers, the mat-icon shows the text instead of the actual icon or it can show the text until the icon is being imported. I tried to import:

@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
@import '~@angular/material/prebuilt-themes/indigo-pink.css';

to my style.css but it didn't solve the issue. Is there a way to prevent showing the text until icon loaded or even not showing text at all?

import {
  MatButtonModule,
  MatCardModule,
  MatCheckboxModule,
  MatChipsModule,
  MatDialogModule,
  MatGridListModule,
  MatIconModule,
  MatInputModule,
  MatListModule,
  MatMenuModule,
  MatOptionModule,
  MatProgressBarModule,
  MatProgressSpinnerModule,
  MatRadioModule,
  MatRippleModule,
  MatSelectModule,
  MatSidenavModule,
  MatStepperModule,
  MatTabsModule,
  MatToolbarModule,
  MatFormFieldModule,
  MatAutocompleteModule
} from '@angular/material';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';
import { UniquePipe } from './pipes/unique/unique.pipe';
import { ConfirmCountryComponent } from './dialogs/confirm-country/confirm-country.component';
import { AutocompleteComponent } from './components/autocomplete/autocomplete.component';
import { ConfirmCountryService } from './dialogs/confirm-country/confirm-country.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatAutocompleteModule,
    MatButtonModule,
    MatProgressSpinnerModule
  ],
  exports: [
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRippleModule,
    MatIconModule,
    MatSidenavModule,
    MatToolbarModule,
    MatMenuModule,
    MatButtonModule,
    MatListModule,
    MatIconModule,
    MatInputModule,
    MatOptionModule,
    MatSelectModule,
    MatGridListModule,
    MatDialogModule,
    MatStepperModule,
    MatCheckboxModule,
    MatCardModule,
    MatRadioModule,
    MatChipsModule,
    MatTabsModule,
    MatAutocompleteModule,
    MatFormFieldModule,
    ScrollDispatchModule,
    UniquePipe
  ],
  entryComponents: [XXX],
  providers: [XXX],
  declarations: [XXX, XXX, XXX],
  schemas: [XXX]
})
export class AngularMaterialModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AngularMaterialModule,
    };
  }
}```

Body:
Add the following to your index.html:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

instead of this:

@import 'https://fonts.googleapis.com/icon?family=Material+Icons';


问:
Fastest way to extract a substring in C#
I'm going to process thousands of strings (with the size of ~150kB on average). Each of them contains zero or more substrings of the following form:

```<code><a href="/link/i/want">Fixed_String</a>
</code>```

I would like to extract all such links and put them into a list.

Additionally, there is another fixed string after which the strings I am looking for will not appear.

What's the fastest way to get the strings?

答:
I think in this case where there are strings which are large enough on average and which contains zero or more substrings the best way will be to use Regex class like this:</p>

```<code>string anchorPattern = @"<(.|/)a(.|\n)+?>";

foreach (string str in strings)
{
    Regex regex = new Regex(anchorPattern);

    foreach (Match match in regex.Matches(str))
    {
         // do here what you want with substring in match.Value
    }

}
</code>```

Body:
I'm going to process thousands of strings (with the size of ~150kB on average). Each of them contains zero or more substrings of the following form:

Fixed_String

I would like to extract all such links and put them into a list.

Additionally, there is another fixed string after which the strings I am looking for will not appear.

What's the fastest way to get the strings?

Body:
I think in this case where there are strings which are large enough on average and which contains zero or more substrings the best way will be to use Regex class like this:

string anchorPattern = @"<(.|/)a(.|\n)+?>";

foreach (string str in strings)
{
    Regex regex = new Regex(anchorPattern);

    foreach (Match match in regex.Matches(str))
    {
         // do here what you want with substring in match.Value
    }

}


问:
CORS after a long inactivity in the chat
I have been inactive in the chat for more than an hour since the connection was initialized. After I started sending requests to getstrem (receiving messages, for example) and I get an error (I attached a photo). Although connection is still active andevent health.check comes to me. This occurs only after a long inactivity.
What could be the problem?

答: I have found a solution. When initializing the connection on my own backend side, I create a token and specify the expiration date for it. If not specified, then by default this value will be null (infinity)


问:
Django admin list page takes forever to load after overriding get_queryset method
I have this model admin -

```<code>class NewsAdmin(ImageWidgetAdmin):
    image_fields = ['featured_image']
    list_per_page = 20
    list_display = ('heading', 'category', 'status', 'is_active', 'created_at', 'published_at',
                    'created_by', 'published_by')
    list_editable = ('category', 'status', 'is_active')
    list_filter = ('published_at', 'created_at', 'status', 'is_active', 'created_by',
                   'published_by',)
    search_fields = ('heading', 'category', 'tags', 'source')
    actions = [enable_object, disable_object, status_draft, status_private, status_public]
    actions_on_bottom = True
</code>```

It only takes max 400ms to load. Here's the django-debug-toolbar image -

djdt image without get_queryset

But when I override the get_queryset method for language filtered objects -

```<code>    def get_queryset(self, request):
        queryset = super(NewsAdmin, self).get_queryset(request)
        return queryset.filter(language=request.LANGUAGE_CODE)
</code>```

It takes around 17-18 seconds which is nuts!!
Here's the django-debug-toolbar image -

djdt image with get_queryset

Even same this is happening for the front end queries as well! For details - I have database table with around 400k records and here's the model -

```<code>class News(BaseEntityBasicAbstract, HitCountMixin):
    NEWS_STATUS = (
        ('draft', _('Draft')),
        ('pending', _('Pending')),
        ('review', _('Review')),
        ('public', _('Public')),
        ('private', _('Private'))
    )
    backup = models.BooleanField(default=False)
    prev_id = models.BigIntegerField(null=True, blank=True)
    language = models.CharField(max_length=10, choices=LANGUAGES, default='bn')
    heading = models.CharField(max_length=255, null=True, blank=True,
                               verbose_name=_('News Heading'),
                               help_text=_('Provide a news heading/caption.'))
    sub_caption = models.TextField(max_length=255, null=True, blank=True,
                                   verbose_name=_('Summary'),
                                   help_text=_('Provide summary of the news.'))
    url = models.CharField(max_length=255, unique=True, verbose_name=_('URL/Slug/Link'),
                           help_text=_('Unique url for the news without whitspace.'))
    content = HTMLField(null=True, blank=True, verbose_name=_('Content'),
                        help_text=_('HTML content with texts, links & images.'))
    featured_image = models.FileField(upload_to=FilePrefix('news/'), null=True, blank=True,
                                      verbose_name=_('Featured Image'),
                                      help_text=_('Upload a featured image for news.'))
    image_caption = models.TextField(max_length=255, null=True, blank=True,
                                     verbose_name=_('Image Caption'),
                                     help_text=_('Provide a image caption.'))
    status = models.CharField(max_length=20, choices=NEWS_STATUS, default='pending',
                              verbose_name=_('News Status'),
                              help_text=_('Only public news can be seen on front end.'))
    source = models.ForeignKey(NewsSource, on_delete=models.SET_NULL, null=True, blank=True,
                               verbose_name=_('News Source'),
                               help_text=_('Select a news source.'))
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True,
                                 verbose_name=_('Category'),
                                 help_text=_('Select a news category.'))
    tags = tagulous.models.TagField(
        blank=True,
        to=Tags,
        verbose_name=_('News Tags'),
        help_text=_('Provide news tags separated with commas.')
    )
    published_at = models.DateTimeField(null=True, blank=True,
                                        verbose_name=_('Published At'))
    menu_items = GenericRelation(MenuItems, object_id_field='id',
                                 related_query_name='news_as_menu')
    hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk',
                                        related_query_name='news_hit_count')
    created_by = models.ForeignKey(User, related_name='news_created_by',
                                   on_delete=models.SET_NULL, null=True, blank=True,
                                   verbose_name=_('Created By'))
    updated_by = models.ForeignKey(User, related_name='news_updated_by',
                                   on_delete=models.SET_NULL, null=True, blank=True,
                                   verbose_name=_('Last Updated By'))
    published_by = models.ForeignKey(User, related_name='news_published_by',
                                     on_delete=models.SET_NULL, null=True, blank=True,
                                     verbose_name=_('Published By'))
    deleted_by = models.ForeignKey(User, related_name='news_deleted_by',
                                   on_delete=models.SET_NULL, null=True, blank=True,
                                   verbose_name=_('Deleted By'))
</code>```

I'm lost why is this happening! Please help me figure out the problem here!

答:
You are filtering on a field without an index. The bigger the table, the longer it takes as the database needs to scan each row. Alter your field definition to allow for an index and take care of migrations.

language = models.CharField(max_length=10, choices=LANGUAGES, default='bn' db_index=True)
```

Body:
I have this model admin -

class NewsAdmin(ImageWidgetAdmin):
    image_fields = ['featured_image']
    list_per_page = 20
    list_display = ('heading', 'category', 'status', 'is_active', 'created_at', 'published_at',
                    'created_by', 'published_by')
    list_editable = ('category', 'status', 'is_active')
    list_filter = ('published_at', 'created_at', 'status', 'is_active', 'created_by',
                   'published_by',)
    search_fields = ('heading', 'category', 'tags', 'source')
    actions = [enable_object, disable_object, status_draft, status_private, status_public]
    actions_on_bottom = True

It only takes max 400ms to load. Here's the django-debug-toolbar image -

djdt image without get_queryset

But when I override the get_queryset method for language filtered objects -

    def get_queryset(self, request):
        queryset = super(NewsAdmin, self).get_queryset(request)
        return queryset.filter(language=request.LANGUAGE_CODE)

It takes around 17-18 seconds which is nuts!!
Here's the django-debug-toolbar image -

djdt image with get_queryset

Even same this is happening for the front end queries as well! For details - I have database table with around 400k records and here's the model -

class News(BaseEntityBasicAbstract, HitCountMixin):
    NEWS_STATUS = (
        ('draft', _('Draft')),
        ('pending', _('Pending')),
        ('review', _('Review')),
        ('public', _('Public')),
        ('private', _('Private'))
    )
    backup = models.BooleanField(default=False)
    prev_id = models.BigIntegerField(null=True, blank=True)
    language = models.CharField(max_length=10, choices=LANGUAGES, default='bn')
    heading = models.CharField(max_length=255, null=True, blank=True,
                               verbose_name=_('News Heading'),
                               help_text=_('Provide a news heading/caption.'))
    sub_caption = models.TextField(max_length=255, null=True, blank=True,
                                   verbose_name=_('Summary'),
                                   help_text=_('Provide summary of the news.'))
    url = models.CharField(max_length=255, unique=True, verbose_name=_('URL/Slug/Link'),
                           help_text=_('Unique url for the news without whitspace.'))
    content = HTMLField(null=True, blank=True, verbose_name=_('Content'),
                        help_text=_('HTML content with texts, links & images.'))
    featured_image = models.FileField(upload_to=FilePrefix('news/'), null=True, blank=True,
                                      verbose_name=_('Featured Image'),
                                      help_text=_('Upload a featured image for news.'))
    image_caption = models.TextField(max_length=255, null=True, blank=True,
                                     verbose_name=_('Image Caption'),
                                     help_text=_('Provide a image caption.'))
    status = models.CharField(max_length=20, choices=NEWS_STATUS, default='pending',
                              verbose_name=_('News Status'),
                              help_text=_('Only public news can be seen on front end.'))
    source = models.ForeignKey(NewsSource, on_delete=models.SET_NULL, null=True, blank=True,
                               verbose_name=_('News Source'),
                               help_text=_('Select a news source.'))
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True,
                                 verbose_name=_('Category'),
                                 help_text=_('Select a news category.'))
    tags = tagulous.models.TagField(
        blank=True,
        to=Tags,
        verbose_name=_('News Tags'),
        help_text=_('Provide news tags separated with commas.')
    )
    published_at = models.DateTimeField(null=True, blank=True,
                                        verbose_name=_('Published At'))
    menu_items = GenericRelation(MenuItems, object_id_field='id',
                                 related_query_name='news_as_menu')
    hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk',
                                        related_query_name='news_hit_count')
    created_by = models.ForeignKey(User, related_name='news_created_by',
                                   on_delete=models.SET_NULL, null=True, blank=True,
                                   verbose_name=_('Created By'))
    updated_by = models.ForeignKey(User, related_name='news_updated_by',
                                   on_delete=models.SET_NULL, null=True, blank=True,
                                   verbose_name=_('Last Updated By'))
    published_by = models.ForeignKey(User, related_name='news_published_by',
                                     on_delete=models.SET_NULL, null=True, blank=True,
                                     verbose_name=_('Published By'))
    deleted_by = models.ForeignKey(User, related_name='news_deleted_by',
                                   on_delete=models.SET_NULL, null=True, blank=True,
                                   verbose_name=_('Deleted By'))

I'm lost why is this happening! Please help me figure out the problem here!


问:
What is the difference between ListView and SingleChildScrollView in Flutter?
I have seen few examples using ListView as the main body element of Scaffold and in few tutorials, it's SingleChildScrollView. All that I understood is both allow some axis of scrolling based on the direction that is configured but cannot figure out when to use one over the other?

ListView:

```<code>Scaffold
  body : ListView
    children : Padding/Container
</code>```

SingleChildScrollView:

```<code>Scaffold
  body : SingleChildScrollView
    child : Column
</code>```

答:
ListView: is used when we have to render the same kind of widgets for n elements

SingleChildScrollView: is used when we have different widgets for n elements.

Ideally, both the cases we required scrolling, Listview have default behavior, but column and other widgets don't have so required to use SingleChildScrollView

Updated:
One important point you should take care while choosing ListView

```<code> ListView() -- Render all the items in the list, even if it is not visible.

`ListView.Builder()` -- Render only visible items on the screen.
</code>```

Body:
I have seen few examples using ListView as the main body element of Scaffold and in few tutorials, it's SingleChildScrollView. All that I understood is both allow some axis of scrolling based on the direction that is configured but cannot figure out when to use one over the other?

ListView:

Scaffold
  body : ListView
    children : Padding/Container

SingleChildScrollView:

Scaffold
  body : SingleChildScrollView
    child : Column

Body:
ListView: is used when we have to render the same kind of widgets for n elements

SingleChildScrollView: is used when we have different widgets for n elements.

Ideally, both the cases we required scrolling, Listview have default behavior, but column and other widgets don't have so required to use SingleChildScrollView

Updated:
One important point you should take care while choosing ListView

 ListView() -- Render all the items in the list, even if it is not visible.

`ListView.Builder()` -- Render only visible items on the screen.


问:
WCF invoking service fail
I was able to call it in my own server and it works but the problem occurs when I host wcf service in IIS. The details of this error are as follows...

Failed to invoke the service. Possible causes: The service is offline
  or inaccessible; the client-side configuration does not match the
  proxy; the existing proxy is invalid. Refer to the stack trace for
  more detail. You can try to recover by starting a new proxy, restoring
  to default configuration, or refreshing the service.

Stack Trace Error Details

The server was unable to process the request due to an internal error.
  For more information about the error, either turn on
  IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
  or from the <serviceDebug> configuration behavior) on the server in
  order to send the exception information back to the client, or turn on
  tracing as per the Microsoft .NET Framework 3.0 SDK documentation and
  inspect the server trace logs.

Server stack trace:

  at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message
  reply, MessageFault fault, String action, MessageVersion version,
  FaultConverter faultConverter)

  at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
  operation, ProxyRpc& rpc)

  at System.ServiceModel.Channels.ServiceChannel.Call(String action,
  Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)

  at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)

  at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)

Exception rethrown at [0]:

  at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)

  at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)

  at IUserService.GetUser(String UserID)

  at UserServiceClient.GetUser(String UserID)

Here are the source codes:

app.config file from wcfservicelirbrary

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>

<system.web>
<compilation debug="true" />
</system.web>
  <system.serviceModel>
    <services>
      <service name="UserServiceLibrary.UserService">
        <endpoint address="" binding="wsHttpBinding"      contract="UserServiceLibrary.IUserService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/UserServiceLibrary/UserService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
</code>```

Web config file from WCF Website Host

```<code><?xml version="1.0"?>
 <configuration>

  <system.web>
    <compilation debug="false" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="UserServiceLibrary.UserService">
       <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
  contract="IMetadataExchange" />
       <endpoint address="basic" binding="basicHttpBinding" bindingConfiguration=""
  contract="UserServiceLibrary.IUserService" />
       <endpoint address="" binding="wsHttpBinding" contract="UserServiceLibrary.IUserService" />
      </service>
    </services>
    <behaviors>
     <serviceBehaviors>
       <behavior>

         <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
</code>```

答:
Problem :- I had the same problem with hosted WCF service on one of our windows servers. Application was unable to connect with the service.

Solution :- Had to reset app/pool of WCF service

Thanks

Title: WCF invoking service fail

Body:
I was able to call it in my own server and it works but the problem occurs when I host wcf service in IIS. The details of this error are as follows...

Failed to invoke the service. Possible causes: The service is offline
  or inaccessible; the client-side configuration does not match the
  proxy; the existing proxy is invalid. Refer to the stack trace for
  more detail. You can try to recover by starting a new proxy, restoring
  to default configuration, or refreshing the service.

Stack Trace Error Details

The server was unable to process the request due to an internal error.
  For more information about the error, either turn on
  IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
  or from the <serviceDebug> configuration behavior) on the server in
  order to send the exception information back to the client, or turn on
  tracing as per the Microsoft .NET Framework 3.0 SDK documentation and
  inspect the server trace logs.

Server stack trace:

  at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message
  reply, MessageFault fault, String action, MessageVersion version,
  FaultConverter faultConverter)

  at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
  operation, ProxyRpc& rpc)

  at System.ServiceModel.Channels.ServiceChannel.Call(String action,
  Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)

  at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)

  at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)

Exception rethrown at [0]:

  at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)

  at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)

  at IUserService.GetUser(String UserID)

  at UserServiceClient.GetUser(String UserID)

Here are the source codes:

app.config file from wcfservicelirbrary

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<system.web>
<compilation debug="true" />
</system.web>
  <system.serviceModel>
    <services>
      <service name="UserServiceLibrary.UserService">
        <endpoint address="" binding="wsHttpBinding"      contract="UserServiceLibrary.IUserService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/UserServiceLibrary/UserService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Web config file from WCF Website Host

<?xml version="1.0"?>
 <configuration>

  <system.web>
    <compilation debug="false" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="UserServiceLibrary.UserService">
       <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
  contract="IMetadataExchange" />
       <endpoint address="basic" binding="basicHttpBinding" bindingConfiguration=""
  contract="UserServiceLibrary.IUserService" />
       <endpoint address="" binding="wsHttpBinding" contract="UserServiceLibrary.IUserService" />
      </service>
    </services>
    <behaviors>
     <serviceBehaviors>
       <behavior>

         <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>


问:
C code generating a "zsh segmentation fault"
I wrote a simple script to calculate prime numbers but when I compile and run it, I get this error and always after 106747.

```<code>...
106727
106739
106747
zsh: segmentation fault  ./a.out 1000000
</code>```

This is the code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int *Primes;

int isPrime(int n) {
    int i = 0;
    int calc_to = ceil(sqrt(n));
    while (Primes[i] < calc_to) {
        if (n % Primes[i] == 0) {
            return 0;
        }
        i ++;
    }
    return 1;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
            printf("Usage: ./a.out <Find Till>");
            return 0;
    }

    int Len = 3;
    Primes = malloc(sizeof(int) * Len);
    Primes[0] = 2; Primes[1] = 3;
    printf("2\n3\n");

    int calc_to = atoi(argv[1]);
    for (int n = 4; n < calc_to; n++) {
        if (isPrime(n) == 1) {
                Primes[Len - 1] = n;
                printf("%d\n", n);
                Primes = realloc(Primes, sizeof(int) * Len);
                Len ++;
            }
        }
    free(Primes);
}
</code>```

Does anyone know what my mistake is? I have no clue.

I'm running Mac OS Catalina (x86_64-apple-darwin19.0)

答:
Make Len a global variable and change isPrime to this:

```<code>int isPrime(int n) {
  int i = 0;
  int calc_to = ceil(sqrt(n));
  while (Primes[i] < calc_to) {
    if (i >= Len)                 // add this line
    {                             // add this line
      printf("Bummer");           // add this line
      exit(1);                    // add this line
    }                             // add this line
    if (n % Primes[i] == 0) {
      return 0;
    }
    i++;
  }
  return 1;
}
</code>```

You'll notice that at some point i is greater equal than Len, meaning that you're accessing the Primes array out of bounds which leads to undefined behaviour.

Body:
I wrote a simple script to calculate prime numbers but when I compile and run it, I get this error and always after 106747.

...
106727
106739
106747
zsh: segmentation fault  ./a.out 1000000

This is the code:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int *Primes;

int isPrime(int n) {
    int i = 0;
    int calc_to = ceil(sqrt(n));
    while (Primes[i] < calc_to) {
        if (n % Primes[i] == 0) {
            return 0;
        }
        i ++;
    }
    return 1;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
            printf("Usage: ./a.out <Find Till>");
            return 0;
    }

    int Len = 3;
    Primes = malloc(sizeof(int) * Len);
    Primes[0] = 2; Primes[1] = 3;
    printf("2\n3\n");

    int calc_to = atoi(argv[1]);
    for (int n = 4; n < calc_to; n++) {
        if (isPrime(n) == 1) {
                Primes[Len - 1] = n;
                printf("%d\n", n);
                Primes = realloc(Primes, sizeof(int) * Len);
                Len ++;
            }
        }
    free(Primes);
}

Does anyone know what my mistake is? I have no clue.

I'm running Mac OS Catalina (x86_64-apple-darwin19.0)

Body:
Make Len a global variable and change isPrime to this:

int isPrime(int n) {
  int i = 0;
  int calc_to = ceil(sqrt(n));
  while (Primes[i] < calc_to) {
    if (i >= Len)                 // add this line
    {                             // add this line
      printf("Bummer");           // add this line
      exit(1);                    // add this line
    }                             // add this line
    if (n % Primes[i] == 0) {
      return 0;
    }
    i++;
  }
  return 1;
}

You'll notice that at some point i is greater equal than Len, meaning that you're accessing the Primes array out of bounds which leads to undefined behaviour.


问:
Is it possible to subscribe on event when backbonejs view is removed from dom?
Is it possible to subscribe on event when backbonejs view is removed from dom?

I need to handle this to unsubscribe from websocket connection.

答:
What triggers the removal of the view from the DOM?  If the view is managing this removal, whomever created the view or has a reference to the view can register to receive an event that the view can trigger when this DOM removal happens.

I haven't tried it, but you might be able to wire up the DOMNodeRemoved event as an event that the view registers a function for.  You would then bubble this DOM event up through your app for any interested listener to respond to.