text:
Q: Create JWTAuth token in Factory Laravel I have model User and need create db seeder with faker lib, but i have record _token using JWT. Now how to create _token with JWT?
$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'firstName' => $faker->name,
        'lastName' => $faker->name,
        'username' => $faker->unique()->username,
        'email' => $faker->unique()->safeEmail,
        'password' => md5('user123'),
        'bio' => $faker->sentence(3, true),
        'type' => $faker->randomElement(['seller', 'buyer']),
        'birthday' => $faker->dateTimeThisCentury,
        'avatar' => $faker->imageUrl($width = 400, $height = 400),
        'cover' => $faker->imageUrl($width = 851, $height = 315),
        'gender' => $faker->randomElement(['male', 'female']),
        'country' => $faker->country,
        '_token' => JWTAuth::fromUser() // ???,

    ];
});

A: *

*That's not how JWT works.

*How do you expect the library to generate a token for the user when the user itself hasn't been created? The token needs to have at least one claim to identify the user.

*JWT is meant to be used as a non persistent token. They're stored only when you want to blacklist or invalidate tokens.

What you're looking for might be a simple token based authentication and not JWT in this case.


text:
Q: schedule sql job in another server via stored procedure Here is a picture of how things are supposed to work.
I'll log into sql server and manually start jobA. My interaction ends here. This job doesn't have a schedule enabled. Hence it is manually started. It has 3 steps. The 3rd step will execute another job manually (which is on another server). Technically the 3 step should in turn schedule jobA, to run say after 5 minutes (only 1 time).
But how to schedule jobA which is on another server?

A: Maybe it is better for jobB to wait for 5 minutes and then start jobA (without scheduling).
Assuming it is SQL Server 2005 or newer, You can use WAITFOR:
WAITFOR DELAY '00:05';

Or if You insist on scheduling a job using stored procedure, check sp_add_schedule stored procedure.
If You already knew this and focus of your question is on 'another' server, check: How to run a Job from a Stored Procedure in another server?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the explanation for this behavior: ES6 Promise that is never resolved The following code:
Promise.resolve('a string')
  .then(resp => {
    console.log('resp from the initial promise: ' + resp)
    const p0 = new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('finished sleeping in p0')
        resolve('hello from p0')
      }, 5000)
    })
    console.log('returning p0')
    return p0
  })
  .then(resp => {
    console.log('resp from p0: ' + resp)
    const p1 = new Promise((resolve, reject) => {
      console.log('p1 completed')
      // resolve('another string from p1')
    })
    console.log('returning p1')
    return p1
  })
  .then(res => {
    console.log('resp from p1: ' + res)
  })
  .catch(err => {
    console.error('Error: ' + err.message)
  })

console.log('last statement')

When I run that, I get the following output (that doesn't make sense to me)
last statement
resp from the initial promise: a string
returning p0
finished sleeping in p0
resp from p0: hello from p0
p1 completed
returning p1

First of all, since the promise p1 is never resolved, I'd expect the program to just wait forever and never finish. That is not the case and it finishes just fine (albeit without ever getting to the last then()).
Also, it creates the promise and executes the code inside of the promise before the code that comes after it's created. I would expect 'returning p1' to come before 'p1 completed' since I assumed that what's inside the promise would be executed on the next tick.

A:
Also, it creates the promise and executes the code inside of the promise before the code that comes after it's created. I would expect 'returning p1' to come before 'p1 completed' since I assumed that what's inside the promise would be executed on the next tick.

If you call .then on a promise, the function that you pass in will be delayed until the next tick. But the constructor of a promise does not behave that way. When you construct a new Promise, the code that you pass into the constructor is run immediately and synchronously. So this code:
const p0 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('finished sleeping in p0')
    resolve('hello from p0')
  }, 5000)
})
console.log('returning p0')

... will immediately set a timeout, before the promise even gets assigned to p0. And this code:
const p1 = new Promise((resolve, reject) => {
  console.log('p1 completed')
  // resolve('another string from p1')
})
console.log('returning p1')

... will immediately log out 'p1 completed', before the promise even gets assigned to p1.


text:
Q: Java filecopy with the same speed (USB2 -> USB3 on Linux server). What's wrong? I have a very simple file copy in Java. It is copies the DB file about 6 minutes to my external (usb3) HDD.
//First database:
try {
fileInputStream = new FileInputStream(selectedfile);
bufferedInputStream = new BufferedInputStream(fileInputStream);
outputFile = new File("" + chosenDestination);
fileOutputStream = new FileOutputStream(outputFile);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
size = selectedfile.length();
byte[] buffer = new byte[1024 * 6];
dbLabel.setText("Copying Database...");
while ((data = bufferedInputStream.read(buffer)) > 0) {
        bufferedOutputStream.write(buffer, 0, data);
        total += data;
        String percent = "" + total / (size / 100);
        pbar.setValue(Integer.valueOf(percent));
        sizeLabel.setText("(" + total / (1024 * 1024) + " / " + (size / (1024 * 1024)) + " MB) ");
    }
} finally {
     bufferedOutputStream.close();
     fileInputStream.close();
     fileOutputStream.close();
     bufferedInputStream.close();
}

Yesterday I bought a Transcend TS-PDU3 (PCI-E) USB additon card. So my computer and my HDD are able to USB3 too. But when I tried the copyjob, it is copy the file with same speed. It is a Linux server so don't need driver (lspci see it) and I think everything work good so I think the error is in the java code. What buffer size I need to choose for USB3. Is the 6 * 1024 is a small buffer size. Or I need to search the error in elsewhere? Thanks.

A: Provided you use Java 7, you have a much easier way to copy data from one file to another. With NIO, you can do that:
final Path src = Paths.get(selectedFile);
final Path dst = Paths.get(outputFile);

Files.copy(src, dst);

The JVM does a pretty good job at that. If you don't see an improvement from your current code, well... Replace your code with this first, and investigate further. As you said, no specific drivers are needed in theory.


text:
Q: Replace host key automatically on linux I have a script that connects to an SFTP server with the following code:
use Net::SFTP::Foreign;
my %cfg = (
    user        => "$user",
    password    => "$password",
    port        => 22,
    more        => [-o => 'StrictHostKeyChecking no']
);
my $sftp = Net::SFTP::Foreign->new("$host",%cfg);

I am using StrictHostKeyChecking to make sure the script automatically accepts the ssh key.
The issue begins when the server replaces the host key with new one. I get the error: WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
So I have to manually remove the key by running ssh-keygen -R testserver.com
After that the script works fine again.
I am trying to find a way to autmatically replace the key if it changes.
Technically I can run ssh-keygen -R testserver.com every time the script runs, but I do not like that solution.
So far I am not able to a good automated way to replace the key.

A: Add another option that points UserKnownHostsFile to /dev/null should do the trick, not that it's recommend from security perspective ;-)
use Net::SFTP::Foreign;
my %cfg = (
    user        => "$user",
    password    => "$password",
    port        => 22,
    more        => [-o => 'StrictHostKeyChecking=no',
                    -o => 'UserKnownHostsFile=/dev/null']
);
my $sftp = Net::SFTP::Foreign->new("$host",%cfg);


