text:
Q: Rspec undefined local variable or method root_path I'm starting to use Rspec, but when I run bundle exec rspec I get an error
 /spec/requests/pages_spec.rb:20:in `block (2 levels) in <top (required)>': undefined local
 variable or method `root_path' for #<Class:0x00000102e46850> (NameError)

I do not have Spork or Guard running so the question below shouldn't apply
undefined local variable or method `root_path' (Rspec Spork Guard)
I have added config.include Rails.application.routes.url_helpers in my spec_helper.rb file, but that did not help.
undefined local variable or method `root_path' Hartl's Tutorial Chapter 5.3.2
Here's pages_spec.rb
require 'spec_helper'

describe "Pages" do
  describe "navigation" do

    def self.it_should_be_on(path_name, value=nil)
      before { visit path_name }

      it "should be on #{path_name}" do
        page.should have_link('Home')
        page.should have_link('Inventory')
        page.should have_link('FAQ')
        page.should have_link('About Us')
        page.should have_link('Location')
        page.should have_link('Contact Us')
        # page.should have_link('Login')
      end
    end

    it_should_be_on root_path
    it_should_be_on faq_path
    it_should_be_on about_path
    it_should_be_on location_path
    it_should_be_on contact_path
    # it_should_be_on login_path
  end
end

spec_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)

RSpec.configure do |config|
  # ## Mock Framework
  #
  # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
  #
  # config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # If true, the base class of anonymous controllers will be inferred
  # automatically. This will be the default behavior in future versions of
  # rspec-rails.
  config.infer_base_class_for_anonymous_controllers = false

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = "random"
  config.include Capybara::DSL
  config.include Rails.application.routes.url_helpers
end

Update
After reading about shared_examples, I tried this out successfully. Is there a better way to write this test? I ended up separating out the pages into individual pages like Home page etc.
require 'spec_helper'

describe "Pages" do

  subject { page }

  shared_examples "navigation" do |path_name|
    before { visit send( path_name) }

    describe "navigation links should be on #{path_name}" do

      it { should have_link('Home') }
      it { should have_link('Inventory') }
      it { should have_link('FAQ') }
      it { should have_link('About Us') }
      it { should have_link('Location') }
      it { should have_link('Contact Us') }
      # it { should have_link('Login') }
    end
  end

  describe "Home Page" do
    include_examples "navigation", :root_path
  end
end

A: None of the Rails helpers are available at the top level of RSpec's describe block. They are only available within the lower level blocks (e.g. let, before, it, etc.).
If you want to share code such as this across examples, you can use a shared_context or a shared_example, as described in the RSpec documentation, or switch to using symbols as parameters while at the describe level and defer interpretation of them as methods until you're within the lower level blocks, as shown in the answer from @IharDrozdov.

A: To save your structure - you can change the code like this:
require 'spec_helper'

describe "Pages" do
  describe "navigation" do

    shared_examples_for 'main page' do |path_name|
      before { visit send(path_name) }

      it "should be on #{path_name}" do
        page.should have_link('Home')
        page.should have_link('Inventory')
        page.should have_link('FAQ')
        page.should have_link('About Us')
        page.should have_link('Location')
        page.should have_link('Contact Us')
        # page.should have_link('Login')
      end
    end

    it_should_behave_like 'main_page', :root_path
    it_should_behave_like 'main_page', :faq_path
    it_should_behave_like 'main_page', :about_path
    it_should_behave_like 'main_page', :location_path
    it_should_behave_like 'main_page', :contact_path
    # it_should_behave_like 'main_page', :login_path
  end
end

because "paths are not defined at the class level in specs"(c)
You cannot call path methods in spec class. It should be in it block.
And your structure is not perfect. It will be better to put code in modules and then include it, if you want to avoid the duplication.


text:
Q: Looking for a list of events that remove shapes from GoogleMap I have a program that, when stripped down to the barest features, draws polygons and circles to my GoogleMap as expected. However, with all other features added, the polygons and circles no longer show up on the map. Since there are a few thousand lines of code to comb through, I was searching for a comprehensive list of events that would cause shapes to be cleared from the map to narrow it down. I haven't been able to find any documentation on this in the official Google Maps documentation.
Is there a complete list somewhere that I'm missing?

A: I found that there is only one event that removes shapes from a GoogleMap. That event is GoogleMap.clear().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Send sessionToken cross domain I have a unique scenario. I have a sessionToken (htmlOnly cookie) set by one server. I need to add this sessionToken in a CORS request to another server. CORS server uses this sessionToken for authentication. I understand this is not the best practice but given our timeframe this is the only way out.
I tried setting withCredentials to true while making the CORS request but that does not seem to be sending any cookies to the server. Is there anyway to send the sessionToken to another server in header?
I have tried setting withCredentials to true but while checking the network request no cookies from the origin domain is being sent in the CORS request.

A: You cannot do this. withCredentials will only send cookies for the domain the request is too, it does not send the cookies from the domain the request is made from, this would be a huge security hole.
You can make the cookie not be httpOnly, and read the value and send in an Authorization header instead to the other domain. Although I wouldn't recommend this since it isn't as secure.
Using an authentication scheme such as OAuth which returns a JWT that has an audience set for both domains that can be passed in the Authorization header and verified by both domains would seem better to me.

A: Website B can't read a cookie from website A.
I think you can use tokens instead, to return jwt token ( session info ) and the client side will submit this token to the other domain.


text:
Q: Can the elements of a two dimensional array be processed for some output in O(n) time? Suppose that each row of an n*n array A consists of 1's and 0's such that, in any row of A, all the 1's come before any 0's in that row. Assuming A is already in memory, describe a method running in O(n) time for finding the row of A that contains the most 1's.

A: *

*start from 0th row and scan from right to left to encounter the first 1

*When you reach the 1, update your answer. Suppose, the column is j.

*Now for every row i from 1 to n, check if jth column holds 1.

*

*If it holds 1, that means there can be 1 in right too. So try to move right until finding the rightmost 1 and update the answer and j

*If it holds 0, we won't need to go left or right as we have better result already from previous rows.

This algorithm will scan atmost c * n elements in total for all rows where c is some small constant. So time complexity is O(n).
Moreover, You can use binary search to find the rightmost 1 for each row which will require less scan. At first, it seems binary search on each row will take O(nlogn), but the left boundary will reduce in each row resulting fewer scan.
Hope it helps!


text:
Q: Highlight if it is the only cell not containing "0" I'm looking for a way in Excel to set up a Conditional Formatting to help identify single errors. We have an Excel spreadsheet with a row of values. If there are only errors in a single section, such as the following, it will be highlighted:
    *note, the 1 could be a 2 and still be highlighted
However, if there are multiple errors in different sections. It would not be highlighted, such as the following:

So far I haven't been able to find a solution.
*Edit in: Looks like I am on the right track now thanks to you guys. I want to try these solutions out, but I have to run at the moment. As soon as I get a second to sit down at my computer, I'll try these out and see if it works for me. I'll accept an answer then. Thanks again guys.

A: I think what you want is a formula such as =AND(COUNTIF($A1:$D1,0)=3,A1<>0) in Conditional Formatting.

(Using Excel 2007)

A: I take it to mean that numbers other than 0 indicate an error?
You can probably use this formula in the conditional formatting:
=AND(A1<>0,COUNTIF($A1:$D1,"<>0")=1)

Assuming that the first value is in cell A1. You can change the range and cell references as necessary.

A: If all your values are zeroes or postive numbers try this formula for conditional formatting for row 2
=AND(A2<>0,COUNTIF(2:2,">0")=1)
you can copy to other rows or change the "applies to" range as required


text:
Q: Regex for roatating floating numbers i'm using the following regex regex=re.compile("""(?P<responce_time>\s\d+\.\d+\s)""", re.M)
to get all response times in my nginx log file
line = 192.168.1.1 - - [08/Sep/2014:15:15:15 +0100]  "GET / HTTP/1.0" 200 612 "-" "-" 4.038 - .
The variable  line` is always rotating with new log entries
print(Regex.match(line).groups())
this returns  AttributeError: NoneType Object has no attribute group
Any ideas ?
The regular expression is vaild http://regex101.com/r/yP5jV0/2,

A: use regex.search instead of regex.match.  The re.match matches only at the beginning of a string whereas re.search will match anywhere in the string.


text:
Q: Multiple tables vs one table with more columns My chosen database is MongoDB. But the question should be independent.
So for example, each row of record will have a flag that can take 1 of 2 possible values.
What is the pro and con of:

*

*Having 1 table with a column to hold the value of this flag.

versus:
the pro and con of:

*

*Having 2 tables to hold the two different types of records distinguished by the aforementioned flag?

*Would this be cheaper in terms of storage, since you don't have that extra column?

*Would this also be faster in queries, since you know exactly which table to look without having to perform a filter?

What is the common practice in industry?

A: Storage for a single column holding just a flag (e.g. active and archived) should be negligible. The query could be faster with two tables, however your application is more complex, you have to write 2 queries.
When you have only 2 distinct values and these values are more or less evenly distributed, then an index will not be used, thus the performance should be equal - unless you select the entire table.
It might be useful to have 2 tables if the flags are not evenly distributed. For example you have a rather small active data set which is queried frequently, and a big archive data set which is much bigger but hardly queried.
If available, you can also work with partitions which is actually a good combination of both.


text:
Q: Selecting md5sums from a text file and remove duplicates in Linux I've used the find command and created a file called Duplicates.txt full of the md5sums of a bunch of images.
How do I go about finding the duplicate md5's in the file, and then using those to remove the duplicates from the archive?
edit: I can't use fdupes.

A: sort Duplicates.txt|uniq -c|grep -v '^ *1 '

A: Assuming you made your file Duplicates in a manner similar to this:
find ./dupimgs -type f -print0 | xargs -0 sha1sum > dupes.txt

Then you could easily extract the files that are unique with this one-liner:
sort dupes.txt  | uniq --check-chars=40 --count | cut -d' ' -f 10

These are the files you'll want to keep. I suggest moving them in another directory and then remove the directory that is now full of copies:
sort dupes.txt  | uniq --check-chars=40 --count | cut -d' ' -f 10 | xargs -I {} mv {} ./originals
rm -rf ./dupimgs

Remark: I used sha1sum rather than md5sum. That means the length of the digests will be different. For sha1sum it's 40 characters. For md5sum, it's 32 hexadecimal digits. So you'll want to change the 40 in the above commands to match the length of the hexadecimal strings that are returned by whichever hashing function you've used.

A: There is some impressive bash-fu behind fslint's duplicate search engine script "findup"; the bit you are interested in is around line 185.
I would normally put in a plug for rmlint but it looks like you are looking for a purely bash solution.


text:
Q: Solution to java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter step-by-step I'm trying to connect SQL Server to Eclipse and I'm getting Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter
After few days of looking into the topic it all boils down to removal of module javax.xml.bind in Java 11 (I have JDK12, using JavaSE-11). I am asking if anyone can help me in step-by-step solution how to resolve this. There are many answers where is said - add module  or   adjust dependency in Maven, but I couldn't find actual way to do that in form of - go to this file, edit it, replace with this... etc.
Also, I've found
https://search.maven.org/artifact/javax.xml.bind/jaxb-api/2.2.9/jar as a patch but I'm not sure if it's of any use since Maven is foreign to me.
I hope I have been clear. Any help is very much appreciated.
Stay safe, everybody!


text:
Q: ImportError DLL load failed when import qgis.core but no errors when import qgis EDIT
So.. after some problems everything seems to semi-work I guess ? I will update my variables so maybe it will help someone.

I am working on a standalone application using Python and QGIS.
I've read every single tutorial/forum I could find and tried multiple times the method described in the QGIS Python Programming CookBook but I can't make it work.
I am using :

*

*Python 3.7.0

*OSGeo4W64 3.12

*PyQT5 5.15.1

I've already configure the PATH and PYTHONPATH variables using the commands below in the QGIS Python console (the path that I obtained where added to the variables)
import sys
print(sys.path)
qgis

Paths that didn't existed where ignored.
For the details here are my variables :
PYTHONPATH
 - C:\OSGeo4W64;
 - C:\OSGeo4W64\bin;
 - C:\OSGeo4W64\apps\qgis\python;
 - C:\OSGeo4W64\apps\qgis\python\qgis;
 - C:\OSGeo4W64\apps\Python37;
 - C:\OSGeo4W64\apps\Python37\lib;
 - C:\OSGeo4W64\apps\Python37\lib\site-packages;
 - C:\OSGeo4W64\apps\Python37\lib\site-packages\win32;
 - C:\OSGeo4W64\apps\Python37\lib\site-packages\win32\lib;
 - C:\OSGeo4W64\apps\Python37\lib\site-packages\pythonwin;
 - C:\OSGeo4W64\apps\Python37\DLLs;
 - C:\OSGeo4W64\apps\Python37\Scripts;
 - C:\Users\ [username]\AppData\Roaming\QGIS\QGIS3\profiles\default\python;

PATH
 - C:\OSGeo4W64\bin;
 - C:\OSGeo4W64\apps;
 - C:\OSGeo4W64\apps\qgis\bin;
 - C:\OSGeo4W64\apps\qgis\python;
 - C:\OSGeo4W64\apps\qgis\python\qgis;
 - C:\OSGeo4W64\apps\Python37;
 - C:\OSGeo4W64\apps\Python37\lib;
 - C:\OSGeo4W64\apps\Python37\lib\site-packages;
 - C:\OSGeo4W64\apps\Python37\lib\site-packages\win32;
 - C:\OSGeo4W64\apps\Python37\lib\site-packages\win32\lib;
 - C:\OSGeo4W64\apps\Python37\lib\site-packages\pythonwin;
 - C:\OSGeo4W64\apps\Python37\DLLs;
 - C:\OSGeo4W64\apps\Python37\Scripts;
 - C:\Users\ [username]\AppData\Roaming\QGIS\QGIS3\profiles\default\python;
 - C:\OSGeo4W64\apps\Qt5\bin;
 - C:\OSGeo4W64\apps\Qt5\lib;
 - C:\OSGeo4W64\apps\Qt5\plugins;

And here's the kicker :
>>> import qgis
>>>
>>> import qgis.core
Traceback (most recent call last):
   File "<stdin>", line 1 in <module>
   File "C:\OSGeo4W64\apps\qgis\python\qgis\core\__init__.py", line 25, in <module>
      from qgis._core import *
ImportError: DLL load failed: the specified procedure could not be found.
>>>

(I've translated the last sentence since it was in french)
So as you can see, when I simply import qgis, it works but if I import qgis.core / qgis.gui and so on, I have the same error.
I've read that changing the version of QGIS might help but I want to try something else before switching to another version and probably messing all up again.


text:
Q: Data Warehouse how to connect fact table with foreign key to dimension table whose primary key contains two attributes I want to design my Data Warehouse fact-dimension schema, fact table should have several foreign keys, Aid, Bid, Cid.... refer to dimension tables A, B, C,.... respectively.
However, dimension table C has an unique key (Aid, Cid). In this case, is that possible for link the fact record to the dimension table C with two keys (Aid and Cid)? Or I should apply another dimension table including only primary key? Thanks a lot!

A: Just as a rule of thumb, your dimension tables should have very simple primary keys, consisting of a single field. In most cases you should consider a surrogate key. Even if your dimension seems to have a natural key or a key coming from the transactional database, you are always only one requirement change away from having to support a slowly changing dimension.


text:
Q: Symbology in the Lantern Corps emblems? I'm curious about the symbology and meaning behind the various emblems of the Lantern Corps.

As I understand it, the Green is by far the oldest (both in- and out-of-universe), while the others are relative newcomers. Unless I'm mistaken, most were created during the War of Light arc, with the exception of the Star Sapphires, whose organization takes the symbol of the older sole-character Star Sapphire.
Some of these emblems seem to be basic representations (e.g. the Orange Lantern Corps symbol has a sense of gathering things together in a central place, which fits with greed, and the Black Lantern Corps points down, a direction generally associated with death), but others seem more abstract.  Almost all feature central circles, and four (yellow, green, blue, and indigo) reference the basic Green Lantern design, with horizontal bars above and/or below.
The Green Lantern symbol itself is obviously a representation of a lantern, and I've also heard arguments that it represents an exertion of willpower (a circle forcing two lines apart, or two lines containing a circle).
Have there been any official comments by the artist(s) who designed these symbols about what the various designs are meant to indicate?  Are they meant to be depictions of the emotion they represent (and if so how), or are they simply abstract symbols meant to look like equivalents of the older Green Lantern symbol?

A: *

*Indigo: Looks similar to a vertical eye, a symbol usually associated with spiritual enlightenment, something the monk like Indigo Tribe seems to have (well, pseudo enlightenment.)

*Red: Has a shape similar to the head of a bull, a creature often associated with rage (and is also the form of their entity.)

*Yellow: A perversion of the original Green Lantern symbol, meant to instill some form of fear.

*Green: It's a lantern... that's it.

*Blue: Resembles a bird or, perhaps more accurately, the entity of the Blue Lantern Corps.

*Violet: A crystal, which makes sense since the Star Sapphires (the wielders of this light) have more crystalline constructs than the other corps.

*Orange: Two theories here; it is either a perversion of the Indigo Tribe's symbol  (look long enough and it starts to look like a wide open round eye); or it is representing a mouth or other similar consuming orifice (after all, one of the symptoms of wielding the orange light is an insatiable hunger.)

*Black: Your theory seems to hold the most water, though it is also another perversion (getting quite a few here) of a lantern corp. This time the White Lantern Corp, who represent life.
BONUS!

*White: Seven beams of light shooting out of a prism, representing the fact that the seven lantern colors, sans black, all originally stemmed from the white light.

I hope this was helpful to you and I didn't spoil anything.

A: Artist Ethan Van Sciver gave an interview about this very thing a few years back.

*

*red: based on Manhunters' chest design

*indigo: circle is like a lantern and the outward-pointing arrows represent giving

*orange: reverse of indigo, with inward-pointing lines and a vaguely humanoid shape to indicate "me" and selfishness

*yellow: inspired by Parallax's costume

*blue: kind of the opposite of yellow

*black: inspired by Black Hand's costume insignia


text:
Q: Hyperledger Fabric Node.js SDK: Issue with offline transaction signatures I am trying to follow this tutorial:
https://hyperledger.github.io/fabric-sdk-node/release-1.4/tutorial-sign-transaction-offline.html
I created a complete Hyperledger Fabric network using this guide:
https://hyperledger-fabric-ca.readthedocs.io/en/latest/operations_guide.html
The Javascript SDK is working well, and I can query/invoke transactions using the client.setUserContext() method.
When trying to sign the transaction offline, the transaction proposal is rejected by the peers with the following response:
{ Error: 2 UNKNOWN: access denied: channel [mychannel] creator org [org1]
      at Object.exports.createStatusError ([...]/node_modules/grpc/src/common.js:91:15)
      at Object.onReceiveStatus ([...]/node_modules/grpc/src/client_interceptors.js:1204:28)
      at InterceptingListener._callNext ([...]/node/node_modules/grpc/src/client_interceptors.js:568:42)
      at InterceptingListener.onReceiveStatus ([...]/node/node_modules/grpc/src/client_interceptors.js:618:8)
      at callback ([...]/node/node_modules/grpc/src/client_interceptors.js:845:24)
    code: 2,
    metadata: Metadata { _internal_repr: {} },
    details: 'access denied: channel [mychannel] creator org [org1]' }

In the logs from the peers, I see the following error:
peer1-org1       | 2020-01-13 21:47:31.569 UTC [protoutils] ValidateProposalMessage -> WARN 078 channel [mychannel]: creator's signature over the proposal is not valid: The signature is invalid

I do not understand why the signature is rejected. I carefully followed all the steps of the tutorial. Here is the complete client code:
//
// Imports
//
var Client = require('fabric-client');
var path = require('path');
var util = require('util');
var fs = require('fs');
const crypto = require('crypto');
const elliptic = require('elliptic');
const { KEYUTIL } = require('jsrsasign');
const config = require('./config');

//
// Script configuartion variables
//
var fcn = 'set';
var args = ["a","60"];
var priv = fs.readFileSync(config.PRIV, 'utf8');
var { prvKeyHex } = KEYUTIL.getKey(priv,'passphrase');
var cert = fs.readFileSync(config.CERT, 'utf8');
const EC = elliptic.ec;
const ecdsaCurve = elliptic.curves['p256'];
const ecdsa = new EC(ecdsaCurve);
const signKey = ecdsa.keyFromPrivate(prvKeyHex, 'hex');

//
// Config init
//
var client = Client.loadFromConfig('network_org1.yaml');
var targets = client.getPeersForOrg('org1');

//
// Main
//
client.initCredentialStores()
.then((nothing) => {

channel = client.getChannel(config.CHANNEL_NAME);

// 1. Generate unsigned transaction proposal
var transaction_proposal = {
  chaincodeId: config.CHAINCODE_NAME,
  channelId: config.CHANNEL_NAME,
  fcn: fcn,
  args: args,
};

var { proposal, tx_id } = channel.generateUnsignedProposal(transaction_proposal, 'org1', cert);

// 2. Hash the transaction proposal
var proposalBytes = proposal.toBuffer();
var digest = client.getCryptoSuite().hash(proposalBytes);
//const hash = crypto.createHash('sha256');
//hash.update(proposalBytes);
//var digest = hash.digest('hex');

// 3. Calculate the signature for this transacton proposal
console.log("digest: "+digest);
console.log("signKey: ");
console.log(util.inspect(signKey));
var sig = ecdsa.sign(Buffer.from(digest, 'hex'), signKey);
var signature = Buffer.from(sig.toDER());
var signedProposal = {
  signature,
  proposal_bytes: proposalBytes,
};

// 4. Send the signed transaction proposal
var proposal_request = {
  signedProposal,
  targets
}
channel.sendSignedProposal(proposal_request)
.then((proposalResponses) => {
    console.log('Proposal responses:');
    console.log(util.inspect(proposalResponses));

    // TODO: Understand why the proposal signature is rejected by the peers

    // 5. Generate unsigned transaction
    var transaction_request = {
      proposalResponses,
      proposal,
    };
    return channel.generateUnsignedTransaction(transaction_request);
})
.then((commitProposal) => {

    // 6. Sign the unsigned transaction
    var transactionBytes = commitProposal.toBuffer();
    var transaction_digest = client.getCryptoSuite().hash(transactionBytes);
    var transaction_sig = ecdsa.sign(Buffer.from(transaction_digest, 'hex'), signKey);
    var transaction_signature = Buffer.from(transaction_sig.toDER());

    var signedTransaction = {
      signedProposal: transaction_signature,
      request: transaction_request
    }

    // 7. Commit the signed transaction
    return channel.sendSignedTransaction(signedTransaction);
})
.then((response) => {
    console.log('Successfully sent transaction');
    console.log('Return code: '+response.status);
});

});

Any help from anybody who might have successfully signed transactions offline would be fantastic.

A: Answering my own question. There were 2 issues in my code.
1st one was related to the actual signature that needs to be done in a very specific way in Fabric. I had to create this function and apply it to the signature to avoid the issue:
function _preventMalleability(sig) {
const halfOrder = elliptic.curves.p256.n.shrn(1);
if (sig.s.cmp(halfOrder) === 1) {
    const bigNum = elliptic.curves.p256.n;
    sig.s = bigNum.sub(sig.s);
}
return sig;

2d one was related to the formatting of the various proposals/requests/transactions structures:
transaction_request = {
  proposalResponses: proposalResponses,
  proposal: proposal,
}

signedTransactionProposal = {
    signature: transaction_signature,
    proposal_bytes: transactionBytes,
}

signedTransaction = {
  signedProposal: signedTransactionProposal,
  request: transaction_request,
}

I have created a complete (working) tutorial with detailed instructions here:
https://gitlab.com/guillaume.goutaudier/wisekeydemo


text:
Q: HBase - query difference between two timestamps I'm considering HBase as a trading system database due in part to its first-class timestamp-based versioning of rows. Trades get modified all the time, and we typically have to cope with that explicitly in the data model when working with SQL databases. In HBase, I'd model trades (not individual trade versions) as rows and let HBase do the hard work of giving me access to trade versions that were live at a previous point in time.
The query side of the system needs access to trade data in 3 major ways:

*

*Current versions of all trades. This is clearly supported by HBase.

*Versions of all trades that were active at a specific timestamp. Again, clear support from HBase. The purpose of this query is typically end of day processes that want to report the trade population at a specific time of day.

*Activity between 2 timestamps. This is useful for feeding information at end of day to systems which are already in sync with the trading system and want to know what's change. It also forms the basis for a daily Profit and Loss (P&L) calculation which indicates what the change of P&L is from yesterday's daily value.

So, my question is: does HBase have any built-in support for performing a "diff" between two timestamps? Alternatively, is there any best-practice way of meeting this requirement at the database level? If not, I'd need consider building a process that fetches two timestamp-based queries out of the database and performs a difference operation.
I'd expect the output of the process to be:

*

*A list of trades trades at the new timestamp that have changed since the old timestamp.

*A separate list of trades as-of the old timestamp that have been made obsolete at the new timestamp.

Those pieces of information allow me to apply the positive changes and "back out" the negative changes. For example, if a trade has changed notional from 1m USD to 2m USD, I want to be able to apply a +2m change and then back out a -1m change to result in a net change of +1m for the day.


text:
Q: javaFX Transform node across boundaries of parent Not sure how to express the question. Please forgive me if not clear.
As shown in the image below, I would like to drag a node (circle) across a parent (pane) and once the node cross the boundary of the parent, the part that is outside would appear on the opposite end.
How do I go about making this? Am I looking at reflection? Or some way of making inverse transforms?is there something around the corner in Javafx current API that permits this ?

A: If the node is always a Circle, which is a Shape, it is possible to make use of intersect and subtract from Shape.

*

*Get intersection Shape of Circle and your Pane (Pane can be represented as a Rectangle with corresponding width and height). You use this as the one that appears on "this" end.

*Subtract the obtained Shape from Circle to get another Shape which is the one that appears on the "opposite" end.

Shapes are also nodes, so you can draw them straight away, as soon as you computed them.


text:
Q: Calling Unity method from Android performance issue Currently I have a Unity game ported to Android. I had to implement bluetooth control that moves game object horizontally.
Right now I am using loop that calls UnityPlayer.UnitySendMessage("paddle", "changePosition", position) with 10ms delay. I've read that this function call is not efficient at all.
Is there any way to call changePosition function in Unity with giving it position argument more efficient way?
Currently the paddle movement may have 0.5ms+ lag from time to time.
EDIT here's my current loop that calls for Unity function:
int tableRowsCounter = 0;
                int[] rawData;
                while (!abort) {
                    if (!btHandler.isAborted()) {
                        tableRowsCounter++;

                        double currentAngle = getFinalAngles()[axis];
                        currentAngle = currentAngle > 0 ? currentAngle * rightMultiplier :
                                currentAngle * leftMultiplier;

                        UnityPlayer.UnitySendMessage("Paddle", "changePosition", Double.toString(currentAngle));

                        rawData = getRawData();

                        dbHandler.addDataToArrayLists(rawData);

                        if (tableRowsCounter == 500) {
                            new AsyncTask<Void, Void, Void>() {

                                @Override
                                protected Void doInBackground(Void... params) {
                                    dbHandler.insertData();
                                    return null;
                                }
                            }.execute();
                            tableRowsCounter = 0;
                        }

                        Thread.sleep(30);
                    }
                }


text:
Q: Countdown timer using jQuery or Google App Engine? I need to create a countdown clock, that counts down the days, hours, minutes and seconds that are left to a date of my choice, using jQuery or Google App Engine (Python).
I have created a timer using JavaScript but for that I was using the system time.
I need to use the server time. Can anybody give me ideas to build a count down timer using the server UTC time.

A:
I created a timer using Javascript,But in that i used system time.

If that JavaScript really serves your needs, then that JavaScript code could easily be made dynamic as well. In the code, wherever the current system time is initialized, simply insert your server time using your language of choice (Python). In other words: use your server language (Python) to output the script just as it is right now, except for replacing the part that initializes the current time.
In PHP, some pseudocode (not sure about the arguments of the Date() constructor) might look like, for example:
// my_countdown_script.php
[..]
var startTime = new Date( <?php echo time(); ?> );
[..]

Then, rather than including your JavaScript, you would be including the PHP file that inserts the server time like above:

The good thing is: this will work in any browser that supports the JavaScript you already created.
(In some later version, your JavaScript could include some initializers that allow you to set the current time after including the library in your HTML. That would allow the actual JavaScript library to be static, and thus to be cached by the browser.)

A: a good jquery plugin can be found here http://keith-wood.name/countdown.html
all you need to do then is pass in your new date from your scripting language php/asp.net by setting a variable on the page before the initialisation and updating the _calculatePeriods function to take that variable instead of the now one.

from js/jquery.countdown.js
 * Calculate the requested periods between now and the target time.
   @param  inst  (object) the current settings for this instance
   @param  show  (string[7]) flags indicating which periods are requested/required
   @param  now   (Date) the current date and time
   @return  (number[7]) the current time periods (always positive)
            by year, month, week, day, hour, minute, second */
_calculatePeriods: function(inst, show, now) {
    // Find endpoints
    inst._now = servernow;

Josh

A: You can reliably get server time from http://just-the-time.appspot.com/ -- an app engine app I made to help out a questioner on stack overflow, actually;-).  Its simple code is opensourced at http://code.google.com/p/just-the-time/, and I could easily add the functionality you require (a page that, queried with the future date of your choice, returns days, hours, minutes and seconds to it, in some easily usable format) -- just let me know!

A: jQuery Timers is a plugin I've used in the past, and found to be very good.
Simply set two JavaScript variables to the current and target time for the countdown, and use a jQuery timer to update the "time remaining". If you want, you can add another time that re-synchronises the server and client times as well, every so often - though this probably isn't necessary.

A: why not simply use the UTC methods of the date object?
see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date
all local time methods have UTC counterparts
edit: this is meant to be used with his existing implementation in javascript.
If you really want to be sure you get the server time, do an XHR request (for anything) and check the Date header

A: So basically you need two things:

*

*Page that displays the countdown time using the server time.

*Client side updating of the time.

Render your time server side in something like this:
4 min. and 24 seconds

Where the title is a timestamp of the current time that you can easily parse. You could also parse the text, but that requires more complex code.
Then add some Javascript that gets the time and updates the text every second. Setting a timeout that gets the date, updates it and sets the text.


text:
Q: Implementing a membership system using OpenID I'm looking to implement a membership system using OpenID for my ASP.NET application, similar to the system used here on StackOverflow. I'm aware that the OpenAuth library is generally recognized as the way to go, but I'm having trouble figuring out how to implement it.
I use NHibernate to persist my domain objects. I have a Users table with a username column, email column, etc. I'm not sure how to integrate OpenID with my own users table, and I haven't found any good tutorials on this. Does anyone have any experience with this? What is the best way to go about doing it?

A: Check out this blog post from Rick Strahl.
A good write up of how to do authentication and registration with OpenID.

A: Tyler, yes, I found the OpenAuth library to be way too complicated (read that as "over engineered") as well. So I developed my own and made it an open source library.
you can check it out my website here
OAuth C# Library
I have a very simple working demo application available as well and you should be up and running in no time.

A: You can have a look at Implementing OpenID in ASP.net "Properly" - Membership or Authentication Provider? on SO. On Codeplex you will find a membership provider that might suite your needs. The other SO answers also share a link to a second alternative implementation.

A: check it out: http://www.dotnetopenauth.net/developers/code-snippets/programmatic-openid-relying-party/
very easy to implement. good luck!


text:
Q: Python module to generate all permutations of possible string replacements in a string? template = "{{ person }} is a {{ quality }} {{ occupation }}"
replacements = {
"person":["John","Matt","Steve"],
"quality":["great","dedicated"],
"occupation":["engineer","student","athelete"]
}

Output:
John is a great engineer
Matt is a great engineer
Steve is a great engineer
John is a dedicated engineer
Matt is a dedicated engineer
Steve is a dedicated engineer
John is a great student
Matt is a great student
Steve is a great student
.............................

They can be generated by using lists of lists of replaceable elements and looping over them to generate permutations, and then joining the list elements.
list_input =     [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]]

example_permutation = ["John","is","a","great","engineer"]

Is there a python module/method which can generate similar permutations ?

A: This just cartesian product of the list
import itertools

list_input =     [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]]
for element in itertools.product(*list_input):
    print element

or you can do directly from your dict @dano(suggested)
replacements = {
"person":["John","Matt","Steve"],
"quality":["great","dedicated"],
"occupation":["engineer","student","athelete"]
}

for element in itertools.product(*replacements.values()):
    print("{} is a {} {}".format(*element))

#output

John is a great engineer
John is a great student
John is a great athelete
John is a dedicated engineer
John is a dedicated student
John is a dedicated athelete
Matt is a great engineer
Matt is a great student
Matt is a great athelete
Matt is a dedicated engineer
Matt is a dedicated student
Matt is a dedicated athelete
Steve is a great engineer
Steve is a great student
Steve is a great athelete
Steve is a dedicated engineer
Steve is a dedicated student
Steve is a dedicated athelete


text:
Q: Inter-Process Comunication in C I'am doing a exercise on IPC using pipes. The protocol is as follows:

*

*client(child) reads file name from stdin

*client sends file name over pipe to server

*server (parent) reads file name from pipe

*server obtains information about the file (stat sys call)

*server sends file information over pipe to client.

*client reads file info from pipe and outputs to stdout

I'am having problems with the last steps i don't know how to send this information correctly. At the moment output from client is garbage. Here is the code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#define BUFSIZE 1024

int main()
{
    int fd1[2], fd2[2], pid, n;
    char buf[BUFSIZE];
    pipe(fd1);
    pipe(fd2);
    if ((pid = fork()) == 0)
    {
        close(fd1[0]);
        close(fd2[1]);
        read(STDIN_FILENO, buf, BUFSIZE); // 1. client(child) reads file name from stdin
        int len = strlen(buf);
        buf[len - 1] = '\0';
        write(fd1[1], buf, len); // 2. client sends file name over pipe to server
        while ((n = read(fd2[0], buf, BUFSIZE)) > 0)
        {
            write (STDOUT_FILENO, buf, n); // 6. client reads file info from pipe and outputs to stdout
        }
    }
    else
    {
        struct stat st;
        close(fd1[1]);
        close(fd2[0]);
        read(fd1[0], buf, BUFSIZE); // 3. server (parent) reads file name from pipe
        stat(buf, &st); // 4. server obtains information about the file (stat sys call)
        write(fd2[1], (void *)st.st_size, sizeof(st.st_size)); // 5. server file information over pipe to client.
        write(fd2[1], (void *)st.st_atime, sizeof(st.st_atime));
    }
    return 0;
}

update:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#define BUFSIZE 1024

int main()
{
    int fd1[2], fd2[2], pid;
    size_t n;
    char buf[BUFSIZE];
    pipe(fd1);
    pipe(fd2);
    if ((pid = fork()) == 0)
    {
        close(fd1[0]);
        close(fd2[1]);
        n = read(STDIN_FILENO, buf, BUFSIZE - 1); // 1. client(child) reads file name from stdin
        buf[n] = '\0';
        write(fd1[1], buf, n); // 2. client sends file name over pipe to server
        while ((n = read(fd2[0], buf, BUFSIZE)) > 0)
        {
            if ((write (STDOUT_FILENO, buf, n)) != n) // 6. client reads file info from pipe and outputs to stdout
            {
                perror("client: write error\n");
            }
        }
    }
    else
    {
        struct stat st;
        close(fd1[1]);
        close(fd2[0]);
        read(fd1[0], buf, BUFSIZE); // 3. server (parent) reads file name from pipe
        stat(buf, &st); // 4. server obtains information about the file (stat sys call)
        if (write(fd2[1], (void *)st.st_size, sizeof(st.st_size)) != sizeof(st.st_size)) // 5. server sends file information over pipe to client
        {
            perror("server: write error\n");
        }
        if (write(fd2[1], (void *)st.st_atime, sizeof(st.st_atime)) != sizeof (st.st_atime))
        {
            perror("server: write error\n");
        }
    }
    return 0;
}

A: You can't use strlen() here. You should use the return value from read() instead.
After read() the data in buf is nothing but a sequence of bytes, it could become a string if you add a '\0' byte at the end of the sequence. Since it's not present, calling strlen() invokes undefined behaviour so it doesn't matter what you do after that, it will not behave as expected.
The strlen() could be thought of as
size_t
strlen(const char *const string)
{
    size_t length;
    length = 0;
    while (string[length] != '\0')
        ++length;
    return length;
}

one reason you should avoid things like
for (size_t i = 0 ; i < strlen(string) ; ++i) ...

specially because you can use a loop like the one in the strlen() implementation above.
Use ther return value from read() instead
ssize_t read_length;
read_length = read(STDIN_FILENO, buf, sizeof(buf) - 1);

if you want to make it a valid string in the sense that you can pass it to any of the str* functions, simply
buf[read_length] = '\0';

don't forget to check for errors read_length != -1 for instance.


text:
Q: nosuchElementException issue using iterator I have this printStackTrace when my program run into the for of a Collection
Exception in thread "main" java.util.NoSuchElementException: No next element
at positionalList.NodePositionList$IteratorList.next(NodePositionList.java:177)
at positionalList.NodePositionList$IteratorList.next(NodePositionList.java:1)
at positionalList.Ricerca.DFS(Ricerca.java:130)
at positionalList.Ricerca.main(Ricerca.java:291)

I wrote my own Iterator, and i used a head node and a tail node (with their Key set to null) to find easily the beginning and the end of the list. This class is inside the NodePositionList class, in the package positionalList
private class IteratorList<T> implements Iterator<K> {
    protected NodePositionList<K> npl;
    protected Position<K> p;

    @SuppressWarnings("unused")
    public IteratorList(NodePositionList<K> n) {
            this.npl = n;
            Position<K> p = (npl.isEmpty()) ? null : npl.first();
    }

    @Override
    public boolean hasNext() {
        return  p != tail;
    }

    @Override
    public K next() throws NoSuchElementException {
        if (p == null) {
            throw new NoSuchElementException("No next element");
        }
        K toReturn = p.element();
        p = (p == npl.getTail()) ? null : npl.next(p);
        return toReturn;
    }

    @Override
    public void remove() {
        if (p == null) {
            throw new NoSuchElementException("No element to remove");
        }
        p = npl.remove(p);
    }
}

I called it with this code, that belongs to the package "algoritmo".
public static <T extends Comparable<T>> void DFS(TDAGraph<T> g) {
    for (Vertex<T> v: g.vertices()) {
        if (v.getColor() == VertexColor.WHITE) {
            DFS_visit(g,v);
        }
    }
}

A: The problem is in your constructor:
public IteratorList(NodePositionList<K> n){
    this.npl = n;
    Position<K> p = (npl.isEmpty()) ? null : npl.first();
}

You're shadowing the variable p by creating a local variable with the same name. That "forces" the instance variable p to stay null. If you call next() for the first time, the check for null will be true, which triggers your NoSuchElementException.
Either remove the type or add this to it:
public IteratorList(NodePositionList<K> n){
    this.npl = n;
    p = (npl.isEmpty()) ? null : npl.first();
}

Or:
public IteratorList(NodePositionList<K> n){
    this.npl = n;
    this.p = (npl.isEmpty()) ? null : npl.first();
}

A: Constructor will be like this
public IteratorList(NodePositionList<K> n){
            this.npl = n;
            this.p = (npl.isEmpty()) ? null : npl.first();
    }


text:
Q: Is it ok to use "chip in" like this in an IELTS writing task I want to express that the purpose of education should serve the development of whole society.
My writing:

On one hand, in most countries, education is invested with national revenue. In other words, every tax payer is required to chip in. So, it should serve for the development of whole society.

My question:

*

*is "chip in" too informal? Should I change it?

*are these three sentences logical to a native speaker of English?

A: It is fairly informal, I would likely just use 'contribute'.
And note that in the US for example it isn't necessarily true. Many school districts are funded from property taxes rather than more general revenue sources.


text:
Q: EWS some emails are missing internet message headers I am working on a windows service that reads the inbox, archives the emails, couples the email to a ticket and put it in the database.
My problem is that we check the internetmessageheaders to see if an email is auto-submitted. But now we get an error message logged to the database every 5 seconds because the internet message headers is null.
for context the inbox is empty and it has worked before.
I did some testing and it worked fine except for 1 email i got in my test mail. It has the email headers that looks like the headers of a sent email and just like a sent email i can't get the internetmessageheaders.
Now i am left wondering if i can get the internetmessageheaders from that email or if i have to build a workaround because internetmessageheaders aren't supposed to be null on an received email


text:
Q: Azure blob storage error showing "Make sure the value of Authorization header is formed correctly including the signature." I am using restapi to fetch data from azure blob storage using the access keys.
I have a postman collection which i can use to generate the signature string for the azure using the access keys.
But when i implement the same logic in java language it fails.
It is giving me the error "403 Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.: [AuthenticationFailedServer failed to authenticate the request. Make sure the value of Authorization header is formed correctly inclu... (435 bytes)]"
here is the postman test pre req part which generate the signature string.
    // Should be UTC GMT string
    pm.environment.set("utcStr", new Date().toUTCString());

    // Get hash of all header-name:value
    const headers = pm.request.getHeaders({ ignoreCase: true, enabled: true });

    // Construct Signature value for Authorization header
    var signatureParts = [
      pm.request.method.toUpperCase(),
      headers["content-encoding"] || "",
      headers["content-language"] || "",
      headers["content-length"]  || "",
      //    pm.request.body ? pm.request.body.toString().length || "" : "",
      headers["content-md5"] || "",
      headers["content-type"] || "",
      headers["x-ms-date"] ? "" : (pm.environment.get("utcStr") || ""),
      headers["if-modified-since"] || "",
      headers["if-match"] || "",
      headers["if-none-match"] || "",
      headers["if-unmodified-since"] || "",
      headers["range"] || ""
    ];

    // Construct CanonicalizedHeaders
    const canonicalHeaderNames = [];
    Object.keys(headers).forEach(key => {
      if (key.startsWith("x-ms-")) {
          canonicalHeaderNames.push(key);
      }
    });
    // Sort headers lexographically by name
    canonicalHeaderNames.sort();

    const canonicalHeaderParts = [];
    canonicalHeaderNames.forEach(key => {
      let value = pm.request.getHeaders({ ignoreCase: true, enabled: true })[key];

      // Populate variables
      value = pm.environment.replaceIn(value);

      // Replace whitespace in value but not if its within quotes
      if (!value.startsWith("\"")) {
        value = value.replace(/\s+/, " ");
      }

      canonicalHeaderParts.push(`${key}:${value}`);
    });

    // Add headers to signature
    signatureParts.push.apply(signatureParts, canonicalHeaderParts);

    // Construct CanonicalizedResource
    const canonicalResourceParts = [
      `/${pm.environment.get("storeAcc")}${pm.request.url.getPath()}`
    ];
    const canonicalQueryNames = [];
    pm.request.url.query.each(query => {
      canonicalQueryNames.push(query.key.toLowerCase());
    });
    canonicalQueryNames.sort();
    canonicalQueryNames.forEach(queryName => {
      const value = pm.request.url.query.get(queryName);

      // NOTE: This does not properly explode multiple same query params' values
      // and turn them into comma-separated list
      canonicalResourceParts.push(`${queryName}:${value}`);
    });
    // Add resource to signature
    signatureParts.push.apply(signatureParts, canonicalResourceParts);

    console.log("Signature Parts", signatureParts);

    // Now, construct signature raw string
    const signatureRaw = signatureParts.join("\n");

    console.log("Signature String", JSON.stringify(signatureRaw));

    // Hash it using HMAC-SHA256 and then encode using base64
    const storageKey = pm.variables.get("accountKey");
    const signatureBytes = CryptoJS.HmacSHA256(signatureRaw,    CryptoJS.enc.Base64.parse(storageKey));
    console.log("signatureBytes",signatureBytes);
    const signatureEncoded = signatureBytes.toString(CryptoJS.enc.Base64);

    console.log("signatureEncoded",signatureEncoded);
    console.log("Storage Account", pm.environment.get("storeAcc"));
    console.log("Storage Key", storageKey);

    // Finally, make it available for headers
    pm.environment.set("sigStr",
       `SharedKey ${pm.environment.get("storeAcc")}:${signatureEncoded}`);

This code works and the signature i generate is authenticated  and i get access to blob apis.
but i implemented the same code in java and every time it gives me the same problem "403 Authentication error."
Java code
    public String generateOauthHeader(String method, UserDetails userFields, String baseUrl, String azureFileListUrl)  {

        String key = userFields.getAccountKey();

        DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String startDate = dateFormat.format(new Date());

        String stringToSign = method + "\\n\\n\\n\\n\\napplication/json\\n\\n\\n\\n\\n\\n\\nx-ms-date:" + "Tue, 05 Jul 2022 11:45:00 "
                + "GMT\\nx-ms-version:2020-04-08\\n/" + userFields.getAccountName() + "/"
                + userFields.getContainerName();

        if (null != azureFileListUrl) {
            azureFileListUrl =azureFileListUrl.replace("?", "");
            azureFileListUrl =azureFileListUrl.replace("=", ":");
            String[] paramlist = azureFileListUrl.split("&");

            stringToSign = stringToSign + "\\n" + paramlist[1] + "\\n" + paramlist[0];
        }
        stringToSign="\""+stringToSign+"\"";
        System.err.println("Signature string  =  " + stringToSign);
        String signature = getHMAC256(key, stringToSign);

        signature = "SharedKey " + userFields.getAccountName() + ":" + signature;
        System.err.println("Final Signature string  =  " + signature);
        return signature;
    }

    private static String getHMAC256(String accountKey, String signStr) {
        String signature = null;
        try {
            SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(accountKey), "HmacSHA256");
            Mac sha256HMAC = Mac.getInstance("HmacSHA256");
            sha256HMAC.init(secretKey);
            signature = Base64.getEncoder().encodeToString(sha256HMAC.doFinal(signStr.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return signature;
    }

I am adding below two string which are generated around same time.
The sample signatureString before signing are identical. I have printed and checked them as well.
postman= "GET\n\n\n\n\napplication/json\n\n\n\n\n\n\nx-ms-date:Tue, 05 Jul 2022 11:45:00 GMT\nx-ms-version:2020-04-08\n/osmosconnectortest/blobcontainer\ncomp:list\nrestype:container"

code = "GET\n\n\n\n\napplication/json\n\n\n\n\n\n\nx-ms-date:Tue, 05 Jul 2022 11:44:56 GMT\nx-ms-version:2020-04-08\n/osmosconnectortest/blobcontainer\ncomp:list\nrestype:container"

EDIT:
here are the headers sent with the request.
      requestHeaders.put("x-ms-date", "Tue, 05 Jul 2022 11:45:00 GMT");
      requestHeaders.put("x-ms-version", "2020-04-08");
      requestHeaders.put("Content-Type", "application/json");
      requestHeaders.put("Authorization", "SharedKey accountName:yvfdsfdssdfF0lGGtEWGU+b7BqFY0UHMkvI=
");

A: I believe the issue is with the following line of code:
requestHeaders.put("x-ms-date", "Tue, 05 Jul 2022 11:45:00 GMT");

Essentially in your request headers, you are sending the date as Tue, 05 Jul 2022 11:45:00 GMT however in your stringToSign you are sending the date as Tue, 05 Jul 2022 11:44:56 GMT in x-ms-date. This would cause the stringToSign that you are sending and the one computed by the server to mismatch and thus resulting in different authorization header values.
To fix this, please ensure that the value for x-ms-date header is the same in both stringToSign and your request headers. I would recommend passing the date object to generateOauthHeader method and use the same date object in your request headers for x-ms-date.


text:
Q: CreateEvent fails (event already exists in \BaseNamedObjects) Some time ago I wrote a small Win32 test application which did nothing else than creating an event to be used to synchronize between two processes. Coming back I was stunned by the fact that the process with CreateEvent would return with error 5 (access denied), even when run as adminstrator.
ghWriteEvent = CreateEvent(
    NULL,                       // default security attributes
    FALSE,                      // auto-reset event
    FALSE,                      // initial state is nonsignaled
    TEXT("Global\\WriteEvent")  // object name
    );

if (ghWriteEvent == NULL)
{
    printf("CreateEvent failed (%d)\n", GetLastError());
    return 1;
}

After some debugging I decided to change the events' name and suddenly it worked. By chance I decided to look at the event creation/deletion in WinObj and I saw why it failed: there already was an event called WriteEvent under \BaseNamedObjects.
What could I have possibly done to make a named event persistent across reboots and more importantly, how can I get rid of it?

Edit: It seems some other application creates WriteEvent in global namespace before my app has a chance to do so. The (now) obvious workaround is to use some unique name or to use a GUID or whatever to avoid name collision.

A: When CreateEventW fails for a named object with error code ERROR_ACCESS_DENIED then that usually means that someone else created an event with that name already. In this case the system attempts to open the event object with EVENT_ALL_ACCESS. When this access mode is incompatible with the ACLs of the calling thread the API call fails with ERROR_ACCESS_DENIED.
To work around this you will need to come up with a unique name for the event object. A common approach is to use the string representation of a GUID for the name. You can generate a GUID using the guidgen.exe tool from a Visual Studio Developer Command prompt.


text:
Q: Java code for guessing game not printing anything So I have a Computer Science course at school in which we learn Java. We were assigned to do a simple text based recreation of the guessing game. I got it done until this point, and I cannot seem to find where I messed up because there is nothing printed when I run the core.
This is the code:
    public class GuessGame
{
  public static void main(String[] args)
  {
    new GuessGame();
  }
  public GuessGame ()
  {
    char end = 'y';
    while (end!='y')
    {
      System.out.println ("Welcome to the Guessing Game!");
      System.out.println ("\nThe computer has picked a number");
      System.out.println ("between 1 and 100. Try to guess it.");
      int num = (int)(Math.random()*(100-1)+1);
      int guess = IBIO.inputInt ("Guess the number: ");
      if (guess==num)
        System.out.println ("You got it!");
      else if (guess>num)
        System.out.println ("That is too high.");
      else
        System.out.println ("That is too low.");
      end = IBIO.inputChar ("Exit game? (y/n)");
    }
  }
}

By the way, IBIO is a class provided by my IB program that we use to make Input/Output statements.
This is IBIO.java:
    public class IBIO
{
    static void output (String info)
    {
 System.out.println (info);
    }

    static void output (char info)
    {
 System.out.println (info);
    }

    static void output (byte info)
    {
 System.out.println (info);
    }

    static void output (int info)
    {
 System.out.println (info);
    }

    static void output (long info)
    {
 System.out.println (info);
    }

    static void output (double info)
    {
 System.out.println (info);
    }

    static void output (boolean info)
    {
 System.out.println (info);
    }

    static String input (String prompt)
    {
 String inputLine = "";
 System.out.print (prompt);
 try
 {
     inputLine = (new java.io.BufferedReader (new java.io.InputStreamReader (System.in))).readLine ();
 }
 catch (Exception e)
 {
     String err = e.toString ();
     System.out.println (err);
     inputLine = "";
 }
 return inputLine;
    }

    static String inputString (String prompt)
    {
 return input (prompt);
    }

    static String input ()
    {
 return input ("");
    }

    static int inputInt ()
    {
 return inputInt ("");
    }

    static double inputDouble ()
    {
 return inputDouble ("");
    }

    static char inputChar (String prompt)
    {
 char result = (char) 0;
 try
 {
     result = input (prompt).charAt (0);
 }
 catch (Exception e)
 {
     result = (char) 0;
 }
 return result;
    }

    static byte inputByte (String prompt)
    {
 byte result = 0;
 try
 {
     result = Byte.valueOf (input (prompt).trim ()).byteValue ();
 }
 catch (Exception e)
 {
     result = 0;
 }
 return result;
    }

    static int inputInt (String prompt)
    {
 int result = 0;
 try
 {
     result = Integer.valueOf (input (prompt).trim ()).intValue ();
 }
 catch (Exception e)
 {
     result = 0;
 }
 return result;
    }

    static long inputLong (String prompt)
    {
 long result = 0;
 try
 {
     result = Long.valueOf (input (prompt).trim ()).longValue ();
 }
 catch (Exception e)
 {
     result = 0;
 }
 return result;
    }

    static double inputDouble (String prompt)
    {
 double result = 0;
 try
 {
     result = Double.valueOf (input (prompt).trim ()).doubleValue ();
 }
 catch (Exception e)
 {
     result = 0;
 }
 return result;
    }

    static boolean inputBoolean (String prompt)
    {
 boolean result = false;
 try
 {
     result = Boolean.valueOf (input (prompt).trim ()).booleanValue ();
 }
 catch (Exception e)
 {
     result = false;
 }
 return result;
    }
}

Sorry for the lengthy question. Im new to Java.

A: The computer is doing exactly what you told it to. When GuessGame's constructor runs:

*

*Declare end as a char local variable and initialise it to contain 'y':
char end = 'y';

*Run the loop body while end does not contain 'y':
while (end!='y')

(since end does contain 'y' it does not run the loop body; it skips to the code after the loop).

A: The problem is that you will never enter the initial loop
char end = 'y';
while (end!='y')

You instantiate end to y, then enter only if end is not y which will always be false, hence never enter the loop.
Simply change the default value of end
char end = 'n';

Also, you don't have to cast the value 0 in your IBIO class
result = (char) 0;

You can simply do result = 0 and it will take the ASCII value.
I would also declare num and guess outside of the loop to avoid re-declaring them each time, as you did for end.
Finally, instead of declaring 7 output method with different paremeter type which simply do a System.out.println of the received parameter I would directly call System.out.println(value).
I would apply the same logic for all other methods that only call one method with the received parameter.

A: These two lines clearly contradict each other, the while loop will never execute. Initialize end to be a different value.
char end = 'y';
while (end!='y')

A: You initialize the variable char end with value 'y'.
char end = 'y';

Then the condition for your loop is
while (end!='y')

This condition is never fulfilled, that's why it's out of the loop. Change the initial value of the variable end.


text:
Q: Form input submit to table with this data Helou,
I have a form like this
<form id="some" data-request="checkout" class="checkoutForm">

                                    Name *
                                    <input class="form-control checkout-form-border" id="firstName" value="" type="text">

                                    Address *
                                    <input class="form-control checkout-form-border" id="address" value="" type="text">

etc etc ....
</form>

Now, I want on submit button show new page with collected data from this form in a table body.
Can I do this via php and jquery or new custom component?
Thanx

A: PHP:
need a submit button  in the form
need action=" " and method="post" attributes added to your form tag
need to add name attributes to your input boxes
Top of page,
if(isset($_POST['submit'])){
    $variable = $_POST['namedOfInputBox'];
    echo "

$variable

";
{

What that says is if the form is submitted (submit being name of your submit button, generally name it submit), the values coming through are these and in PHP we "echo", or print, out html code and place our variable here. You can either use :
echo "

$variable

";

or
echo "

" . $variable . "

";


text:
Q: Capturing a Multicast UDP Video stream using OpenCV I have a multi-cast UDP Video stream that I need my OPenCV (Emgu ) 2.4.x app to capture and process ("client").
On the client, I can capture the stream using VLC (udp://xx.yy.zz.aaa:1234, However the my app fails to capture this udp stream. My code is quite simple (
Capture cap = new Capture ("udp://@212.1.1.1:1234");

p.s. I have tried with and 2/o the @ also tried rtp on that address. No luck :-/
Does OpenCV directly allow "capture" of UDP streams? or do I need to run VLC on the client to re-stream the video as rtp or http or some other....?
Thanks.

A: I finally figured this out and sharing in the hope that might help others,
Capture cap = new Capture ("udp://@212.1.1.1:1234");

don't forget the @ symbol!
the capture is successfully created on the UDP Stream, however accessing the capture properties causes it to exception out and causes the error.
Long story short, the UDP stream does not appear to stream the device properties so you might need to obtain that elsewhere or code it in.
On other thing of note, that since the FPS (frames per sec) is unreliable, if not outright incorrect, you might need to make the FPS adjustable, especially if you are polling the stream  in a loop.
HTH

A: IplImage* frame;
CvCapture* pCapture;
pCapture = cvCaptureFromFile("udp://ip:port/path");
frame = cvQueryFrame(pCapture);

This will also do the job in case you don't have videoInput libraries


text:
Q: Replacing the system's soft keyboard with the customized one I created my own keyboard on my Android Project, and it works fine; here is a little snippet of code:
mKeyboard = new Keyboard(this, R.layout .keyboard);
mKeyboardView = (CustomKeyboardView) findViewById(R.id.KeyboardArea);
mKeyboardView.setKeyboard(mKeyboard);

I make it appear whenever the user touches the editText of my Activity. My problem is that the standard keyboard is still working if I press the central botton of my emulator keyboard...furthermore despite I put this:
android:windowSoftInputMode="adjustResize"

in my AndroidManifest file but it only works for the standard keyboard...so, is it possibile to completely substitute the system's soft keyboard with my customized one?

A: Try: getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
See also: How to stop Soft keyboard showing automatically when focus is changed (OnStart event)

A: You just do this....
int lastwidth;

@Override
    public void onInitializeInterface() {

        if(mKeyboard!=null){
            int diswidth = getMaxWidth();
            if(lastwidth==diswidth){
                return;
            }
            lastwidth=diswidth;
        }

        alphakeyb = new Keyboard(this, R.layout.alphakey);

    }

    @Override
    public View onCreateInputView() {

        // inflatin keyboardview from xml file
        keybview = (KeyboardView) getLayoutInflater().inflate(R.layout.customkeybview,null);

        // setting listner on keyboardview
        keybview.setOnKeyboardActionListener(this);
        // setting keyboard to keyboardview
        keybview.setKeyboard(alphakeyb);

        return keybview;

    }

You can also refer the android softkeyboard example in the API Demos


text:
Q: How to show an image from local images folder? I want to show a logo in the header of React web app. The code given below works well, but it needs that the logo is uploaded to an external images repository:

Is there any way to show a logo that is located in /images folder of the web app project instead of pointing to an external image?
import React from 'react'
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles({
  logo: {
    width: '20%',
    maxWidth: 100,
    float: 'left',
    position: 'relative',
    margin: '10px 15px 15px 10px'
  },
  author: {
    width: '20%',
    maxWidth: 100,
    float: 'right',
    position: 'relative',
    margin: '10px 15px 15px 10px',
    color: '#FFFFFF',
    textDecoration: 'none'
  }
});

export function Header() {
    const classes = useStyles();

    return (

My header

    )
}

A: import the logo from the /images
import logo from 'images/logo.png'

/*use it*/

A: use ../ to go back the upper directory and ./ for the current directory.
If the directory of your image is src/image/logo.png and src/components/Headers for the react file. Use the following code:

A: Yes you can drag the image from your file explorer and drop it in your browser and than copy and paste the url. It should look something like file:///C:/myimages/image.jpg
The problem with this approach is that you can't deploy or share your project because your users will need to have this image in the correct path on their local computer.
If you used create-react-app to create your react app than you can put it in the public folder and then in the image add the following attribute: .
This format is called "Relative URL". When you run "npm start", Webpack serves the public folder and when the browser sees "/image.jpg" it will go to the the root of the served folder(public in our case) and search for "image.jpg".


text:
Q: Javascript dynamically change another page, is what I'm trying to do possible? I was wondering if it was possible to change another page that's not opened yet, when a user clicks a link from the first page. It's hard to explain, but I'll try to show you what I mean with an example below.
The html is more complex for the actual site, but here is a watered-down version:
Index:

Product Page:

  all of product 1 info and pictures

  all of product 2 info and pictures

So basically, is it possible just using javascript, no php or anything, when product1 image is clicked to only show the product1 info on the product page and when product2 is clicked only show the info for product 2 on the page. I've been trying to find something similar but as of yet haven't, which leads me to believe I may not be able to do it, but I thought I would ask.
My javascript document doesn't have much in it, because I haven't been able to figure it out, but I have been playing around trying to make their display = none. I haven't been able to get a variable to continue onto the next page, if you know what I mean. Sorry, I only have a basic understanding of Javascript.

A: The technique that you're looking for is a combination of DHTML (Dynamic HTML) and AJAX (Asynchronous JavaScript and XML).
DHTML:
The idea behind DHTML is that when the user requests an HTML page from the server, the server responds with that page, as well as other data that may be needed if a user were to perform certain actions, such as clicking on a product image.
The data that the server returns to the HTML page, upon initial pageload, is generally hidden by default. For instance, the DOM of the page is loaded, but it may have style="display:none" on the elements.
Once a user initiates a certain action, the page uses JavaScript to manipulate the elements on the page that are visible, as well as the ones that may be hidden.
Consider the following page:

          back to Product Categories

                 ...
                 ...

                 ...
                 ...

          </div

The above page is split up into two sections, one with the id="page1" and the other id="page2". By default, we hide page 2.
When a user clicks on the link for a product, we hide page 1 and show page 2:
document.getElementById("page1").setAttribute("style","display:none");
document.getElementById("page2").setAttribute("style","display:block");

Additionally, depending on which link was clicked, we also unhide the product details for the product that was clicked, and hide the details for the product that wasn't. For example, if product 1 is clicked, we show product 1:
document.getElementById("prod2").setAttribute("style","display:none");
document.getElementById("prod1").setAttribute("style","display:block");

The end result is that only the page2 div is displayed. If the user clicks the "back to Product Categories" link, we reverse the process, hiding page2 and showing page1.
In summary, this type of manipulation can be done completely on the client-side, without any PHP or server-side code, simply using HTML, JavaScript, and CSS, as pointed out by @Marcel. However, the use of pure DHTML is more of an academic exercise than a practical solution, since the server-side maintains customer data, product data, and everything that would be required in a professional, revenue generating product.
AJAX:
AJAX, on the other hand, is quite similar to DHTML and may even be considered an extension of DHTML. The idea behind AJAX is that -- when the user initiates an action -- the page requests data from the server. When the server responds, the data is handed-off to a callback function that then manipulates the page using the data.
In your particular example, you might use a combination of both DHTML and AJAX to pull off the desired effects. Consider the following page, which uses AJAX to pull in the relevant HTML for the product the user selects:

In the above example, when the user clicks on a link for a product, the server responds with just enough HTML to sufficiently replace the div#container portion of the page:

Product Name 1

Product details...

This is injected into the page so that the DOM would then look like this:

Product Name 1

Product details...

Summary:
This question is tagged JavaScript, not jQuery, so the answers are focused on JavaScript, but the techniques described in the DHTML section are utilized in many JavaScript libraries. For example, see jQuery Mobile's Multi-Page Template for a demo of the technique you describe.

A: You could change the link to add parameter. This way PRODUCTPAGE.html knows which link you clicked.

Inside PRODUCTPAGE.html you could parse the URL using JavaScript and display only specific product's data.

A: Yes you can hide and show different parts of the DOM via javascript.
Check out this example of a toggle for an idea of what you need to do.


text:
Q: Environment variable is not assigning with Typescript My code is:
const port: Number = process.env.PORT || 3000;

[ts]
Type 'string | 3000' is not assignable to type 'Number'.
  Type 'string' is not assignable to type 'Number'.

I tried
const port: Number = parseInt(process.env.PORT, 10) || 3000;

But it gives me another error:
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.
(property) NodeJS.Process.env: NodeJS.ProcessEnv

What am I doing wrong?

A: const port: Number = parseInt(<string>process.env.PORT, 10) || 3000

This solved it. I think it's called Type Assertion

A: I usually do this.
const PORT = Number(process.env.PORT ?? 3000);

A: This should work as well.

const port: Number = parseInt(process.env.PORT as string, 10) || 3000


text:
Q: form-control no aplica formato Por algún motivo, siguiendo un tutorial al pie de la letra e incluso copiando y pegando código no consigo que form-control funcione.
Ya intenté escribiendolo en el HTML como .form-control y tampoco funciona, estoy usando bootstrap-4.4.1-dist, copié y pegué las carpetas de bootstrap (css y js) dentro de la carpeta de mi proyecto.
Dejo una imagen de como se ve en el navegador.
Google chrome no funciona en mi PC (crashea al abrir y reinstalarlo no sirvió de nada) por lo que solo puedo visualizar en mozilla y edge, en ambos se ve mal.
    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="flogin/css/bootstrap.css">
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">

Contactenos

        <form method="POST" name="fcontacto" id="fcontacto" action="./">
            Tu nombre:
            <input type="text" name="name" id="name" class="form-control">
             Tu email
            <input type="text" name="email" id="email" class="form-control">
             Asunto:
            <input type="text" name="asunto" id="asunto" class="form-control">
             Tu Mensaje:
            <textarea name="mensaje" id="mensaje" cols="30" rows="10" class="form-control"></textarea>
        </form>

  * {
    margin: 0px;
    padding: 0px;
}

body {
    font-family: 'Montserrat', sans-serif;
}

.ibody {
    background-color: #ecf0f3;
    margin: 30px auto;
    width: 500px;
}

.jumbotron {
    padding: 16px;
}

.jumbotron h1 {
    font-size: 26px;
    text-align: center;
}

A: Como bien muestra la documentación Bootstrap, en su página oficial, para hacer uso de todos los componentes de este framework, se debe de hacer referencia a los archivos que este posee:
Para hacer referencia a CSS, se debe se colocar lo siguiente en el head de tu archivo html:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Y los archivos JS, deben de ir de preferencia al final del template, antes de terminar el body:

O de otra manera puedes descargar los archivos, como menciona en este apartado de la página oficial, en la misma especifica los pasos a seguir para que todos los componentes descargados funcionen correctamente.
Resultado final:

* {
            margin: 0px;
            padding: 0px;
        }

        body {
            font-family: 'Montserrat', sans-serif;
        }

        .ibody {
            background-color: #ecf0f3;
            margin: 30px auto;
            width: 500px;
        }

        .jumbotron {
            padding: 16px;
        }

        .jumbotron h1 {
            font-size: 26px;
            text-align: center;
        }
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="flogin/css/bootstrap.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">

Contactenos

        <form method="POST" name="fcontacto" id="fcontacto" action="./">
            Tu nombre:
            <input type="text" name="name" id="name" class="form-control">
             Tu email
            <input type="text" name="email" id="email" class="form-control">
             Asunto:
            <input type="text" name="asunto" id="asunto" class="form-control">
             Tu Mensaje:
            <textarea name="mensaje" id="mensaje" cols="30" rows="10" class="form-control"></textarea>
        </form>


text:
Q: How does Professor McGonagall know about the Golden Trio's conversation? In The Order of the Phoenix, there's this conversation between Harry and Professor McGonagall at the end of the twelfth chapter.

"Didn't you listen to Dolores Umbridge's speech at the start-of-term feast, Potter?"
  "Yeah," said Harry. "Yeah... she said... progress will be prohibited or... well, it meant that... that the Ministry of Magic is trying to interfere at Hogwarts."
  Professor McGonagall eyed him for a moment, then sniffed,  walked around her desk, and held open the door for him.
  "Well, I'm glad you listen to Hermione Granger at any rate."

Did some of you notice that the professor is talking about Hermione, when she can't possibly know the talk between Harry, Ron, and Hermione at the feast? When they were talking about it, they were sitting at the Gryffindor table, weren't they? Professor McGonagall was sitting at the professor's table, which is far away from them and it's really impossible to hear student's conversations. Well, I wonder how she knows. The professors really couldn't be spying on students,  could they?

A: She doesn't know that it happened, but she can make an educated guess
The implication is that McGonagall (correctly) assumed that Harry hadn't actually understood the subtext of Umbridge's speech, and is regurgitating an analysis given to him by somebody else. Since Hermione is one of his best friends, as well as the sort of person who would have understood that subtext, it's a pretty safe bet that she's the one who told him; no espionage necessary
There are a few clues to this effect:

*

*Harry is quoting Hermione more-or-less verbatim; McGonagall is likely to recognize the words of one her long-time students, even though Harry's the one saying them1

*Harry's incredibly naive approach to dealing with Umbridge makes it clear that he either doesn't understand the gravity of her appointment (that is, the implications of the Ministry foisting a teacher upon Dumbledore, who otherwise acts largely autonomously to the government), or he just doesn't care. Either is as likely as the other, knowing Harry, which brings me to:

*

*As a subpoint to this, it's worth pointing out that McGonagall subltly tests Harry's perceptions earlier in their conversation; by his reaction, Harry clearly doesn't really understand the danger posed by Umbridge:

"Misbehavior in Dolores Umbridge's class could cost you much more than House points and a detention."
"What do you - ?"
"Potter, use your common sense," snapped Professor McGonagall, with an abrupt return to her usual manner. "You know where she comes from, you must know to whom she is reporting."
Harry Potter and the Order of the Phoenix Chapter 12: "Professor Umbridge"

*He struggles to remember what Umbridge actually said (note the ellipses in his speech, indicating pauses for recollection and uncertainty), despite having heard it only the night before, but easily recalls the one-sentence summary. Clearly the speech didn't make much of an impression on him.

*

*Recall also my sub-point above: there's an incongruity between Harry's responses in the two conversations. At first he has absolutely no idea what Umbridge's presence represents, but when prompted with a specific memory he suddenly does. Again, sure indication that he didn't puzzle it out on his own

Bear in mind that McGonagall has been teaching Harry and Hermione for four years by this point; she sees how they contribute in lessons, and how they perform on homework assignments and exams. It seems quite reasonable that she'd be able to guess this.

1 Credit where it's due; Valorum made this same point in a now-deleted answer


text:
Q: Android - font (only letters) background color I want to make in my application some meme - type images.
I've found some fonts, which I can use, but one thing, which is connecting them is, that when I'm changing textColor property for TextView, which is contining text, I'm changing contour of letters, not whole letter color. When I'm changing background color, I'm changing whole TextView field background (and I want it to be transparent). And the problem is, that in letter I can see background image of photo, which is under the letter, which is problem, because photos can have different colors and text could be not visible. Is there any possibility, to change background color, but only for letters? Or it is a job for someone who is working with graphics and fonts?

There is a photo, which is from my app, which is showing problem.

And there, what I'm looking for:

(source: canada.com)

A: It sounds like you want to change the text colour not the background colour.
The thing is fonts are all defined like small bitmaps, if you change the colour only the opaque bits will be colourised never the bit's which were left transparent.
I think your only option is to change font

A: It sounds like what you want is text outline or a text shadow. This question has both of those already answered. Or you could instead use solid font types.


text:
Q: this.subject() returns already destroyed object at beginning of test I have several qunit tests for my ember model.
When I try to save my model, it raises
Assertion Failed: calling set on destroyed object
And when I run this this.subject().get('isDestroyed') it returns true.
What is going on here?

A: This ended up solving the problem for me: https://github.com/rwjblue/ember-qunit/issues/83#issuecomment-95990645


text:
Q: how can I query last month data in elasticsearch I want to get last month data from elasticsearch.
For example, today is 09/08/2019, so the last month data should be from 01/07/2019 - 31/07/2019.
I try to set the time range "gte": "now+1m-1M/M", "gte" is greater than or equal to, it will return the data from 01/07/2019 (the first day of last month) to 09/08/2019 (today).
I think to make it query with the correct date range, I need to specify the upper bound using "lte" - less than or queal to. How can I define the last day of the month?
{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "now+1m-1M/M",
        "time_zone": "+00:00"
      }
    }
  }
}

A: What I would do is to add an lt constraint on the beginning of the current month, like this:
{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "now+1m-1M/M",
        "lt": "now/M",
        "time_zone": "+00:00"
      }
    }
  }
}


text:
Q: Debian/Ubuntu is it possible to reinitialize /var/lib/apt/lists and /var/apt/cache after deleting them? Is it possible to restore the functionality of /var/lib/apt/lists and /var/apt/cache after deleting them or minmizing them in some wa
I am trying to shrink down an Ubuntu VM to the smallest size and decided to delete /var/lib/apt/lists and /var/cache/apt with the intention of restoring them when the system needs to be updated. I have done /var/cache/apt without major side effects, simply recreating some directories reenables it. The /var/lib/apt/lists is the one I am unsure of. Is it possible delete it and restore its functionality by recreating like /var/cache/apt?
Does doing that destroy the knowledge apt and dpkg have of the systems configuration or is that stored elsewhere?

A: On Ubuntu 10.04 LTS the directories are not recreated. So you have to be careful not to delete these.
You can use the following command to delete only the files.
sudo find /var/cache/apt/ -type f -exec rm -v {} \;
sudo find /var/lib/apt/lists -type f -exec rm -v {} \;

To recreate the cache use
sudo apt-get update

A better answer is probably Debian/Ubuntu - How to restore /var/cache/apt structure after deleting it?

A: Yes, you can delete them!
Let's clone a VM and see what happens! :)
$ rm -r /var/cache/apt /var/lib/apt/lists
$ apt-get update #takes a while re-fetching everything
$ apt-get install <some-random-package>

Directories are recreated from the apt-get update operation and all is well. I might leave the *.gpg files alone if you're feeling paranoid, but otherwise those files are all ok to disappear.
In the past, I've had issues where I've had to manually mkdir /var/cache/apt/archives, but that no longer seems to be an issue.


text:
Q: Assertion failure when trying to write (INSERT, UPDATE) to sqlite database on iPhone I have a really frustrating error that I've spent hours looking at and cannot fix. I can get data from my db no problem with this code, but inserting or updating gives me these errors:

*** Assertion failure in +[Functions db_insert_answer:question_type:score:], /Volumes/Xcode/Kanji/Classes/Functions.m:129

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error inserting: db_insert_answer:question_type:score:'

Here is the code I'm using:

    [Functions db_insert_answer:[[dict_question objectForKey:@"JISDec"] intValue] question_type:@"kanji_meaning" score:arc4random() % 100];

    //update EF, Next_question, n here
    [Functions db_update_EF:[dict_question objectForKey:@"question"] EF:EF];

To call these functions:

+(sqlite3_stmt *)db_query:(NSString *)queryText{
    sqlite3 *database = [self get_db];
        sqlite3_stmt *statement;
    NSLog(queryText);
    if (sqlite3_prepare_v2(database, [queryText UTF8String], -1, &statement, nil) == SQLITE_OK) {
    } else {
        NSLog(@"HMM, COULDNT RUN QUERY: %s\n", sqlite3_errmsg(database));
    }
    sqlite3_close(database);
    return statement;
}
+(void)db_insert_answer:(int)obj_id question_type:(NSString *)question_type score:(int)score{
    sqlite3 *database = [self get_db];
        sqlite3_stmt *statement;
    char *errorMsg;
    char *update = "INSERT INTO Answers (obj_id, question_type, score, date) VALUES (?, ?, ?, DATE())";
    if (sqlite3_prepare_v2(database, update, -1, &statement, nil) == SQLITE_OK) {
        sqlite3_bind_int(statement, 1, obj_id);
        sqlite3_bind_text(statement, 2, [question_type UTF8String], -1, NULL);
        sqlite3_bind_int(statement, 3, score);
    }
    if (sqlite3_step(statement) != SQLITE_DONE){
        NSAssert1(0, @"Error inserting: %s", errorMsg);
    }
    sqlite3_finalize(statement);
    sqlite3_close(database);
    NSLog(@"Answer saved");
}
+(void)db_update_EF:(NSString *)kanji EF:(int)EF{
    sqlite3 *database = [self get_db];
        sqlite3_stmt *statement;
    //NSLog(queryText);
    char *errorMsg;
    char *update = "UPDATE Kanji SET EF = ? WHERE Kanji = '?'";
    if (sqlite3_prepare_v2(database, update, -1, &statement, nil) == SQLITE_OK) {
        sqlite3_bind_int(statement, 1, EF);
        sqlite3_bind_text(statement, 2, [kanji UTF8String], -1, NULL);
    } else {
        NSLog(@"HMM, COULDNT RUN QUERY: %s\n", sqlite3_errmsg(database));
    }
    if (sqlite3_step(statement) != SQLITE_DONE){
        NSAssert1(0, @"Error updating: %s", errorMsg);
    }
    sqlite3_finalize(statement);
    sqlite3_close(database);
    NSLog(@"Update saved");
}

+(sqlite3 *)get_db{
    sqlite3 *database;

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *copyFrom = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"/kanji_training.sqlite"];
    if([fileManager fileExistsAtPath:[self dataFilePath]]) {
        //NSLog(@"DB FILE ALREADY EXISTS");
    } else {
        [fileManager copyItemAtPath:copyFrom toPath:[self dataFilePath] error:nil];
        NSLog(@"COPIED DB TO DOCUMENTS BECAUSE IT DIDNT EXIST: NEW INSTALL");
    }
    if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
        sqlite3_close(database); NSAssert(0, @"Failed to open database");
        NSLog(@"FAILED TO OPEN DB");
    } else {
        if([fileManager fileExistsAtPath:[self dataFilePath]]) {
            //NSLog(@"DB PATH:");
            //NSLog([self dataFilePath]);
        }
    }
    return database;
}

+ (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:@"kanji_training.sqlite"];
}

I really can't work it out! Can anyone help me?
Many thanks.

A: in db_insert_answer, you prepare your statement
if the prepare is SQLITE_OK, you bind your variables
however, regardless of preparation OK or not, you run the statement (which could be invalid)
you also do the same thing in db_update_EF
start there

A: char *update = "UPDATE Kanji SET EF = ? WHERE Kanji = '?'";

Replace it with
char *update = "UPDATE Kanji SET EF = ? WHERE Kanji = ?";

It's already a string. You don't need single quotes around that question mark.


text:
Q: Communication between client class library and web service / web service and server class library Wondering what others do / best practice for communicating between layers. This question relates to communication between layers 2-3 and 3-4.
Our Basic Architecture (in order) as follows:

*

*UI

*Front End Business Classes

*Web Services

*Back End Business Classes

*DAL

The web services are just a façade that include logging and authentication to back end class libraries.
As such, the web service is passed a request object that includes the parameters required by the web method along with the user credential (the user credential for example is stored in a base class as we will always need to pass this to the webservice) and responds with response objects (has things such as status and message, if failed etc along with the object required) both request & response use a custom generic class/or interface where only one result is returned, otherwise a class needs to be created.
Sometimes it makes sense to do this for the response object at layer 4 (though we don't use a request object unless a lot of parameters need to be pasaws), in which case we just have an adapter class in layer 3 which returns this to the client. For consistency I have considered doing this all the time, though think it may be overkill.
So to iterate the question, what are the best practices for communicating between layers? and should/do people use this method outlined above (it works well for us) and should layers 3-4 implement similar method to 2-3?
Possible considerations:

*

*currently everything is coded in house by a team of developers, some client code may be outsourced in the future

*future web services will be WCF based (not sure if that effects design other than coding to interfaces which I would prefer anyway).

*We use .net

A: For the sake of completeness:
It seems a good idea to have the response / requests in the class library, that way if you want to change the web service to WCF, there is less work to do.


text:
Q: Modelling and Invoice table to hold both AP and AR All,
We are having an internal debate about the best way to model an invoicing system that needs to keep track of both accounts receivable and accounts payable invoices.
In our system when an invoice arrives the invoices can have their data changed so that the values on the 2 invoices are different.  For instance the AP and AR terms might be different or we may decide to add a surcharge to the AR invoice that is not on the AP invoice.
We have one side that believes the Invoice table should contain a "type" field that denotes either AP or AR in it.
The other side believes that we should create 2 separate physical tables.  One to hold the AP invoice data and one to hold the AR invoice data.  In this case not only is the invoice "header" record duplicated but so are the line item and tax tables.
I have searched for "double entry accounting schemas" and cannot find a conclusive answer that I can bring to the team.  I have seen a few examples of using a "type" field and I cannot seem to find any examples where the table schemas are duplicated and only the names are changed.
Is there anyone that can provide me links to credible sources that I can use to convince people the correct path to go along?
FYI - I am firmly in the "type" camp because there will be other data structures and process that need a foreign key relationship to the Invoice table and I would prefer to have only one key field that is a required link to the Invoice table rather than a joining table where either the AccountsPayableInvoiceKey or the AccountsReceivableInvoiceKey is required and the other one is blank.
Thanks in advance.
Tony


text:
Q: Redundant Apache RewriteRules, is there a way to shorten them? I feel my Rewriterules are a bit redundant. Is there a way to shorten the following htaccess code,into one line please? I'm thinking it would use an * somewhere, but I just can't figure it out xD
RewriteRule ^([^/\.]+)?$ index.php?year=$1 [L]

RewriteRule ^([^/\.]+)/?$ index.php?year=$1 [L]

RewriteRule ^([^/\.]+)/([^/\.]+)?$ index.php?year=$1&month=$2[L]

RewriteRule ^([^/\.]+)/([^/\.]+)/?$ index.php?year=$1&month=$2[L]

RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)?$ index.php?year=$1&month=$2&day=$3[L]

RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ index.php?year=$1&month=$2&day=$3[L]

RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)?$ index.php?year=$1&month=$2&day=$3&post=$4[L]

RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ index.php?year=$1&month=$2&day=$3&post=$4[L]

RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)?$ index.php?year=$1&month=$2&day=$3&post=$4&action=$5 [L]

RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ index.php?year=$1&month=$2&day=$3&post=$4&action=$5 [L]

Thank you!
Currently, a php script checks if each GET parameter is set, and depending on which parameter is available, it does a different task. My PHP code works perfectly, no problem, but I am only wondering if there is a way to shorten the apache rules above. I also realize that this way of parsing GET parameters may create many many loopholes, so I appreciate any advice or feedback! :) Thanks a lot ^_^

A: You are wanting everything to goto index.php?
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /

RewriteRule . index.php$1 [L,NC]
</IfModule>