text:
Q: image upload not working on heroku with s3 I'm using the Paperclip gem to handle image uploads on my Rails app. Everything works great in development but when I upload an image on the heroku app I get the "Something went wrong" error. I checked the heroku logs and I don't see any error messages. However, the one difference I noticed between dev and heroku is that the dev logs shows that the "begin..insert into...etc" SQL shows, whereas in heroku the logs don't show any SQL. It doesn't even get to write to the database.
The heroku logs only show the "Parameters" and some commands afterwards:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"****", "show"=>{"name"=>"test", "description"=>"this is a description", "cover"=>#<ActionDispatch::Http::UploadedFile:0x007f3776700fd0 @tempfile=#<Tempfile:/tmp/RackMultipart20140427-2-1431xte>, @original_filename="bc_top.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"show[cover]\"; filename=\"bc_top.png\"\r\nContent-Type: image/png\r\n">, "thumbnail"=>#<ActionDispatch::Http::UploadedFile:0x007f3776700eb8 @tempfile=#<Tempfile:/tmp/RackMultipart20140427-2-al452c>, @original_filename="bc_cover.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"show[thumbnail]\"; filename=\"bc_cover.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Add show"}

Then it shows some other commands but no errors:
Command :: file -b --mime '/tmp/bdccc4601dd7e6aea5035c03817bca8020140427-2-2i17k4.png'
2014-04-27T16:06:34.040235+00:00 app[web.1]: Command :: file -b --mime '/tmp/68aaf40ebdc9b119d96bb0b3ff13118020140427-2-189rb23.png'
2014-04-27T16:06:34.150632+00:00 app[web.1]: Command :: file -b --mime '/tmp/bdccc4601dd7e6aea5035c03817bca8020140427-2-bfdlsj.png'
2014-04-27T16:06:33.966054+00:00 app[web.1]:   vendor/bundle/ruby/2.1.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:60:in `service'
2014-04-27T16:06:33.966069+00:00 app[web.1]: Started POST "/shows" for 76.***.***.** at 2014-04-27 16:06:33 +0000
2014-04-27T16:06:33.966071+00:00 app[web.1]: Processing by ShowsController#create as HTML
2014-04-27T16:06:34.099317+00:00 app[web.1]: Command :: file -b --mime '/tmp/68aaf40ebdc9b119d96bb0b3ff13118020140427-2-5r5s9s.png'
2014-04-27T16:06:34.446474+00:00 heroku[router]: at=info method=POST path=/shows host=app.herokuapp.com request_id=1bc386a4-147c-403a-9b88-55fe488ec4e3 fwd="76.***.***.**" dyno=web.1 connect=2ms service=676ms status=500 bytes=919

I'm completely stumped. No errors! Here are the relevant files:
production.rb
appName::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # Code is not reloaded between requests
  config.cache_classes = true

  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Disable Rails's static asset server (Apache or nginx will already do this)
  config.serve_static_assets = false

  # Compress JavaScripts and CSS
  config.assets.compress = true

  # Don't fallback to assets pipeline if a precompiled asset is missed
  config.assets.compile = true

  # Generate digests for assets URLs
  config.assets.digest = true

  config.assets.precompile = [ /\A[^\/\\]+\.(ccs|js)$/i ]

  # Defaults to nil and saved in location specified by config.assets.prefix
  # config.assets.manifest = YOUR_PATH

  # Specifies the header that your server uses for sending files
  # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # See everything in the log (default is :info)
  # config.log_level = :debug

  # Prepend all log lines with the following tags
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"

  # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
  # config.assets.precompile += %w( search.js )

  # Disable delivery errors, bad email addresses will be ignored
  # config.action_mailer.raise_delivery_errors = false

  # Enable threaded mode
  # config.threadsafe!

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify

  # Log the query plan for queries taking more than this (works
  # with SQLite, MySQL, and PostgreSQL)
  # config.active_record.auto_explain_threshold_in_seconds = 0.5

  # config/environments/production.rb
  config.paperclip_defaults = {
  :storage => :s3,
  :s3_credentials => {
    :bucket => ENV['AWS_BUCKET'],
    :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
    :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
  }
}

end

application.rb
require File.expand_path('../boot', __FILE__)

require 'rails/all'

if defined?(Bundler)
  # If you precompile assets before deploying to production, use this line
  Bundler.require(*Rails.groups(:assets => %w(development test)))
  # If you want your assets lazily compiled in production, use this line
  # Bundler.require(:default, :assets, Rails.env)
end

module appName
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/extras)

    # Only load the plugins named here, in the order given (default is alphabetical).
    # :all can be used as a placeholder for all plugins not explicitly named.
    # config.plugins = [ :exception_notification, :ssl_requirement, :all ]

    # Activate observers that should always be running.
    # config.active_record.observers = :cacher, :garbage_collector, :forum_observer

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de

    # Configure the default encoding used in templates for Ruby 1.9.
    config.encoding = "utf-8"

    # Configure sensitive parameters which will be filtered from the log file.
    config.filter_parameters += [:password]

    # Enable escaping HTML in JSON.
    config.active_support.escape_html_entities_in_json = true

    # Use SQL instead of Active Record's schema dumper when creating the database.
    # This is necessary if your schema can't be completely dumped by the schema dumper,
    # like if you have constraints or database-specific column types
    # config.active_record.schema_format = :sql

    # Enforce whitelist mode for mass assignment.
    # This will create an empty whitelist of attributes available for mass-assignment for all models
    # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
    # parameters by using an attr_accessible or attr_protected declaration.
    config.active_record.whitelist_attributes = true

    # Enable the asset pipeline
    config.assets.enabled = true

    # Version of your assets, change this if you want to expire all your assets
    config.assets.version = '1.0'

    config.serve_static_assets = true

  end
end

initializer/paperclip.rb
Paperclip::Attachment.default_options[:storage] = :s3
Paperclip::Attachment.default_options[:s3_protocol] = 'http'
Paperclip::Attachment.default_options[:s3_credentials] =
  { :bucket => ENV['AWS_BUCKET'],
    :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
    :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'] }

Show model (object with the file attachments)
class Show < ActiveRecord::Base
    has_many :episodes

    has_attached_file :thumbnail
    validates_attachment_content_type :thumbnail, :content_type => /\Aimage\/.*\Z/

    has_attached_file :cover
    validates_attachment_content_type :cover, :content_type => /\Aimage\/.*\Z/
end

I double checked my heroku config vars and they match up fine. I have this working on a different Rails 3 app and I'm wondering if I am missing something on this new Rails 4 app. Any ideas?
Thanks!

A: Heroku logs don't always help.
For your purposes since you're just getting started I would recommend setting your heroku app to "development" mode so you can see verbose error messages.
heroku config # Should return a list of your current environment, including RACK_ENV=production
heroku config:add RACK_ENV=development # now you'll get verbose error messages
heroku config:add RACK_ENV=production # set this back when you're done debugging

Check out the logs and tell us what you see.
But I would recommend that you use direct upload to S3. I've written about uploading images to S3 over here (http://blog.jobspire.net/uploading-images-to-heroku/). So do take a look.
Also Heroku has a read-only filesystem. That means Paperclip cannot save uploaded files to any place within Heroku. That might be the issue.

If you would like to be able to upload files to an application hosted
  on Heroku, then you must either store the files as binary blobs within
  your database or you must use a separate service to store the files.
  If you are looking for a separate service, Paperclip has built-in
  support for integrating with Amazon S3.

See the relevant Heroku docs.


text:
Q: Ansible loop JSON array contains objects and replace each found element in JSON in file i have this JSON :
[{
        "${foo1}": "somevalue1",
        "${foo2}": "somevalue2"
    }, {
        "${zoo1}": "somevalue111",
        "${zoo2}": "somevalue222"
}]

In which i need to loop over in ansible and each object in the JSON array each key / pair value
I like to check if the key exists in the file and replace it with the value .
For example:
if in the file i have
key1=${foo1}

it will be replaced with
key1=somevalue1

i use to have hard coded ansible task :
replace:
    path: "/myfile.txt"
    regexp: "{{ item.regexp }}"
    replace: "{{ item.replace }}"
  with_items:
    - { regexp: '${foo1}', replace: "new_value" }

i like to convert it to dynamically search and replace according to the given JSON
i capture the JSON like this : ( this is trim down YAML )
---
-
  gather_facts: false
  hosts: localhost
  name: test
  tasks:
    - name: debug
      debug:
        msg: "{{ AAA| to_json }}"
    - name: set fact
      set_fact:
         multi_parms: "{{ AAA| to_json }}"
    - name: debug multi_parms
      debug:
        var: multi_parms

A: Read the JSON file into a single dictionary, e.g.
    - set_fact:
        my_data: "{{ my_data|d({})|combine(item) }}"
      loop: "{{ lookup('file', 'test.json') }}"

gives
  my_data:
    ${foo1}: somevalue1
    ${foo2}: somevalue2
    ${zoo1}: somevalue111
    ${zoo2}: somevalue222

Given an INI file, e.g.
shell> cat conf.ini
key1=${foo1}
key2=${foo2}
key3=xyz

parse the configuration into a dictionary, e.g.
    - set_fact:
        my_ini: "{{ dict(_keys|zip(_vals)) }}"
      vars:
        _lines: "{{ lookup('file', 'conf.ini').splitlines() }}"
        _regex: '^(.*)=(.*)$'
        _keys: "{{ _lines|map('regex_replace', _regex, '\\1') }}"
        _vals: "{{ _lines|map('regex_replace', _regex, '\\2') }}"

gives
  my_ini:
    key1: ${foo1}
    key2: ${foo2}
    key3: xyz

Then use the module ini_file to substitute the data, e.g.
    - ini_file:
        path: conf.ini
        section:
        option: "{{ item }}"
        value: "{{ my_data[my_ini[item]] }}"
        no_extra_spaces: true
      loop: "{{ my_ini|list }}"
      when: my_ini[item] in my_data

gives
shell> cat conf.ini
key1=somevalue1
key2=somevalue2
key3=xyz

Q: "How can I do the search and replace in the destination file?"
A: See below the "--diff" output of each iteration.
TASK [ini_file] ***************************************************
--- before: conf.ini (content)
+++ after: conf.ini (content)
@@ -1,3 +1,3 @@
-key1=${foo1}
+key1=somevalue1
 key2=${foo2}
 key3=xyz

changed: [localhost] => (item=key1)
--- before: conf.ini (content)
+++ after: conf.ini (content)
@@ -1,3 +1,3 @@
 key1=${foo1}
-key2=${foo2}
+key2=somevalue2
 key3=xyz

changed: [localhost] => (item=key2)
skipping: [localhost] => (item=key3)

A: this code in j2 template
  {% for  item in json_data %}
    {% for k, v in item.items() %}

      key{{loop.index}}  =  {{ v }}

     {% endfor %}
   {% endfor %}

gets you this result
  key1  =  somevalue1

   key2  =  somevalue2

   key1  =  somevalue111

  key2  =  somevalue222

is this what you were looking for?


text:
Q: Why does my sql statment return the same output multiple times Hell everyone.
I made a sql statment that returns me the name of a teacher, the time he has to attend the class and what type of class he is giving. My statement returns what i expect but it returns the same answer multiple time, why is that ? I don't quite undersand it.
Here is my statement
SELECT
`profile`.`name`,
`profile`.nachname,
unterichts_zeit.zeit,
unterichts_typ.typ
FROM
unterichts_zeit
INNER JOIN `profile` ON unterichts_zeit.lehrer = `profile`.id ,
unterichts_typ

And my output
teacher1    teacher1    9:35    klavier
teacher2    teacher2    10:35   klavier
teacher1    teacher1    9:35    gittare
teacher2    teacher2    10:35   gittare
teacher1    teacher1    9:35    generell
teacher2    teacher2    10:35   generell
teacher1    teacher1    9:35    schlagzeug
teacher2    teacher2    10:35   schlagzeug
teacher1    teacher1    9:35    trombone
teacher2    teacher2    10:35   trombone
teacher1    teacher1    9:35    generell
teacher2    teacher2    10:35   generell

Seeing this now it also doesnt really display what i want ...
it display every type of class which is not correct obv... damn
if anyone has an idea how i can solve this
thank you

A: You've mixed your join styles and created a Cartesian product. A Cartesian product is where the number of rows grows because unrelated rows are joined together. Sometimes it is useful, but usually it is not what is required
At the very end of your sql statement you have a comma and then another table name
The database has taken the work it already did with the INNER JOINed pair of tables and then just combined every row from them with every row from this table
If you intend to join 3 tables together use another inner join statement
SELECT
`profile`.`name`,
`profile`.nachname,
unterichts_zeit.zeit,
unterichts_typ.typ
FROM
unterichts_zeit
INNER JOIN `profile` ON unterichts_zeit.lehrer = `profile`.id
INNER JOIN unterichts_typ ON <<fill-this-on-clause-out>>

In the old days we joined tables like this:
SELECT *
FROM a, b, c
WHERE a.id = b.id AND b.id = c.id

If you left off the WHERE clause the db would just output every row combination. If A contained 1 and 2 and B contained "x" and "y" and c contained true and false you'd get:
1,x,true
1,x,false
1,y,true
1,y,false
2,x,true
2,x,false
2,y,true
2,y,false

Now the modern equivalent is to use INNER JOIN, and it's a lot harder to forget the ON clause (equivalent of the old way using the where clause) because it's a syntax error to do so. But db still allow the old way too and even allow mixing. Your statement having "comma tablename" at the end is a mixed join style, old way of producing a Cartesian product (forgotten where clause)


text:
Q: Execute a sqoop command using processbuilder in java I have a working sqoop command which imports data from oracle to hive.
When i am trying to run the sqoop command using the process builder API it is giving

java.io.IOException: error=2, No such file or directory

The same command works without any issues when executing it from the shell. Please let me know how to resolve this.
I also tried splitting the command into array of strings as well as list of strings. But, the two approaches did not work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class SqoopTest {
    static ProcessBuilder processBuilder = null;
    static Process spawnProcess = null;
    static int exitValue;
    static int pid;
    static List<String> commands;

    public static void main(String[] args) {

      runSqoop();

    }

    /*
     * Executes the shell script with a series of sqoop commands.
     *
     *
     *
     * sqoop import -D mapred.child.java.opts='\-Djava.security.egd=file:/dev/../dev/urandom'
     * --connect 'jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))'
     * --username XXCSS_O --password "c******3" --split-by LINE_ITEM_ID -m 10
     * --query "select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \$CONDITIONS AND lid_date > to_date('2016-10-13 03:04:18','MM/dd/yyyy hh24:mi:ss') and lid_date <= to_date('2016-10-13 03:04:18','MM/dd/yyyy hh24:mi:ss')"
     * --map-column-hive LINE_ITEM_ID=BIGINT,LIST_PRICE=BIGINT,SERVICE_VALUE=BIGINT
     * --null-string '\\\\N' --null-non-string '\\\\N' --hcatalog-home
     * /opt/mapr/hive/hive-1.2/hcatalog --hcatalog-table XXCSS_KTN_REQ_LINE_DETAIL --hcatalog-database frameworks_dataingestion
     *
     */
    public static void runSqoop() {
        commands = new ArrayList<String>();
        commands.add("sqoop import -D mapred.child.java.opts=\'\\-Djava.security.egd=file:/dev/../dev/urandom\' --connect \'jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))\' --username XXCSS_O --password \"c*****3\" --split-by LINE_ITEM_ID -m 10 --query \"select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \\$CONDITIONS AND lid_date > to_date(\'2016-10-13 00:00:00\',\'yyyy-MM-dd hh24:mi:ss\') and lid_date <= to_date(\'2016-10-13 03:04:18\',\'yyyy-MM-dd hh24:mi:ss\')\" --map-column-hive LINE_ITEM_ID=BIGINT,LIST_PRICE=BIGINT,SERVICE_VALUE=BIGINT --null-string '\\\\N' --null-non-string '\\\\N' --hcatalog-home /opt/mapr/hive/hive-1.2/hcatalog --hcatalog-table XXCSS_KTN_REQ_LINE_DETAIL --hcatalog-database frameworks_dataingestion");
        processBuilder = new ProcessBuilder(commands);
        try {
            System.out.println("Executing " + commands.toString());
            spawnProcess = processBuilder.start();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(spawnProcess.getErrorStream()));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ( (line = reader.readLine()) != null) {
               builder.append(line);
               builder.append(System.getProperty("line.separator"));
            }
            String result = builder.toString();
            System.out.println(result);
            try {
                exitValue = spawnProcess.waitFor();
                pid = getPID(spawnProcess);
                System.out.println("The PID is " + pid);
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            System.out.println("Process exited with the status :" + exitValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * Retrieves the process id of the executed command.
     *
     * @param process the executed process
     *
     * @return PID
     */

    public static int getPID(Process process) {
        try {
            Class<?> processImplClass = process.getClass();
            Field fpid = processImplClass.getDeclaredField("pid");
            if (!fpid.isAccessible()) {
                fpid.setAccessible(true);
            }
            return fpid.getInt(process);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return -1;
        }
    }

    /*
     * Retrieves the current java process id
     *
     * @return java process ID
     */

//  @SuppressWarnings("restriction")
//  public static int getCurrentJavaPID() {
//      int jvmpid = 0;
//      java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
//      try {
//          java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
//          jvm.setAccessible(true);
//          sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
//          java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
//          pid_method.setAccessible(true);
//
//          jvmpid = (Integer) pid_method.invoke(mgmt);
//      } catch (Exception e) {
//          e.getMessage();
//      }
//      return jvmpid;
//  }

}

Note: for security concerns i have replaced the ip addresses and passwords with dummy variables.
Tried passing the command as a string array. But, it doesnt recognize the JDBC Connection string
public static void runSqoop() {
        String[] commands = {"sqoop","import","-D mapred.child.java.opts=\'\\-Djava.security.egd=file:/dev/../dev/urandom\'","--connect", "\'jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.370)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))\'","--username","XXCSS_O","--password","\"c***3\"", "--split-by","LINE_ITEM_ID","-m","10","--query","\"select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \\$CONDITIONS AND lid_date > to_date(\'2016-10-13 00:00:00\',\'yyyy-MM-dd hh24:mi:ss\') and lid_date <= to_date(\'2016-10-13 03:04:18\',\'yyyy-MM-dd hh24:mi:ss\')\"","--null-string","'\\\\N'","--null-non-string","'\\\\N'","--hcatalog-home","/opt/mapr/hive/hive-1.2/hcatalog","--hcatalog-table","XXCSS_KTN_REQ_LINE_DETAIL","--hcatalog-database","frameworks_dataingestion"};
        processBuilder = new ProcessBuilder(commands);
        try {
            System.out.println("Executing " + commands.toString());
            spawnProcess = processBuilder.start();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(spawnProcess.getErrorStream()));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ( (line = reader.readLine()) != null) {
               builder.append(line);
               builder.append(System.getProperty("line.separator"));
            }
            String result = builder.toString();
            System.out.println(result);
            try {
                exitValue = spawnProcess.waitFor();
                pid = getPID(spawnProcess);
                System.out.println("The PID is " + pid);
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            System.out.println("Process exited with the status :" + exitValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Stack trace:

cat: /opt/mapr/zookeeper/zookeeperversion: No such file or directory
  16/10/25 07:41:12 INFO sqoop.Sqoop: Running Sqoop version:
  1.4.6-mapr-1609 16/10/25 07:41:12 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P
  instead. 16/10/25 07:41:13 ERROR tool.BaseSqoopTool: Got error
  creating database manager: java.io.IOException: No manager for connect
  string:
  'jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))'
          at org.apache.sqoop.ConnFactory.getManager(ConnFactory.java:191)
          at org.apache.sqoop.tool.BaseSqoopTool.init(BaseSqoopTool.java:256)
          at org.apache.sqoop.tool.ImportTool.init(ImportTool.java:89)
          at org.apache.sqoop.tool.ImportTool.run(ImportTool.java:593)
          at org.apache.sqoop.Sqoop.run(Sqoop.java:143)
          at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
          at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:179)
          at org.apache.sqoop.Sqoop.runTool(Sqoop.java:218)
          at org.apache.sqoop.Sqoop.runTool(Sqoop.java:227)
          at org.apache.sqoop.Sqoop.main(Sqoop.java:236)

A: You have to provide commands and args separately as like below
  Process p = new ProcessBuilder("myCommand", "myArg").start();

OR
    ProcessBuilder pb =
       new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.start();

Here is a example


text:
Q: node-mongodb-native - cursor returns null as last value during an each call So. I have a very basic script, that connects to a database and does a find on a collection that has a lot of documents and limit it to 3 items. Everything runs smoothly except that at the end of my results, a null and the script doesn't terminate instead of closing the connection quietly after having succeedeed.
Here I declare my params and create my database object:
var SERVER = 'localhost',
 PORT = 27017,
 DATABASE = 'test',
 COLLECTION = 'coll',
 mongo = require('mongodb'),
 db = new mongo.Db(DATABASE,
  new mongo.Server(SERVER, PORT, {auto_reconnect: true}),
  {});

And here I connect to the database and proceed to query it with a find cursor and the each function:
db.open(function(err, db) {
 if(err) throw err;
 var collection = new mongo.Collection(db, COLLECTION),
  cursor = collection.find({}, {}).limit(3);
 cursor.each(function(err, doc) {
  if(err) throw err;
  console.log(doc);
 });
 db.close();
});

Results are nice:
{ _id: '1',
  a: 'first object' }
{ _id: '2',
  a: 'second object' }
{ _id: '3',
  a: 'third object' }

up until the point where a
null

appears.
As precised above, the script then proceeds not to terminate.
I don't get why and would appreciate pointers on how to make it terminate nicely.

A: Well, that was stupid. Too much time without programming in an async setup and you make mistakes: the db.close() call came before the each looping was over. Returned null and hanged because of that. Here is the correct code:
db.open(function(err, db) {
 if(err) throw err;
 var collection = new mongo.Collection(db, COLLECTION),
  cursor = collection.find({}, {}).limit(3);
 cursor.each(function(err, doc) {
  if(err) throw err;
  if(doc !== null) console.log(doc);
  else db.close();
 });
});

I hope it'll save some minutes to someone, somehow.

A: This question's a few years old, and already has a possible answer, but I just wanted to point out another possibility for anyone who's still confused after reading this. Turns out, each repeatedly calls nextObject which actually is intended to return null when the cursor is exhausted.
The answer here was the one I needed: Node Mongo Native - how to tell when a cursor is exhausted?
From the Node MongoDB driver docs: http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#nextobject


text:
Q: Dedekind Sum Congruences For $a,b,c \in \mathbb{N}$, let $a^{\prime} = \gcd(b,c)$, $b^{\prime} = \gcd(a,c)$, $c^{\prime} = \gcd(a,b)$ and $d = a^{\prime} b^{\prime} c^{\prime}$. Define $\mathfrak{S}(a,b,c) =  a^{\prime} \mathfrak{s}( \tfrac{bc}{d}, \tfrac{a}{b^{\prime} c^{\prime}}) +   b^{\prime} \mathfrak{s}( \tfrac{ac}{d}, \tfrac{b}{a^{\prime} c^{\prime}}) + c^{\prime} \mathfrak{s}( \tfrac{ab}{d}, \tfrac{c }{a^{\prime} b^{\prime}} )$, where $\mathfrak{s}$ is the Dedekind sum. I can prove the following: For $a, b, c \in \mathbb{N}$ with $\gcd(a,b,c) = 1$,
\begin{align}
12 a b c \ \mathfrak{S}(a,b,c) \equiv (ab)^{2} + (bc)^{2} + (ca)^{2} + d^{2}  \ \pmod{a b c}.
\end{align}
Is this congruence in the literature? I'm aware of the 3-term generalization of Rademacher and Pommersheim and of the work of Beck on the Carlitz-Dedekind Sums, but these don't seem to include this particular congruence as a special case.
I generalize. For $a_{1}, \dots, a_{n} \in \mathbb{N}$ such that $\gcd(a_1, \dots, a_{n}) = 1$, let $a_{i}^{\prime} = \gcd(a_{1}, \dots, \hat{a}_{i}, \dots, a_{n})$. Define the symmetric summation
$$
\mathfrak{S}(a_{1},\dots, a_{n}) = \sum_{i = 1}^{n} a_{i}^{\prime} \, \mathfrak{s}\left( \tfrac{a_{1} \cdots \hat{a}_{i} \cdots a_{n}}{a_{n+1}},  \tfrac{a_{i}}{a_{1}^{\prime} \cdots \hat{a}_{i}^{\prime} \cdots a_{n}^{\prime}} \right).
$$
where $\hat{}$ denotes omission. For pairwise coprime $a_{1}, \dots, a_{n} \in \mathbb{N}$ (all primed variables equal $1$), I conjecture the following congruence holds for $n = 4$ (and I have a hunch that it continues to hold for $n > 4$):
$$
12 a_{1} \cdots a_{n} \, \mathfrak{S}(a_{1}, \dots, a_{n}) \equiv \left( \sum_{i = 1}^{n} (a_{1} \cdots \hat{a}_{i} \cdots a_{n})^{2} \right) + 1 \ \pmod{a_{1} \cdots a_{n}}.
$$
Is this more general congruence known?


text:
Q: Unable to Connect to Box API in R all. I am trying to set up boxr to read files from Box's API.
The set up seems pretty simple. I created a Box app. I then copy/pasted the client secret and client ID into box_auth()
library(boxr)
box_auth(client_id = "<placeholder>", client_secret = "<placeholder>")

When I do this I am taken to a new page that says:
There seems to be a problem with this app.

Error: redirect_uri_mismatch

Because there are so few steps, I am a little lost on what could be going wrong.
Advice is appreciated.

A: Ran into this same issue after months of boxr working as expected - the steps and explanation outlined here resolved the issue on my end.
Going to the dev console for your Box account, and then to the "Configuration" tab, add http://localhost:1410/ as a Redirect URI:


text:
Q: Adicionar linha RichText Delphi Boa tarde
Tenho um aplicativo que o texto tem que ter Negrito, italico e sublinhado por isso estou usando um TRichText. Até aqui tudo bem
Para o mesmo funcionar na impressão eu fiz RTRLrichText que recebe os valores do TRichText.
Porém... se eu inserir linhas em brancos para que o texto aparece do meio ou para o fim da pagina na visualização e na impressão não sai como na tela. Ou seja não consigo add linhas.
Alguém sabe como ?

A: Experimente assim:
Richedit1.SelAttributes.Color:=clBLue; // Cor Azul
Richedit1.SelAttributes.Style:=[fsBold,fsUnderline]; // Negrito e sublinhado
Richedit1.Lines.Add('Linha'); // Adiciona linha
Richedit1.SelAttributes.Style:=[]; // Volta ao estilo normal
Richedit1.SelAttributes.Color:=clBlack; // Volta à cor normal

Achei isso em um site


text:
Q: how to connection establish with both database from different database oracle and mysql in yii2 Actually i create a application and
please someone say me. how to establish connection with mysql and different oracle server.
and how to update if update my mysql field so automatic update my oracle erp system.

A: Follow the link that @Paritosh Mahale has commented up:
Multiple database connections and Yii 2.0
as regards the part of updating the fields in a database you can use migrations in these ways:
/yiic migrate                 # The default component db
/yiic migrate --db=db1        # Connection db component mysql
/yiic migrate --db=db2        # Connection oracle component db

and you need to run the same migration command on both databases with different option --db.
Or you can override the init() method of yii\db\Migration:
<?php

use yii\db\Migration;

class m150101_185401_create_news_table extends Migration
{
    public function init()
    {
        $this->db = 'db2';
        parent::init();
    }
}

and use like this: /yiic migrate
This migration will be applied to db2.
If you have multiple migrations that use the same database, it is recommended that you create a base migration class with the above init() code. Then each migration class can extend from this base class.
If you want to have separated path of migrations for each database connections you can do like this:
yii migrate --migrationPath=@app/migrations/db1 --db=db1
yii migrate --migrationPath=@app/migrations/db2 --db=db2
...

For apply migrations "automatic" in each database in one command you can (just an idea) extend yii\console\controllers\MigrateController class and add a property public $dbs. After you can add that property to options() so when you call the migrate command you can pass a param like this:
/yiic migrate --dbs=db1,db2

and so you can manage that parameter for executing a migration for each $dbs;
[Edit]
Some parts of the answer were taken from here: Migrating Multiple Databases

A: Use Paritosh Mahale link. Assume you have OracleModel with getDb() returning oracle connection and MySql model with getDb() returning mysql connection. Then in MySql model define afterSave event hendler:
public function afterSave()
{
    $oracleModel = OracleModel::findOne(/* condition */);
    $oracleModel->someField = 123;
    $oracleModel->save();
}


text:
Q: Samsung Series 5 getting hot I've just installed Ubuntu 12.04.02 64bit on my Samsung however I noticed it is getting too hot :(
It has 2 VGAs (Intel HD4000 & Nvidia GT 630M 2GB) however I'm using only Intel. At least the nvidia* drivers are not loaded.
Any idea?
Thanks!

A: I had a similar problem on my Dell Studio XPS laptop with Ubuntu 11.04. Basically the kernel didn't have proper control of the CPU, and it would heat up very quickly unnecessarily. Once 12.04 came out, the fixes were there to solve the issue, and I no longer had to drag my fan around with me! Unfortunatly I don't know enough to point you in the direction of what exactly the issue is, but if you report the bug I'm sure someone will be able to get to the bottom of it!


text:
Q: Trying to use clock_gettime(), but getting plenty of "undeclared" errors from time.h I am trying to measure the running time of a function using clock_gettime(). I am including time.h, I added -lrt to the Makefile, and added the right path on Eclipse CDT. However, when I try to compile I keep getting these kinds of errors:
experiments.c: In function 'main':
experiments.c:137:2: error: unknown type name 'timespec'
timespec time1, time2;
^
experiments.c:139:2: warning: implicit declaration of function 'clock_gettime' [-Wimplicit-function-declaration]
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
^
experiments.c:139:16: error: 'CLOCK_PROCESS_CPUTIME_ID' undeclared
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);

This happens with any type of CLOCK_ I try to use. I've been reading plenty of questions/answers and tutorials but haven't been able to find something that helps.
The headers I'm including are:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

I'm on Ubuntu 13.10 32 bit and compiling on gcc with the following CFLAGS: -g -Wall -pedantic -std=c99
If I add the flag -D_POSIX_C_SOURCE=199309L I get error: unknown type name 'timespec' and warnings about using timespec.
This is the part of the code, just in case it helps:
timespec time1, time2;
int temp;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
.
.
.
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
/*code stuff*/
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);

Thanks

A: Putting this and this answers together I was able to make it work. I had to add the _POSIX_C_SOURCE macro, to make sure the preprocessor was getting the library features correctly, which I did by adding this line before all my includes:
#define _POSIX_C_SOURCE 199309L

Then I started getting a unknown type name timespec error, which was happening because you have to tell the compiler explicitly that timespec is a struct. Fixed it by writing:
struct timespec time1, time2;

instead of just timespec time1, time2;.


text:
Q: Making predictions when model.matrix row count differs from the test data frame in neuralnet I recently asked the following question about the error requires numeric/complex matrix/vector arguments when working with the neuralnet library. Here is my original question: "Working with neuralnet in R for the first time: get "requires numeric/complex matrix/vector arguments" but don't know how to correct".
The solution was to convert the factors in my data frame to "dummy" variables using the model.matrix function. The resulting code was the following:
matrix.train <- model.matrix(
  ~ survived + pclass + sex + age + sibsp + parch + fare + embarked,
  data = train
)

Because my source data frame is peppered throughout with a number of individual NA values, the resulting matrix ends up with 714 rows rather than the 891 rows of the original data frame.
This is OK for my training data. However, when I load my test data frame and convert it to a matrix, I run into the same issue. This time I get 331 matrix rows vs the 418 rows in my source data frame.
After I compute, applying the model to my test data, I'm unable to cbind my predictions back to my test data because the row counts are different. So, my question is:
Is there a way to force model.matrix to output the same number of rows as the source data frame, ignoring NA cases? My model will need to be able to handle NA and still output a prediction because encountering a row with at least one NA is common. Alternately, would it be better to tell the neuralnet to treat NA values as valid factors?
Here is the code I've been attempting to use so far:
#Build a matrix from training data (714 rows vs 891 rows due to NAs in data)
matrix.train <- model.matrix(
  ~ survived + pclass + sex + age + sibsp + parch + fare + embarked,
  data=train
)

library(neuralnet)

#Train the neural net
net <- neuralnet(
  survived ~ pclass + sexmale + age + sibsp + parch + fare + embarkedC +
  embarkedQ + embarkedS, data=matrix.train, hidden=10, threshold=0.01
)

#Build a matrix from test data (331 rows vs 418 rows due to NAs in data)
matrix.test <- model.matrix(~ pclass + sex + age + sibsp + parch + fare + embarked,
  data=test
)

#Apply neural net to test matrix
net.results <- compute(
  net, matrix.test
)

#Attempt to map results back to original test data
cleanoutput <- cbind(
  net.results$net.result,test
)

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 331, 418

When I try to use the rownames from the train data frame to force the matrix.model matrix into the same row count I get the following:
matrix.train <- matrix.train[match(rownames(train),rownames(matrix.train)),]

> matrix.train
    (Intercept) survived pclass sexmale   age sibsp parch     fare embarkedC embarkedQ embarkedS
1             1        0      3       1 22.00     1     0   7.2500         0         0         1
2             1        1      1       0 38.00     1     0  71.2833         1         0         0
3             1        1      3       0 26.00     0     0   7.9250         0         0         1
4             1        1      1       0 35.00     1     0  53.1000         0         0         1
5             1        0      3       1 35.00     0     0   8.0500         0         0         1
6            NA       NA     NA      NA    NA    NA    NA       NA        NA        NA        NA
7             1        0      1       1 54.00     0     0  51.8625         0         0         1

However, that row of NAs is inaccurate. In fact, there may only be one NA value in that row but for some reason whenever one NA value is listed in the row the matrix turns the whole row into NAs. Instead of the above, this is what I would like to see:
> matrix.train
    (Intercept) survived pclass sexmale   age sibsp parch     fare embarkedC embarkedQ embarkedS
1             1        0      3       1 22.00     1     0   7.2500         0         0           1
2             1        1      1       0 38.00     1     0  71.2833         1         0         0
3             1        1      3       0 26.00     0     0   7.9250         0         0         1
4             1        1      1       0 35.00     1     0  53.1000         0         0         1
5             1        0      3       1 35.00     0     0   8.0500         0         0         1
6             1        0      3       1 NA        0     0   6.25           1         0        NA
7             1        0      1       1 54.00     0     0  51.8625         0         0         1


text:
Q: tdd - how to test whether User.Identity.Name appears in razor view I am trying to unit test a razor view (MVC .NET). I want to test whether the user logged in's name appears on the site. I am not sure how will I do this due to User.Identity.Name - this is a static object, so can't be mocked.
Should this static object be set in the test? Is there a nicer way of doing this?
Thanks!

A: You could create create a ControllerContext with a mock HttpContext to return an IPrincipal to your liking. See this post on how to do that:
Mocking and HttpContextBase.get_User()
The example uses Rhino Mocks, but is easily adaptable to whatever mock framework you are using. Make sure that the fake IPrincipal.Identity.Name returns a string for the name. I can give you an example with FakeItEasy or Rhino Mocks if you think its not clear.
You can then assert that the user name placed in the ViewBag or in the ViewModel for your view is equal to the name you let your fake IIdentity return.


text:
Q: Reusing part of the query with joins I need to implement 3 public methods that all rely on the same initial join. Would a solution like the one described below work?
The code below is an example, the real stuff is much more complicated, that's why I want to reuse it.
private Tuple<Customer,Order> GetCustomerOrders()
{
    from c in customers
    join o in orders
        on c.customerid equals o.customerid
    select Tuple.Create(c, o)
}

public MyCustomerOrder GetCustomerOrder(int customerId)
{
    return (from co in GetCustomerOrders()
    where co.Item1.customerid == customerId
    select new MyCustomerOrder(co.Item1, co.Item2)).FirstOrDefault();
}

public IEnumerable<MyCustomerOrder> GetCustomerOrders()
{
    return from co in GetCustomerOrders()
    orderby co.Item1.Name
    select new MyCustomerOrder(co.Item1, co.Item2);
}

The question is, does the tuple break the query? In other words, will this end up in the SQL query that gets generated where co.Item1.customerid == customerId?

A: It really depends on whether LINQ to SQL understands the point of Tuple.Create. I suspect that it does in .NET 4.0 - but the only way to find out is to try it.
It certainly makes conceptual sense, and composability is part of the goal of LINQ - which is why I'd hope it's supported. Effectively it's just like using an anonymous type, except you get to "export" the type information out of the method, which is the point of Tuple.


text:
Q: FeynCalc Kronecker delta contraction I want to simplify some expressions like a[i]*b[i]*KD[i,j]. After contraction, it should be a[j]*b[j], but it seems that FeynCalc cannot handle more than 3 of the same CartesianIndices.
I know for contraction it is not well defined. But what I just want to do is symbolically change a[i]*b[i] to a[j]*b[j]

A: Sorry, but this is not going to work. FeynCalc inherently relies on Einstein's summation convention, so every attempt to use the program on expressions violating it will generate inconsistent or simply wrong output.
What you will get for your input is, in fact, a[j] b[i] and not a[j] b[j]
DataType[a, FCTensor] = True;
DataType[b, FCTensor] = True;
a[CartesianIndex[i]]*b[CartesianIndex[i]]*KD[i, j]
% // Contract


text:
Q: how to remove class with a link that created with jquery html function I want that class remove from an element, when click on a link, that created with jquery html function
here is an example:
//script
  $("#test").click(function(){
       $("#body").html("removeclass");
    });
   $("#removeclass").click(function(){
      $("#test").removeClass("anClass");
    });

//html

<button id="test" class="anClass">Test</button>

A: $("#test").on('click',  function() {
       $("#body").html("removeclass");
});
$("#removeclass").live('click',  function() {
        $("#test").removeClass("anClass");
});


text:
Q: Django Formset vs Modelform I am a bit confused. I know that by using Formset we could generate multiple form. Aside from that , when should I use Formset or Modelform?

A: ModelForms are used to automatically create forms based on a single model instance.
If you don't have a model instance (and don't want to create one), but just want to handle arbitrary data, use a plain old form.
If you have lists of data that you need to get, whether as Models or data, FormSets are the answer.
FormSets are used to automatically manage lists of forms. You don't want to handle each form separately unless you need to. A FormSet can also use ModelForms, Yeah!


text:
Q: PushViewController to navigate to next stack I am new to IOS .what I am doing is I just simply placed a UIButton on my main view and I want when I click on that button i t should take me to the next stack . for that what I am doing is
-(IBAction)stack:(id)sender{
 Page1 *button =[[Page1 alloc]init];
 [self.navigationController pushViewController:button animated:YES];
}

I simply add this in my code ...but it is not working.
Do I need to put UINavigationController in main view or in AppDelegate to press button and create new stack with navigation

A: in AppDelegate,
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:self.viewController];

and change your button press method,
-(IBAction)stack:(id)sender{
    Page1 *button =[[Page1 alloc] initWithNibName:@"Page1" bundle:nil];
    [self.navigationController pushViewController:button animated:YES];
}

A: Try this
-(void)aboutButtonPressed {
    AboutViewController *aboutView =[[AboutViewController alloc] initWithNibName:@"About" bundle:nil];
    [self.navigationController pushViewController:aboutView animated:YES];
    [aboutView release];
}

A: Yes you need to write following lines in appdel
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
navigationController=[[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = navigationController;

A: Please do the following thing:
In AppDelegate.h
@property (nonatomic, retain) UINavigationController *navigationController;

In AppDelegate.m
@implementation AppDelegate

@synthesize navigationController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
    } else {
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
    }
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];

    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

and when you want to push the next viewcontroller , you can write the above code :
-(void)fontButtonPress{
      FontViewController *fontViewController = [[FontViewController alloc]  initWithNibName:@"FontViewController_iPhone" bundle:nil];
  [self.navigationController pushViewController:fontViewController animated:YES];
}

Let Me know if You have any issue.
Thanks


text:
Q: json_serializable - generate fromJson and toJson on abstract base class and its concrete children When I run the build runner on this class:
@freezed
@ReactiveFormAnnotation()
class Search with _$Search {
  factory Search(
      {@FormControlAnnotation() required Suggestion? search,
      @JsonKey(ignore: true) Ref? provider}) = _Search;

  const Search._();

  factory Search.fromJson(Map<String, dynamic> json) => _$SearchFromJson(json);
}

I get:

[SEVERE] json_serializable:json_serializable on
lib/src/presentation/pages/find/form_definition.dart:
Could not generate fromJson code for search. To support the type
Suggestion you can:

*

*Use JsonConverter https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html

*Use JsonKey fields fromJson and toJson https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html
https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html
package:vepo/src/presentation/pages/find/form_definition.freezed.dart:24:28
╷ 24 │   Suggestion? get search => throw
_privateConstructorUsedError;    │                            ^^^^^^    ╵

In other words, Suggestion is not serializable. I need its child class, CategorySuggestion to be serializable, and I need Search above, to treat the abstract class Suggestion as though it is serializable:
Suggestion:
abstract class Suggestion<TValue> {
  const Suggestion();
  factory Suggestion.from(dynamic value, [Ref? $provider]) {
    if (value is VgnItmType) {
      return CategorySuggestion(value) as Suggestion<TValue>;
    }
    return VgnItmEstSuggestion(value as VgnItmEst) as Suggestion<TValue>;
  }

  TValue get value;
}

child:
@freezed
class CategorySuggestion extends Suggestion<VgnItmType>
    with _$CategorySuggestion {
  const factory CategorySuggestion(
    VgnItmType value,
  ) = _CategorySuggestion;

  const CategorySuggestion._();
}

I don't care about using freezed, I just want it serializable. I think I need to do something like this for all the concrete children of Suggestion:
@JsonSerializable(genericArgumentFactories: true)
class CategorySuggestion extends Suggestion<VgnItmType> {
  CategorySuggestion(
    VgnItmType value,
  ) : super(value);

  factory CategorySuggestion.fromJson(
    Map<String, dynamic> json,
  ) {
    return _$CategorySuggestionFromJson(json);
  }

  Map<String, dynamic> toJson() => _$CategorySuggestionToJson(this);
    }

But I get the same error as in the question. I think because Suggestion does not have fromJson and toJson. What would I need to do to give it those signatures?
P.S. this is my VgnItmType:
enum VgnItmType {
  @JsonValue(1)
  groceryItm(value: Option(name: 'Grocery Item', iconCodePoint: 0xf291, id: 1)),
      @JsonValue(7)
      recipeItm(value: Option(name: 'Recipe', iconCodePoint: 0xf86b, id: 7));

      const VgnItmType({required this.value});
      final Option value;

      String get optionName => value.name;
      int get id => value.id;
      int get iconCodePoint => value.iconCodePoint;
      Option get option => value;

      static List<Option> get options =>
          values.map((e) => e.value).sortedBy((option) => option.name);

      static VgnItmType idToEnum(int id) =>
          values.firstWhere((element) => element.id == id);
    }


text:
Q: how to change an attribute value after clicking swatches based on sku in magento 2.1 i want to change an attribute value based on swatches selection for example based on swatches selection the SKU gets changes so how to change an attribute value?

A: Here are the steps to change value of sku on base of option selection:
Step 1: (override class using di.xml)
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <preference for="Magento\ConfigurableProduct\Helper\Data" type="<VendorName>\<ModuleName>\Helper\Data"/>

    <type name="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable">
        <plugin name="xnotifConfigurable" type="<VendorName>\<ModuleName>\Block\Product\View\Type\Configurable"/>
    </type>

</config>

Step 2 : Helper/data.php
<?php
namespace <VendorName>\<ModuleName>\Helper;

use Magento\Catalog\Model\Product;

/**
 * Class Data
 * Helper class for getting options
 *
 */
class Data extends \Magento\ConfigurableProduct\Helper\Data
{
    /**
     * Catalog Image Helper
     *
     * @var \Magento\Catalog\Helper\Image
     */
    protected $imageHelper;

    protected $_productloader;

    /**
     * @param \Magento\Catalog\Helper\Image $imageHelper
     */
    public function __construct(
        \Magento\Catalog\Helper\Image $imageHelper,
        \Magento\Catalog\Model\ProductFactory $_productloader
    )
    {
        $this->_productloader = $_productloader;
        parent::__construct($imageHelper);
    }

    public function getOptionsSkus($currentProduct, $allowedProducts)
    {
        $options = [];
        foreach ($allowedProducts as $product) {
            $productId = $product->getId();
            $productDetail = $this->_productloader->create()->load($productId);
            $sku = $productDetail->getSku();
            $options['sku'][$productId][] = $sku;
        }
        return $options;
    }
}

Step 3: (..\Type\Configurable.php)
<?php
namespace <VendorName>\<ModuleName>\Block\Product\View\Type;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Configurable
{
    protected $jsonEncoder;
    protected $jsonDecoder;
    protected $swatchHelper;

    public function __construct(
        \Magento\Framework\Json\EncoderInterface $jsonEncoder,
        \Magento\Framework\Json\DecoderInterface $jsonDecoder,
        \<VendorName>\<ModuleName>\Helper\Data $swatchHelper
    ) {

        $this->jsonDecoder = $jsonDecoder;
        $this->jsonEncoder = $jsonEncoder;
        $this->swatchHelper = $swatchHelper;
    }

    /**
     * Composes configuration for js
     *
     * @return string
     */
    public function aroundGetJsonConfig(
        \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject,
        \Closure $proceed
    )
    {
        $currentProduct = $subject->getProduct();
        $sku = $this->swatchHelper->getOptionsSkus($currentProduct, $subject->getAllowProducts());
        $config = $proceed();
        $config = $this->jsonDecoder->decode($config);
        $config['sku'] = isset($sku['sku']) ? $sku['sku'] : [];
        return $this->jsonEncoder->encode($config);
    }
}

Step 4: (Override swatch-renderer.js into your module or theme)
initialize selector for sku in $.widget.options as
selectorProductSku: '<sku selector>',

call this function OnClick() & OnChange() function:
$widget._SetSkus(childProductId);

add this function:
    /**
     * Update sku
     *
     * @private
     */
    SetSkus: function (childId) {
        var $widget = this,
            $product = $widget.element.parents($widget.options.selectorProduct),
            childId = this.getProduct(),
            $productSku = $product.find(this.options.selectorProductSku),
            sku;
        if(childId)
        {
            sku = this.options.jsonConfig.sku[childId][0];

            var skuSelect =  $productsku.find("<sku selector where to point>");
            $skuSelect.html(sku);
        }
    },

Hope it will help you. Contact if have any query!


text:
Q: How to get the output of AT command into a string in java? I am trying to read the result of an AT command (command executed to do various operation to a GSM modem from console). I have seen and successfully tested using the Java OuputStream class to get the result of an AT command as output stream but what I need to do is to get the result not as outputstream but into a variable (String for now) in my class.
If it is possible to do like
outStream.write(("Some At command").getBytes());

which works fine, how can it be possibe to do something like this
Strign resultOfCommmand=.....result of some AT command;

I am trying it in this way
 InputStream is = new ByteArrayInputStream(("some at commamd").getBytes());

 String result = getStringFromInputStream(is);

 System.out.println("66666666666666666666-----"+result);

/////////////////////

 private static String getStringFromInputStream(InputStream is) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();

    }

but insted of getting the result iam getting the at command itself as a string
 like this....
output:
66666666666666666666-----AT+CMGR=20

A: You must restructure the flow in your program so that it starts by sending the AT command line, and then read back and parse the every single response line given back from the modem until you get a final result code. See this answer for the general outline.
Properly parsing AT command responses is not that complicated, have a look at the source code for atinout for an example.


text:
Q: Express $(152)(45)$ as a product of powers of $(12)$ and $(12345)$ I'm looking at an old group theory question that I botched, and I'm wondering how I should proceed. The question asks to write $(152)(45)$ as a product of powers of $(12)$ and $(12345)$.
The 2-cycle $(45)$ is easily enough written as $(12345)^3(12)(12345)^{-3}$. It's also easy to break down the 3-cycle $(152)$ into $(12)(15)$, which partly satisfies the requirements. I just need to figure out how to express $(15)$ as a product of exponents of $(12)$ and $(12345)$. This is where I'm a bit stuck.
I thought about expressing $(15)$ as $(12345)^j(12)^k(12345)^{-m}$ for positive integers $j$, $k$ and $m$, but I couldn't see if/how that would help. Then I tried $(45)(34)(23)(12)$ (knowing that I could decompose each of those transpositions as I did above) but it doesn't produce a 2-cycle. Is there another way to make $(15)$ that I'm missing?
Thanks.

A: $(15)=(15432)(12)(12345)$ if I'm not mistaken.
Edit: To clarify, this corresponds to $m=j=4$ I guess.
Edit #2: It might be worth mentioning that $\sigma(12)\sigma^{-1}=(\sigma(1)\sigma(2))$ for any permutation $\sigma$ (and more generally, this holds for any cycle type).

A: Have you ever played the Game of 15 (Fifteen Puzzle)? You randomly move the tiles and then have to solve the puzzle: move them back to the initial position.
The reason I am asking you is that one way (not always optimal) to solve the puzzle is row by row. It is quite easy to fill the first two rows with the right tiles using allowed permutations, and then move the last two rows in a cycle and permute them until they eventually take the right positions.
Similarly you can solve your problem. Your permutation is $12345\rightarrow 51324$ and you have two cycles to represent it.
Let us do it step by step.
We have initial permutation: $12345$.
First, put $1$ after $5$: no action ($1$ is already after $5$ because we have the large cycle $(12345)$ which we are to apply at the very last step).
Then, put $3$ after $1$ by swapping $3$ and $2$: $(12345)(12)$ $\rightarrow32451$.
Now, put $2$ after $3$ and $4$ after $2$: already there.
Now cycle to the final position: $(12345)^3$ $\rightarrow 51324$.
To sum up: we have obtained a solution: $$(152)(45)=(12345)(12)(12345)^3$$ which looks quite optimal to me. Just compare it to what you currently have: $(152)(45)=(12)(12345)^4(12)(12345)^4(12)(12345)^2$.


text:
Q: Qt Creator + CMake header and source files separation Is it possible for QtCreator to automatically create header files into ./include/%name of project%/ and source files into ./src/ directories?
By 'create' I mean Header Files -> right click -> Add New... -> C++ Class.
Currently QtCreator creates source and header files in project root directory (or both files in the specified directory), and it seems hard to separate header and source files manually.


text:
Q: Creating word pairs, triplets etc for evaluation in Bleu I need to create a list of word pairs, triplets etc for evaluation in the Bleu metric. Bleu starts with unigrams (a single word) and goes up to N-grams - the N being specified at runtime.
For example, given the sentence
"Israeli officials are responsible for airport security"
For unigrams it would just be a list of the words. For bigrams it would be
Israeli officials
officials are
are responsible
responsible for
for airport
airport security

The relevant trigrams are
Israeli officials are
officials are responsible
are responsible for
responsible for aiport
for airport security

I've coded a working Bleu that hard codes the NGrams to 4 and brute forces the calculations of the unigrams etc. It's ugly as hell, and besides, I need to be able to supply the N at run time.
The snippet that's trying to generate the pairs / triplets etc -
    String current = "";
    int temp = 0;
    for (int i = 0; i < goldWords.length - N_GRAM_ORDER; i++) {
        current = current + ":" + goldWords[i];
        while (temp < N_GRAM_ORDER) {
            current = current + ":" + goldWords[temp + i];
            temp++;
        }
        goldNGrams.add(current);
        current = "";
        temp = 0;
    }
}

Edit - so the output from this snippet should be for bigrams -
israeli:officials
officials:are
are:responsible
responsible:for
for:airport
airport:security

Where goldWords is a String array containing the individual words to be made into NGrams.
I've been tinkering with this loop for days, drawing out the relationships etc and it just won't click for me. Can anyone see what I'm doing wrong?

A: I would change this:
String current = "";
int temp = 0;
for (int i = 0; i < goldWords.length - N_GRAM_ORDER; i++) {
    current = current + ":" + goldWords[i];
    while (temp < N_GRAM_ORDER) {
        current = current + ":" + goldWords[temp + i];
        temp++;
    }
    goldNGrams.add(current);
    current = "";
    temp = 0;
}
}

to this:
 String current = "";
 for (int i = 0; i < goldWords.length(); i++){
     for (int j = 0; j < N_GRAM_ORDER; j++){
            if (i + j < goldWords.length())
                 current += ":" + goldWords[i + j];
     }
     goldNGrams.add(current);
     current = "";
 }

So, the outer for loop iterates through the first word to be included, the inner loop iterates through all the words to be included.  One thing to note is that the if statement is used to prevent an array out of bounds error.  This should be moved to outside the inner for loop if you only want complete n-grams.
With the if statement where it is you will get:
Israeli:officials
officials:are
are:responsible
responsible:for
for:airport
airport:security
security

If you want:
Israeli:officials
officials:are
are:responsible
responsible:for
for:airport
airport:security

instead, try this code:
 String current = "";
 for (int i = 0; i < goldWords.length(); i++){
     if (i + N_GRAM_ORDER < goldWords.length()){
         for (int j = 0; j < N_GRAM_ORDER; j++){
                 current += ":" + goldWords[i + j];
         }
     }
     goldNGrams.add(current);
     current = "";
 }

(the above code is done without checking it against the compiler, so there might be an Off By One or minor syntax error in it.  Validate it, but it will get you close).

A: Here's an alternative that uses a String[] to collect the ngrams instead of a string. I changed the number of iterations on the outer for loop to ensure it captures the last n-gram.
public static List<String[]> ngrams(String[] gold, int n_length) {
    List<String[]> list = new ArrayList<String[]>();
    for (int i = 0; i < gold.length - (n_length-1); i++) {
        String[] ngram = new String[n_length];
        for(int j = 0; j < n_length; j++) {
            ngram[j] = gold[i+j];
        }
        list.add(ngram);
    }
    return list;
}

A: according to the N_GRAM programming output
  int N_GRAM_ORDER = 3, temp = 0, i;
        for (i = 0; i <= goldWords.length - N_GRAM_ORDER; i += N_GRAM_ORDER) {
            while (temp < N_GRAM_ORDER) {
                current = current + ":" + goldWords[temp + i];
                temp++;

            }
            goldGrams.add(current);
            current = "";
            temp = 0;
        }

        if ((temp + i) < goldWords.length) {
            temp += i;
            while (temp < goldWords.length) {

                current = current + ":" + goldWords[temp++];

            }
            goldGrams.add(current);

        }

    }

output
Israeli:officials:are
responsible:for:airport
security


text:
Q: Calculate $\int_{x^2+y^2+z^2
Calculate the integral: $$\int_{x^2+y^2+z^2<x+y+z} (x^2+y^2+z^2)dxdydz$$
Of course calculating the integral $\int_{a}^{b}\int_{c}^{d}\int_{e}^{f} (x^2+y^2+z^2)dxdydz$ would be very easy. However I have a problem because I must find $a,b,c,d,e,f$. I tried to use substitution: $$\begin{cases} x=r \cos \alpha \cos \beta \\ y=r \cos \beta \sin \alpha \\ z=r \sin \beta \end{cases} \text{   or   } \begin{cases} x=r \cos \alpha \\ y=r  \sin \alpha \\ z=z \end{cases}$$
But every of them proved to be ineffective.
Is there anyone who have some tips what I can do to find limits of integrity?

A: Note that \begin{align*} x^2 + y^2 + z^2 < x+y+z \,\,\,\,\, &\Longleftrightarrow \,\,\,\,\, (x^2-x) + (y^2-y) + (z^2-z) < 0\\
&\Longleftrightarrow \,\,\,\,\, (x-1/2)^2 + (y-1/2)^2 + (z-1/2)^2 < 3/4.
\end{align*} Thus you are integrating over a sphere centered not at the origin, but at $(1/2,1/2,1/2)$ which should inform your substitution.


text:
Q: Plotly-Dash: Dropdown options work but won't plot data I am new to Dash. I am trying to plot a simple line plot and add a dropdown to change the data which comes from a dataframe (which is nested in a dictionary with other dataframes). Here is the dataframe:
df_vals['corn']

time    2m_temp_prod    2m_temp_area    total_precip_prod   total_precip_area
0   2020-09-19 00:00:00 299.346777  299.799234  0.000000    0.000000
1   2020-09-19 06:00:00 294.039512  294.443352  0.191070    0.286952
2   2020-09-19 12:00:00 292.959274  293.182931  0.155765    0.216606
3   2020-09-19 18:00:00 301.318046  301.767516  0.421768    0.485691
4   2020-09-20 00:00:00 300.623567  300.979650  0.363572    0.501164
... ... ... ... ... ...
56  2020-10-03 00:00:00 301.177141  301.052273  0.371209    0.408515
57  2020-10-03 06:00:00 295.874298  295.720135  0.281793    0.300564
58  2020-10-03 12:00:00 293.838787  293.686738  0.586887    0.549365
59  2020-10-03 18:00:00 302.384474  302.191334  0.492712    0.493798
60  2020-10-04 00:00:00 300.920766  300.817993  0.522374    0.531138

Here is the code where I attempt the plot.
app = JupyterDash(__name__)
cols=df_vals['corn'].columns[1:]
app.layout = html.Div([
    html.Div([

        html.Div([
            dcc.Dropdown(
                id='variables',
                options=[{'label': i, 'value': i} for i in cols],
                value='2m_temp_prod'
            )
        ]),
    dcc.Graph(id='plot')])
])

@app.callback(
    Output('plot', 'figure'),
    [Input('variables', 'value')])

def update_graph(variable_name):
    fig=px.line(x=df_vals['corn']['time'], y=df_vals['corn'][variable_name])
    return fig

app.run_server(mode='inline')

This makes a plot with the correct dropdown options, but there is no data being plotted. What am I doing wrong here? Trying to follow a tutorial on the Dash website, but appear to be tripping up something.

A: You definitely seem to be close to a solution here. Iactually think that you've only forgotten to import plotly.express as px. I took the time to make a proper data sample out of the data you provided in the question. And without any information of your imports I just had to go for my standard plotly and JupyteDash imports. Anyway, the snippet below will produce the following plot. And please take a look at how I've set up your dataframe. You can learn to make the same setup if you invest the few minutes it takes to read this post.
Dash App - Plot 1
Dropdown selection = '2m_temp_prod'

Dash App - Plot 2

**Dropdown selection = 'total_precip_prod''
Complete code
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px

df=pd.DataFrame({'time':{0:'2020-09-1900:00:00',
                        1:'2020-09-1906:00:00',
                        2:'2020-09-1912:00:00',
                        3:'2020-09-1918:00:00',
                        4:'2020-09-2000:00:00',
                        5:'2020-10-0300:00:00',
                        6:'2020-10-0306:00:00',
                        7:'2020-10-0312:00:00',
                        8:'2020-10-0318:00:00',
                        60:'2020-10-0400:00:00'},
                        '2m_temp_prod':{0:299.346777,
                        1:294.039512,
                        2:292.95927400000005,
                        3:301.318046,
                        4:300.623567,
                        5:301.177141,
                        6:295.874298,
                        7:293.838787,
                        8:302.384474,
                        60:300.920766},
                        '2m_temp_area':{0:299.799234,
                        1:294.443352,
                        2:293.182931,
                        3:301.767516,
                        4:300.97965,
                        5:301.052273,
                        6:295.720135,
                        7:293.686738,
                        8:302.191334,
                        60:300.817993},
                        'total_precip_prod':{0:0.0,
                        1:0.19107000000000002,
                        2:0.15576500000000001,
                        3:0.42176800000000003,
                        4:0.363572,
                        5:0.371209,
                        6:0.28179299999999996,
                        7:0.5868869999999999,
                        8:0.492712,
                        60:0.522374},
                        'total_precip_area':{0:0.0,
                        1:0.286952,
                        2:0.216606,
                        3:0.485691,
                        4:0.501164,
                        5:0.408515,
                        6:0.300564,
                        7:0.549365,
                        8:0.49379799999999996,
                        60:0.531138}})

df_vals = {'corn':df}

app = JupyterDash(__name__)
cols=df_vals['corn'].columns[1:]

app.layout = html.Div([
    html.Div([

        html.Div([
            dcc.Dropdown(
                id='variables',
                options=[{'label': i, 'value': i} for i in cols],
                value='2m_temp_prod'
            )
        ]),
    dcc.Graph(id='plot')])
])

@app.callback(
    Output('plot', 'figure'),
    [Input('variables', 'value')])

def update_graph(variable_name):
    fig=px.line(x=df_vals['corn']['time'], y=df_vals['corn'][variable_name])
    fig.update_layout(template='plotly_dark')
    return fig

app.run_server(mode='inline', debug=True)


text:
Q: youtube api json url I am starting a little jquery plugin for a youtube playlist and I am having problems constructing the URL properly
this is my code:
var playlist = {
    playlist: '**',
    apiKey: '**',
    container: $('#test'),
    shuffle: false
}

function player() {
    var url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=$'+playlist.playlist+'&key=$'+playlist.apiKey+'&callback=?';
    console.log(url);
    $.getJSON(url, function(result){
        $.each(result, function(){
            $('#test').append();
        });
    });
}

and this is what the url above returns:
{"error":{"errors":[{"domain":"global","reason":"invalidParameter","message":"Invalid value for parameter callback: ","locationType":"parameter","location":"callback"}],"code":400,"message":"Invalid value for parameter callback: "}}

A: Why you putted the callback=? and extra $ before the variables. I just used your credentials and get back the json response data.
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLoyiiz-eZk1WRfVo0JR8YyRiYhuJBwkaY&key=#######
N.B: Don't expose your key for public usage.

A: You need to put on the callback a function to execute. If you don't want anything you can just put false like this &callback=false. On your code it will be like this:
var url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=$'+playlist.playlist+'&key=$'+playlist.apiKey+'&callback=false';

Hope it helps you.


text:
Q: Encoding problem (Hebrew UTF8) in WordPress I have a blog (of a friend) I am failing to fix:
http://www.nivcalderon.com/

The language of the website is Hebrew, but the encoding scrambles the output, and I can't find how to fix it.
I tried changing the DB colliation to be utf8_general_ci.
I added this:
define('DB_COLLATE', 'utf8_general_ci');

To the wp-config
(and also this: define('DB_CHARSET', 'utf8');
But removed it later, since it didn't seem to fix the problem)
Any ideas of what else to do ?
Thanks

A: The issue is causing because of a bad import, which make the database to contain double-encoded utf-8 strings. It can be fixed by exporting the tables as latin1 and than importing it as UTF-8. This is not a WordPress fault.


text:
Q: [CORS]:' Access-Control-Allow-Origin' not allowing to get a cross-domain JSON? Actually, I want to get a JSON object from this url ,
I tried using XMLHttpRequest() in javascript but console logged this error: [CORS] The origin 'http://localhost' did not find 'http://localhost' in the Access-Control-Allow-Origin response header for cross-origin  resource at 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN'.
But when I typed url in browser address bar, it loaded correctly! See the screenshot!

See my javascript code:
    <script>
        var url='http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN';
        var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status === 200) {
    callback(null, xhr.response);
  } else {
    callback(status, xhr.response);
  }
};
xhr.send();
};
getJSON('http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN',
function(err, data) {
  if (err !== null) {
    alert('Something went wrong: ' + err);
  } else {
    console.log(data);
  }
});

        </script>

Note: I can't control the server.

A: You can view the information on what CORS is here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
As to your problem, you can solve it by proxying your requests through services like https://cors.io. For example, run this in your console:
fetch('https://cors.io?http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN')
.then(res => res.json())
.then(data => console.log(data))

Please keep in mind that it's not ideal solution as your code will depend on a 3rd-party service in this case. Which is ok for some personal home projects, but not for big corporate ones.

A: You can add https:// in the url instead of http://. This will fix your issue.
You can also open your chrome browser with
chrome.exe --allow-file-access-from-files --disable-web-security

in Windows Run.

A: I got this error when playing with AWS serverless using S3 bucket. after adding below in S3/bucketname/permission/CORSconfiguration the following:
<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>


text:
Q: Unable to scroll through search results in App Store on iOS I'm using an iPhone 5s running iOS 12.2. I can't scroll in the App Store after entering a search term. The Search results load, but it just won't scroll down the list of results.
However, tapping on Featured, Categories, Top Charts or Updates, the scrolling works just fine. But tapping back on Search it just refuses to scroll.
What could be causing this? How do I resolve?


text:
Q: Running PHP, Ruby or Python processes in sandbox mode I'm working on a small weekend project, which is basically an online IDE that allows you to run PHP, Ruby or Python code from the browser. I have everything setup and working, but the way i created the system, if a user runs a badly-written script, or a script with heavy-calculation, the system might slow down for everyone until i reach the timeout (15 seconds).
My system does not pass the fibonacci test. How can i run the process in isolation, that would allow users to create:
while (true) { fibonacci() } // pseudo-code

Without crashing the server? I have considered the following courses of action:

*

*Running each process inside a Docker (https://www.docker.io) container, but i'm not sure how docker deals with slow containers

*Running each process inside a VM

*Running each process in an instantly-created EC2 instance (which is not really an option, since this is slow and expensive)

A: You should spawn another process using the multiprocessing module, then run the users code within that spawned process, thus keeping the inputted code "isolated" in another process. However, you should still keep in mind, you should always run this in a virtual machine because running it outside of one is unsafe on many levels.
Using this method, you can lower the processes priority, since you are in linux, and this should keep each proc. from slowing down your overall machine while the timeout runs. This is assuming that you are indeed running a linux system.

A: Try limiting the process to just one of your CPU cores.
You can use taskset to do that:
http://linux.die.net/man/1/taskset
You can also isolate one of your CPU cores using isolcpus (and your system processes won't use that core), and use taskset to run PHP/Ruby/Python code in that CPU core.
Learn more about isolcpus:
Whole one core dedicated to single process
https://askubuntu.com/questions/165075/how-to-get-isolcpus-kernel-parameter-working-with-precise-12-04-amd64


text:
Q: How to detect a checkbox click in jQuery I cannot detect when and which checkbox gets clicked from script below:
HTML Snippet:
<input type="checkbox" name="checkbox[1]" id="checkbox[1]" class="detectThisChange" value="10.00" checked=""> Amount $10.00
<input type="checkbox" name="checkbox[2]" id="checkbox[2]" class="detectThisChange" value="20.00" checked=""> Amount $20.00
<input type="checkbox" name="checkbox[3]" id="checkbox[3]" class="detectThisChange" value="30.00" checked=""> Amount $30.00

jQuery Snippet:
$(document).ready(function() {
  $(window).load(function() {
// ... //
        $('.detectThisChange').change(function(event){
          var targetID = triggerEvent.target.id; // get the id that triggered the event
          var posStart = targetID.indexOf('[') + 1;
          var posEnd = targetID.indexOf(']');
          var i = targetID.substring(posStart, posEnd); // get the index of the id that triggered the event

          if ( $('#checkbox\\['+ i +'\\]').prop('checked') != true ) {
            alert('checkbox ' + i + ' was checked');
          }
          else {
            alert('checkbox ' + i + ' was unchecked');
          }

        });
// ... //
  }); // end .load()
}); // end .ready()

Appended:
The problem I am experiencing is that none of my alerts work. So that tells me the change() function is not firing.

A: Try like this
$("input[type=checkbox]").is(":checked") // returns boolean checked or unchecked

   var arr = [];
    $("input[type=checkbox]").each(function () {
        var self = $(this);
        if (self.is(':checked')) {
            arr.push(self.attr("id"));
        }
    });
    console.log(arr);

EdIted:
$("input[type=checkbox]").on('change', function () {
    var self = $(this);
    if (self.is(":checked")) {
        console.log("checkbox  id =" + self.attr("id") + "is checked ");
    } else {
        console.log("Id = " + self.attr("id") + "is Unchecked ");
    }
});

Edited 2 :
$("body").on('change','.detectThisChange', function () {
    var self = $(this);
    if (self.is(":checked")) {
        console.log("checkbox  id =" + self.attr("id") + "is checked ");
    } else {
        console.log("Id = " + self.attr("id") + "is Unchecked ");
    }
});

Working Demo

A: Try on change event with this id selector as 'input[id^=checkbox]':

$(function() {
  $('input[id^=checkbox]').on('change', function() {
    console.log(this.value, this.checked);
  }).trigger('change');//fire event on page load
});

  <input type="checkbox" name="checkbox[1]" id="checkbox[1]" class="detectThisChange" value="10.00" checked="">Amount $10.00

  <input type="checkbox" name="checkbox[2]" id="checkbox[2]" class="detectThisChange" value="20.00" checked="">Amount $20.00

  <input type="checkbox" name="checkbox[3]" id="checkbox[3]" class="detectThisChange" value="30.00" checked="">Amount $30.00

A: Try this :
$(".detectThisChange").on('change', function () {

    alert("In the function");
    var targetID = this.id; // get the id that triggered the event
    var posStart = targetID.indexOf('[') + 1;
    var posEnd = targetID.indexOf(']');
    var i = targetID.substring(posStart, posEnd); // get the index of the id that triggered the event

    if ($('#checkbox\\[' + i + '\\]').prop('checked') == true) {
        alert('checkbox ' + i + ' was checked');
    } else {
        alert('checkbox ' + i + ' was unchecked');
    }
});

Here's the JSFiddle, even though you have an answer :)

A: If you are adding this HTML dinamically, you should use the .on() method, like:
$(document).on('change', '.detectThisChange', function() {
    // your code
});

Give it a try and let me know if it helps.

A: Try:)
if ( $('#checkbox\\['+ i +'\\]').is(":checked") ) {
  alert('checkbox ' + i + ' was checked');
}
else {
  alert('checkbox ' + i + ' was unchecked');
}


text:
Q: How to solve error 504: Gateway Timeout between Angular and asp.net I'm making an application where I run my frontend in angular and my backend in asp.net.
In asp.net I have a RecipeApi which provides recipes to the frontend part in Angular. Running this code in Swagger works. All the code from Angular is running correctly, but when I use Angular to get data from the RecipeApi I always get the same error:

Failed to load resource: the server responded with a status of 504 (Gateway Timeout).

All this is running on my localhost.
I already tried to disable my firewall while running these applications and I added the SSL certificate. I changed the name of localhost to [::1] in my proxy.conf.json file, but I don't really know where else I have to look to fix this error.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, RecipeDataInitializer recipeDataInitializer)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            app.UseSwaggerUi3();
            app.UseSwagger();

            recipeDataInitializer.InitializeData(); //.Wait();
        }

{
  "/api": {
    "target": {
      "host": "localhost",
      "protocol": "https:",
      "port": 44393
    },
    "secure": false,
    "changeOrigin": true,
    "logLevel": "info"
  }
}


text:
Q: Checking 2 values to find same string I am trying to compare 2 varchar fields to see if they are similar and I'm having a bit of trouble trying to find my answer anywhere.  I've tried using SOUNDEX and DIFFERENCE, but they don't give me what I need.
This is what I am trying to do:-
Column 1   Column 2    Column 3
123 456    456 123    Should show 1 or "Yes"
123 456    789 987    Should show 0 or "No"

This will generally be a sort code and account number, but they quite often appear swapped round in the fields so I am trying to weed them out
Any help would be great

A: Not sure which RDBMS you are using, but this works in SQL Server to split the fields:
DECLARE @str VARCHAR(10) = '123 456'
SELECT LEFT(@str,CHARINDEX(' ',@str)-1)''
        ,RIGHT(@str,CHARINDEX(' ',REVERSE(@str))-1)

In your case, assuming both sides must match:
SELECT col1
      ,col2
      ,CASE WHEN col1 = col2 THEN 1
            WHEN LEFT(col1,CHARINDEX(' ',col1)-1) = RIGHT(col2,CHARINDEX(' ',REVERSE(col2))-1)
               AND LEFT(col2,CHARINDEX(' ',col2)-1) = RIGHT(col1,CHARINDEX(' ',REVERSE(col1))-1) THEN 1
            ELSE 0
       END
FROM YourTable

If you're trying to isolate matching numbers that are out of order, then you can give the first and second WHEN lines different THEN values.


text:
Q: Way to launch a browser w/ specific webpage without using ShellExecute? (Visual C++) I want to add a button to my visual C++ form that will open with a specific browser. So far for links I've been using:
System::Diagnostics::Process::Start("UrlHere")

Which, as standard, opens with whatever your default browser is.
I'm wondering what the process would be to force the URL to open with a specific browser and if it's possible without the use of ShellExecute?
Edit - You are correct, this is C++/CLI. Removed the C++ Tag.
Edit Edit - Apologies if it came across as misleading. Some slight elaboration;
The buttons will launch to application URL's, some of which can only be used in Internet Explorer, others that CAN (and should) be used in Chrome. This is why I need to avoid using the default browser and have different buttons using different browsers when launching URLs

A: Before answering the 'how', I'd like to ask the question "should you be implementing this?"

*

*By not launching the user's default browser, you are subverting the user's decision.

*

*Perhaps the user prefers a particular interface, and is willing to live with the incorrect renderings that come with it.

*Perhaps the user has a browser addon that they really need, such as a screen reader for the blind.

*You are requiring additional software installed that the user may or may not want.

*

*Perhaps the user doesn't want Chrome. Perhaps the user prefers FireFox.

*You are saying that you know which browser is best, now and forever.

*

*What if the next version of IE makes it work with the sites that are currently Chrome-only? What if the next version of Chrome fixes the sites that are currently IE-only?

*What if the site changes so that it works in more browsers?

*Do you go back and release a new version of your software that changes the browser for particular sites?

*You're trying to solve a problem that may already be fixed.

*

*Both Chrome and Firefox support a addon that will render a tab using the IE engine. It can be set to automatically activate when certain URLs are seen.

*Perhaps there is a browser that already works with all your sites, that you don't know about.

Therefore, my recommendation is no, do not do this. The user has decided which browser they want to use, respect that decision and use the default browser.
That said, here's how you would do it: You could use the CreateProcess method, but you're in managed-land, so you might as well use it. Use the Process class to launch the new process for you.
Process^ browserProcess = gcnew Process();
browserProcess->StartInfo->UseShellExecute = false;
browserProcess->StartInfo->FileName = "C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";
browserProcess->StartInfo->Arguments = "http://www.google.com";
browserProcess->Start();


text:
Q: Toshiba Satellite C850 boot loop I've got a Toshiba laptop acting strange on me. Any thoughts appreciated.
C850-11C
PSCC2E
AMD E1-1200 APU
Windows 8
UEFI
Problem:
Laptop cant restart.
If i shut down the OS or restart, or it restarts it self becaus of an installation or update, it cannot boot up.
Display turns on, its blank but illuminated (purple not black). Stay that way for a couple second then restarts. It doesnt even get to the Toshiba leading innovation logo.
Cant get into BIOS or recovery either. (F2 or F12)
Only way it starts is if i unplug, remove battery, hold down power for 30sec then plug in and start it. In that case it boot perfectly. But no other way.

*

*Tried resetting bios setting to default.

*Tried Windows reset,    refresh.

*Tried removing the bios battery.

*Tried removing HDD , but i dont think it even gets to the point of accessing devices.

Same thing if plugged in/on battery/ both.
Im thinking it might be some kind of internal power component problem....maybe?
Any thoughts welcome!
UPDATE:
Turns out, CMOS reset is not the only way.
Unplugging power (no battery) and pulling RAM module, than putting back results in successful boot too.

A: At this point I would try and run memtest 86++. Failing memory has been know to cause all kinds of crazy issues and killing POST is definitely one of them.


text:
Q: jquery menu list item click function I am using this tutorial
http://www.1stwebdesigner.com/css/create-sliding-navigation-menu-jquery/
this is the index.html file:
!DOCTYPE html> Jquery Sliding Navigation Menu

About Us

Categories

Coding

Freebies

Icons5

Templates10

Fonts3

Tutorial

Icons5

Templates10

Fonts3

Web Design

Archive

Coding

Freebies

Icons5

Templates10

Fonts3

Web Design

Contact

Write For Us ?

I have been trying to figure out how to add a different click function to each of the drop dpwn elements.
I have used this:
$(".level2 a").live("click",function(){
  return false;
});

and it works by adding the same function to every item in the drop down menu.  I was wondering how to address each specific one?

A: If the content is static, you can use something like $('.level2 a:eq(0)'