text:
Q: How To Properly Handle Passwords In C# It's a well known fact that C# string is pretty insecure, it's not pinned in RAM, the Garbage Collector can move it, copy it, leave multiple traces of it in RAM and the RAM can be swapped and be available as a file to be read, not mentioning several other known facts.
In order to mitigate this Microsoft came up with SecureString. The thing is: what is the proper way of using it?
I ask this because sooner or later you will have to extract the inner string. And yes, SecureString does allow us to write one char at a time and gives us some other minor usages while hiding it's secret, but sometimes we need the whole string at once or something like it. So far all implementations I see use a regular string at the end, with the extracted and decrypted content from the SecureString which I think (or hope) it's avoidable in some cases even though it might involve some complicated code to get around a .NET string.
In my case I use a library for password hashing called BCrypt. It uses a regular string for calculating the hashes, which I think is far from ideal. I didn't find any libraries that would accept a SecureString directly, so I don't have much of an option but use it.
Currently I run code such as this:
SecureString password; // This usually comes from a PasswordBox Property
IntPtr passwordBSTR = Marshal.SecureStringToBSTR(password);

string insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);
Marshal.ZeroFreeBSTR(passwordBSTR);
passwordBSTR = default(IntPtr);
password.Clear();

// Use the insecurePassword....usually as:
bool result = BCrypt.Net.BCrypt.Verify(insecurePassword, user.Password); // This hashes the provided password and compares it with another BCrypt hash.

insecureString = string.Empty; // hoping for the GC to act now, fingers crossed.

// use result and etc...

This way the password raw string will be copied multiple times for the BCrypt method and probably even more times inside it.
This makes some questions arise in my mind:
1 - Are BSTR strings like C strings in the sense of memory management? Are they pinned in RAM and I can manipulate them and erase them as I see fit so it will be more secure to use them in C# or interop it with a C++ code so I can eliminate a lot of my .NET string manipulations (like verifying if the password string is null or white space or has the correct length or has the desired password strength)?
2 - If question's #1 answer is "yes" then should I invest some time to pass the BSTR string to a interop C++ code to calculate it's hash and verify?
3 - Is my later code correct or am I missing something on SecureString manipulation?
Just to be clear: My main intent with this question is to evaluate if I should pass all my password handling code to C++ from my C# (probably using C++/CLI or interop) to achieve a more secure code than what C# has to offer. This scenario really concerns me for password string hashing were multiple strings will be created and copied with the user's secret information scattered all over the RAM.
As an example: I could make a method like:
public string SecureHash(SecureString password)

And this method will extract the SecureString value and pass it as a BSTR string (or other extraction option, I honestly don't know the benefits between them) to a C++ hashing method, so we can control all the places our password sits in memory.
I ask this to not have a huge work refactoring my code and in the end discover it was all for nothing because I was using SecureStrings wrongly all the time and there are already solutions for this, or a false sense of security, as it happens sometimes, since I am not aware of how BSTR strings are implemented in memory or the other SecureStrings extraction options (Unicode, ANSI and etc).

A: *

*Marshal.SecureStringToBSTR() will create a BSTR string (i.e. an array of bytes) in unmanaged memory and return a pointer to it; it means the underlying value is pinned. The value itself is a sequence of Unicode characters representing your string, prefixed with string length, and followed by two subsequent null characters (https://msdn.microsoft.com/en-us/library/windows/desktop/ms221069(v=vs.85).aspx).
On the other hand, Marshal.PtrToStringBSTR() will return a .Net System.String object, which is insecure.

*I would say your options are:

*

*Convert your SecureString object to unmanaged object and then pass to any
unmanaged library which calculates hashes

*Use SecureString everywhere in your stack, in your case it means to rewrite BCrypt.Net to work with SecureString objects (the library is open source and really small: https://bcrypt.codeplex.com/SourceControl/latest#BCrypt.Net/BCrypt.cs), or find an alternative managed implementation. But since SecureString doesn't provide methods to read its data, you will need to convert it to, most likely unmanaged, string anyway at some point (you can use that unmanaged data from your managed code though).

*You're missing correct disposal of SecureString (either within "using" or try/finally).

A: How about an extension method to the SecureString:
using System;
using System.Runtime.InteropServices;

public static class SecureStringExtensions
{
    public static T Decrypt<T>(this SecureString ss, Func<string, T> handler)
    {
        if (handler == null)
        {
            throw new ArgumentNullException(nameof(handler));
        }

        var ptr = Marshal.SecureStringToBSTR(ss);
        try {
            return handler(Marshal.PtrToStringBSTR(ptr));
        } finally {
            Marshal.ZeroFreeBSTR(ptr);
        }
    }
}

This way, the decrypted string stays on the stack and will get quickly overwritten by future stack variables.

A: Why not use a one way crypt (HASH)?  Save the random salt with the crypted password and push those 2 value around.  That way you can crypt the password you want to check with the same salt and compare the encrypted values.  I would recommend SHA-256 or stronger.
As for security, this is pretty much the same method Microsoft uses in C# AspNet Membership.  Since this is pretty much industry standard with Dot Net, this level of security should work for you as well.
Here is a good source to look at how to do that:
http://www.obviex.com/samples/hash.aspx


text:
Q: What is the fundamental reason why information is on the event horizon of a black hole? I don't know the mathematics behind black holes and information theory but is there a simple explanation of why information is on the event horizon. Why can't it be elsewhere?

A: I'm going to answer the question you actually asked, but as you'll see, this is probably not quite the question you really wanted.
A possibly intuitive argument for it is information conservation. The basic idea behind this is Laplace's idea that if you knew the state of the universe perfectly at one instant of time, you could predict its entire future and deduce its entire past from that slice by applying the laws of motion. All the information about the entire 4D history of the universe is encoded in every 3D instant-of-time slice.
In general relativity, the slices can curve and bend, but the same general principle applies. If we take a surface that intersects (cuts) every worldline running from the beginning of the universe to the end exactly once, then the entire past and future of the universe can be determined from its state on that slice. This is called a Cauchy surface.
And if we have a region of spacetime surrounded by a surface such that every worldline passing through that region has to cross the surface, then what happens on the surface determines everything that happens inside the region. This is close to being the defining property of the event horizon of a black hole. All the information about what happens inside the black hole has to pass through the event horizon, and all the information that passes through the event horizon ends up in the black hole. If we know the state of the universe on the event horizon, we can use Laplace's 'Clockwork Universe' principle and the laws of physics to deduce everything that happens subsequently, inside the black hole. So all the information in the interior of the black hole is on the surface - or more precisely, passes through the surface.
That is certainly not the end of the story. The main reason physicists talk about information being 'on' the event horizon is that the Bekenstein-Hawking formula for the entropy of a black hole says it is proportional to the event horizon area. Laplace's idea tells us that all the information passes through the horizon, but gives no reason to expect it to do so uniformly. It is not clear why the information should be proportional to area. And of course we can consider concentric spheres inside the event horizon which also have the property that every worldline must pass through them, and must therefore also contain all the information, but which have a smaller surface area. What is special about the outermost of them; the event horizon? (There are special properties known, e.g. it's a null surface, but not reasons why that specialness should lead to this result.) I have not seen anyone give a clear and convincing answer, that doesn't amount to numerology (i.e. speculative deductions of deeper causes made from observing numerical coincidences). This is one of the current mysteries in physics.
There is a nice, fairly basic discussion of Cauchy surfaces and the implications for black holes and the information paradox in philosopher Tim Maudlin's (Information) Paradox Lost. Because he deliberately takes a provocative and controversial stance (which is good for science, of course), it's appropriate to point to replies, like (Information) Paradox Regained?
A Brief Comment on Maudlin on Black Hole Information Loss.
In summary - all the information about the interior of a black hole is deducible (by Laplace's 'Clockwork Universe' principle) from the state of the universe on the event horizon. The information is certainly there. But when physicists say this, they're talking about something different, which is that in a lot of calculations the information inside a closed region like a black hole or an entire universe is proportional to the area of the boundary. So far as I know, the reason for this is not currently understood.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to run command rasa train I'm trying to install my first rasa project but when I run rasa train I get those error messages. can someone help me? (Sorry If is too messy its my first time in StackOverflow)
(venv) ➜  rasa-init-demo rasa train
The configuration for policies and pipeline was chosen automatically. It was written into the config file at 'config.yml'.
Training NLU model...
2021-02-08 18:38:15 INFO     rasa.shared.nlu.training_data.training_data  - Training data stats:
2021-02-08 18:38:15 INFO     rasa.shared.nlu.training_data.training_data  - Number of intent examples: 69 (7 distinct intents)
2021-02-08 18:38:15 INFO     rasa.shared.nlu.training_data.training_data  -   Found intents: 'deny', 'goodbye', 'mood_unhappy', 'affirm', 'greet', 'mood_great', 'bot_challenge'
2021-02-08 18:38:15 INFO     rasa.shared.nlu.training_data.training_data  - Number of response examples: 0 (0 distinct responses)
2021-02-08 18:38:15 INFO     rasa.shared.nlu.training_data.training_data  - Number of entity examples: 0 (0 distinct entities)
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Starting to train component WhitespaceTokenizer
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Finished training component.
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Starting to train component RegexFeaturizer
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Finished training component.
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Starting to train component LexicalSyntacticFeaturizer
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Finished training component.
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Starting to train component CountVectorsFeaturizer
2021-02-08 18:38:15 INFO     rasa.nlu.featurizers.sparse_featurizer.count_vectors_featurizer  - 80 vocabulary slots consumed out of 1080 slots configured for text attribute.
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Finished training component.
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Starting to train component CountVectorsFeaturizer
2021-02-08 18:38:15 INFO     rasa.nlu.featurizers.sparse_featurizer.count_vectors_featurizer  - 697 vocabulary slots consumed out of 1697 slots configured for text attribute.
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Finished training component.
2021-02-08 18:38:15 INFO     rasa.nlu.model  - Starting to train component DIETClassifier
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py", line 584, in converted_call
converted_f = conversion.convert(target_entity, program_ctx)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/impl/conversion.py", line 118, in convert
transformed, module, source_map = _TRANSPILER.transform_function(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/pyct/transpiler.py", line 411, in transform_function
factory = self._transformed_factory(fn, caching_subkey, user_context,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/pyct/transpiler.py", line 373, in _transformed_factory
nodes, ctx = self._transform_function(fn, user_context)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/pyct/transpiler.py", line 339, in _transform_function
node = self.transform_ast(node, context)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/impl/conversion.py", line 69, in transform_ast
node = qual_names.resolve(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/pyct/qual_names.py", line 252, in resolve
return QnResolver().visit(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 371, in visit
return visitor(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 456, in generic_visit
new_node = self.visit(old_value)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 371, in visit
return visitor(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 447, in generic_visit
value = self.visit(value)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 371, in visit
return visitor(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/pyct/qual_names.py", line 217, in visit_Name
node = self.generic_visit(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 456, in generic_visit
new_node = self.visit(old_value)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 371, in visit
return visitor(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/pyct/qual_names.py", line 230, in visit_Subscript
node = self.generic_visit(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 456, in generic_visit
new_node = self.visit(old_value)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 371, in visit
return visitor(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 447, in generic_visit
value = self.visit(value)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 371, in visit
return visitor(node)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/pyct/qual_names.py", line 232, in visit_Subscript
if not isinstance(s, gast.Index):
AttributeError: module 'gast' has no attribute 'Index'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/bin/rasa", line 8, in
sys.exit(main())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/main.py", line 116, in main
cmdline_arguments.func(cmdline_arguments)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/cli/train.py", line 58, in
train_parser.set_defaults(func=lambda args: train(args, can_exit=True))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/cli/train.py", line 90, in train
training_result = rasa.train(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/train.py", line 94, in train
return rasa.utils.common.run_in_loop(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/utils/common.py", line 308, in run_in_loop
result = loop.run_until_complete(f)
File "uvloop/loop.pyx", line 1456, in uvloop.loop.Loop.run_until_complete
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/train.py", line 163, in train_async
return await _train_async_internal(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/train.py", line 342, in _train_async_internal
await _do_training(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/train.py", line 388, in _do_training
model_path = await _train_nlu_with_validated_data(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/train.py", line 811, in _train_nlu_with_validated_data
await rasa.nlu.train(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/nlu/train.py", line 116, in train
interpreter = trainer.train(training_data, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/nlu/model.py", line 209, in train
updates = component.train(working_data, self.config, **context)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/nlu/classifiers/diet_classifier.py", line 816, in train
self.model.fit(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/utils/tensorflow/models.py", line 220, in fit
) = self._get_tf_train_functions(eager, model_data, batch_strategy)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/utils/tensorflow/models.py", line 481, in _get_tf_train_functions
self._get_tf_call_model_function(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/utils/tensorflow/models.py", line 464, in _get_tf_call_model_function
tf_call_model_function(next(iter(init_dataset)))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 780, in call
result = self._call(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 823, in _call
self._initialize(args, kwds, add_initializers_to=initializers)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 696, in _initialize
self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 2855, in _get_concrete_function_internal_garbage_collected
graph_function, _, _ = self._maybe_define_function(args, kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 3213, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 3065, in _create_graph_function
func_graph_module.func_graph_from_py_func(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py", line 986, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 600, in wrapped_fn
return weak_wrapped_fn().wrapped(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py", line 962, in wrapper
return autograph.converted_call(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py", line 591, in converted_call
return _fall_back_unconverted(f, args, kwargs, options, e)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py", line 398, in _fall_back_unconverted
return _call_unconverted(f, args, kwargs, options)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py", line 339, in _call_unconverted
return f(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/utils/tensorflow/models.py", line 293, in train_on_batch
prediction_loss = self.batch_loss(batch_in)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/nlu/classifiers/diet_classifier.py", line 1417, in batch_loss
sequence_lengths = self._get_sequence_lengths(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rasa/utils/tensorflow/models.py", line 1112, in _get_sequence_lengths
sequence_lengths = tf.ones([batch_dim], dtype=tf.int32)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/util/dispatch.py", line 201, in wrapper
return target(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/ops/array_ops.py", line 3041, in ones
output = _constant_if_small(one, shape, dtype, name)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/ops/array_ops.py", line 2732, in _constant_if_small
if np.prod(shape) < 1000:
File "<array_function internals>", line 5, in prod
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/core/fromnumeric.py", line 3030, in prod
return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/core/fromnumeric.py", line 87, in _wrapreduction
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/framework/ops.py", line 845, in array
raise NotImplementedError(
NotImplementedError: Cannot convert a symbolic Tensor (strided_slice_6:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported
Rasa Version     : 2.2.9
Rasa SDK Version : 2.2.0
Rasa X Version   : None
Python Version   : 3.8.7
Operating System : macOS-10.15.7-x86_64-i386-64bit
Python Path      : /usr/local/bin/python3.8

A: this should be fixed in 2.2.10, which was released today: https://github.com/RasaHQ/rasa/releases/tag/2.2.10


text:
Q: Delaying Startup Services; Faster boot I really liked how Windows boot faster than Ubuntu. I think, Windows only ran the basic services needed to operate minimally. Then Start the services when it's booted. So it seems Windows is booting faster.
If that's what Windows does, Can I do the same with Ubuntu?
I tried  systemd-analyze blame. It shows-

4.214s plymouth-quit-wait.service
7.683s NetworkManager-wait-online.service
6.163s snapd.service
5.592s networkd-dispatcher.service
4.734s dev-sda8.device
4.486s udisks2.service
3.630s accounts-daemon.service
3.601s apport-autoreport.service
2.885s NetworkManager.service
2.671s polkit.service
2.586s dev-loop8.device
2.546s dev-loop10.device
2.475s dev-loop9.device
2.452s dev-loop7.device
2.366s dev-loop1.device
2.232s dev-loop5.device
2.216s avahi-daemon.service
2.181s dev-loop0.device
2.144s dev-loop2.device
2.140s switcheroo-control.service
2.136s thermald.service
2.136s systemd-logind.service
2.134s wpa_supplicant.service

How can I delay the services a bit so that it boots faster & I'll be able to log in faster...
Most of the cases I open the Firefox(start browsing) right after Logging in & sometimes I open  Nautilus, but that's it. My guess is delaying some services won't cause any issues.
Please suggest me How can I do it...
I currently Have only these startup applications


text:
Q: NHibernate Caching Problems I am having a problem with Nhibernate caching objects and returning old versions:
Here is the code I an running
public IList<Foo> GetFoos()
{
  return _session.Query<Foo>().Where(f => f.State == 0).ToList();
}

public void Update(Foo foo)
{
  foo.State = 1;

  _session.Transaction.Begin();
  _session.Update(foo);
  _session.Transaction.Commit();
}

If I have 10 Foos in state 0 in the database and I call GetFoos I get 10 Foo object which have a state of 0, thats great.
If I call Update on every Foo the database shows 10 foos in state 1, thats great.
Now if I call GetFoos I get 0 Foo objects, thats great.
If an external application changes the state of all the Foos to state 0, and I run the GetFoos method I get 10 objects returned, that's great. However the objects all have a state of 1!!!!!!, thats awful!
Now if I call Update on all the foos, the database doesn't update because Nhibernate thinks nothing has changed, so they stay in state 0 in the database forever.
Have I done something wrong with my configuration, or is this expected behaviour?
How can I get the objects to return the correct, new, values?
Thanks

A: The entities loaded by a session (ISession instance) will be kept in first level cache. You can either clear them all (ISession.Clear()) or manually call a ISession.Refresh() on every one to get the current values from the DB.


text:
Q: Openshift: Endpoints/Service for External MongoDB: Error No server chosen by WritableServerSelector from cluster description I am deploying my spring boot application in Openshift and the same uses external mongodb cluster for which I have created Endpoints/Service Objects. In my application.properties file I am using service name and when I try to call some API I am getting below error
No server chosen by WritableServerSelector from cluster description
Thanks for the help

A: Can you check your configurations as following link.
https://docs.openshift.com/container-platform/3.9/dev_guide/integrating_external_services.html


text:
Q: Why can't we use Meterbridge to measure high resistance and low resistance? Our physics master taught us that we can't use meterbridge to measure low resistance but he didn't give a valid reason for that.

A: A Wheatstone bridge works best (smallest error) when the resistors are all about equal. Having two small resistors in series on one side of the bridge will result in a lot of current (maybe more than the supply can handle), heating, and errors in the measurement. And because you're measuring the voltage across the same contact that carries the current, you will be more sensitive to contact resistance (compare this with the 4 point Kelvin probe arrangement that circumvents the problem and is more suited for low impedance measurements). Furthermore, the slightest imbalance in the bridge will send a large current through the galvanometer - which might well break it.
On the other hand, when resistance gets very high, the currents that would flow if the bridge was unbalanced become very small, and this may make them hard to detect (it depends a bit on the make and model of the device you use to detect the imbalance). Here, for example, is the calculation of the current that flows when you have two resistors of resistance R in series, with 10 V across the bridge, and you offset the jockey by 5%. I will assume that the resistance of the wire is lower (maybe 10 kOhm) so it doesn't really come into play.
We see then that there are unequal voltages across the two resistors; with the jockey 5% off center, the voltages will be 5.5 V and 4.5 V respectively. There is a net current of (5.5 - 4.5)V / (1 MOhm) = 1 uA that flows through the galvanometer.
That's not a ridiculous small current - but it is already near the limit of what ordinary mechanical (coil and needle) devices can measure. So as resistance increases, your ability to measure it accurately with a bridge decreases.

A: Is this part of a homework problem?
Low resistance - think about how you would connect the resistors to the bridge.
High resistance - think about how you note when the bridge is balanced.
The answer to your question is in all three Physics textbooks that I have opened as well as a couple of webpages.


text:
Q: ValueError: Error when checking target: expected dense_3 to have shape (1000,) but got array with shape (1,) I tried to implement a VGG-16 architecture of my Keras model, however I got the error message complaining checking target shapes.
img_width, img_height = 512, 560

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)
# build the VGG16 network
model = Sequential([
Conv2D(64, (3, 3), input_shape=input_shape, padding='same', activation='relu'),
Conv2D(64, (3, 3), activation='relu', padding='same'),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Conv2D(128, (3, 3), activation='relu', padding='same'),
Conv2D(128, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Conv2D(256, (3, 3), activation='relu', padding='same',),
Conv2D(256, (3, 3), activation='relu', padding='same',),
Conv2D(256, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Flatten(),
Dense(4096, activation='relu'),
Dense(4096, activation='relu'),
Dense(1000, activation='softmax')
])

model.summary()
model.compile(loss = 'binary_crossentropy',
              optimizer = 'rmsprop',
              metrics = ['accuracy'])
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_datagen = ImageDataGenerator(
    rotation_range = 180,
    width_shift_range = 0.2,
    height_shift_range = 0.2,
    brightness_range = (0.8, 1.2),
    rescale = 1. / 255,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True,
    vertical_flip = True
)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    #target_size=(224, 224),
    target_size = (img_width, img_height),
    batch_size = batch_size,
    class_mode ='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size = (img_width, img_height),
    #target_size=(224, 224),
    batch_size = batch_size,
    class_mode = 'binary'
)

history = model.fit_generator(
    train_generator,
    steps_per_epoch = nb_train_samples // batch_size,
    epochs = epochs,
    validation_data = validation_generator,
    validation_steps = nb_validation_samples // batch_size)

I tried to train and fit my model, however I got error messages shown below, how do I fix this problem? It looks like my last dense layer is with dimension 1000 why it's still complaining this?
    Found 576 images belonging to 2 classes.
Found 145 images belonging to 2 classes.
Epoch 1/50
Traceback (most recent call last):
  File "Trimer_useful_life_VGG.py", line 109, in <module>
    validation_steps = nb_validation_samples // batch_size)
  File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/keras/engine/training.py", line 1418, in fit_generator
    initial_epoch=initial_epoch)
  File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/keras/engine/training_generator.py", line 217, in fit_generator
    class_weight=class_weight)
  File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/keras/engine/training.py", line 1211, in train_on_batch
    class_weight=class_weight)
  File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/keras/engine/training.py", line 789, in _standardize_user_data
    exception_prefix='target')
  File "/home/hliu/.conda/envs/hliuPython/lib/python3.6/site-packages/keras/engine/training_utils.py", line 138, in standardize_input_data
    str(data_shape))
ValueError: Error when checking target: expected dense_3 to have shape (1000,) but got array with shape (1,)

A: This mode is configured to output 1000 classes, to use it for two classes and binary_crossentropy loss, you should change the last layer to:
Dense(1, activation='sigmoid')

This configuration allows for binary classification as 0-1, if you need more classes you need to put the number of classes in the last Dense, and use a softmax activation.


text:
Q: Problems with XSLT I am having issues with an assignment in my XML class. We have been assigned to create an XSL document and format some pre-existing XML files. For some reason I'm not able to view my XML file and I think it has to do with an error in the XSL, but I'm not sure.
Here's the XSL File (flowers.xsl)

<?xml version="1.0" encoding="UTF-8" ?>

<xsl:stylesheet version='1.0' xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:variable
name="items"
select="items.xml">
</xsl:variable>

<xsl:variable
name="customers"
select="customers.xml">
</xsl:variable>

<key id=ID name=itemID>
</key>

<key id=ID name=custID>
</key>

<key id=date name=date>
</key>

<xsl:template match="/">

      <title>Flower Orders</title>
      <link href="flowers.css" rel="stylesheet" type="text/css" />

Flower Orders

         Date
         Customer
         Item
         Price
         Qty
         Total

    <xsl:key name="order-by-date" match="date" use="key(date)" />
<xsl:template match="order">
    <xsl:for-each select="date[count(. | key('order-by-date', date)[1]) = 1]">
        <xsl:sort select="date" />
            </xsl:for-each>
</xsl:template>

         Grand Total
          sum(qty)

    <xsl:template match="totalCost" list="key(order)"

</xsl:template>

<xsl:template match="order">
<xsl:variable
    name="cID"
    select="customer">

</xsl:variable>

<xsl:variable
    name="iID"
    select="item">

</xsl:variable>

<xsl:variable
    name="qtyValue"
    select="qty">

</xsl:variable>

    <xsl:if test="position() == 1">

        date
        rows=count(<xsl:value-of select="current()"/>)

    </xsl:if>

    <xsl:for-each select="customers">

    <xsl:key name="order-by-name" match="key(custID)\name" use="cID" />

    <xsl:key name="order-by-city" match="key(custID)\city" use="cID" />
,
    <xsl:key name="order-by-state" match="key(custID)\state" use="cID" />
    <xsl:key name="order-by-zip" match="key(custID)\zip" use="cID" />

    </xsl:for-each>

        <xsl:for-each select="items">

        <xsl:key name="order-by-name" match="key(itemID)\name" use="iID" />

        <xsl:key name="order-by-price" match="key(itemID)\price" use="iID" />

    </xsl:for-each>

      <xsl:value-of select="@qty" />

    <xsl:for-each select="items">

        item cost

    </xsl:for-each>

   <xsl:if test="position()=last()">

         Subtotal
         sum(current(key(date)), current(key(qty)))

    <xsl:template match="node(key(date))" mode="rows">
    </xsl:template>

   </xsl:if>

</xsl:template>

<xsl:template match="/">
<xsl:param name="list"/>
<xsl:param name="total" select="0"/>

<xsl:choose>
  <xsl:when test="$list == NULL">
    <xsl:variable
name="first"
select="list">
</xsl:variable>

<xsl:variable
name="iID"
select="item">
</xsl:variable>

<xsl:variable
name="itemQty"
select="qty">
</xsl:variable>

</xsl:when>
<xsl:otherwise>
 <xsl:value-of select='format-number (total, "$#,#00.00)' />
</xsl:otherwise>
</xsl:choose>

 <xsl:for-each select="items">
    <xsl:variable
    name="itemPrice"
    select="key(itemID, iID)">
    </xsl:variable>

    </xsl:for-each>
<xsl:call-template name="totalCost">
    select= ($itemQty * $itemPrice + $total)
</xsl:call-template>
</xsl:stylesheet>

And here's one of the XML files that this stylesheet is attached to:
<?xml version="1.0" encoding="UTF-8" ?>

<?xml-stylesheet type="text/xsl" href="flowers.xsl"?>
<items>
   <item id="F101">
      <name>Large Flower Vase Arrangement</name>
      <price>74.99</price>
   </item>
   <item id="F102">
      <name>Flowers Galore: Orchids and Roses</name>
      <price>89.99</price>
   </item>
   <item id="F103">
      <name>Bear with Dozen Roses</name>
      <price>82.99</price>
   </item>
   <item id="F104">
      <name>Medium Ivy Flower Bowl</name>
      <price>49.99</price>
   </item>
   <item id="F105">
      <name>Flower Bowl</name>
      <price>54.99</price>
   </item>
   <item id="F106">
      <name>One Dozen Red Roses</name>
      <price>64.99</price>
   </item>
   <item id="F107">
      <name>One Dozen White Roses</name>
      <price>62.99</price>
   </item>
   <item id="F108">
      <name>One Dozen Pink Roses</name>
      <price>62.99</price>
   </item>
   <item id="F109">
      <name>Fragrant Garden Basket</name>
      <price>49.99</price>
   </item>
   <item id="F110">
      <name>Classic Vase</name>
      <price>64.99</price>
   </item>
   <item id="F111">
      <name>White Flower Elegance</name>
      <price>84.99</price>
   </item>
   <item id="F112">
      <name>Flowers to Go</name>
      <price>44.99</price>
   </item>
   <item id="F113">
      <name>Bright Autumn Flowers</name>
      <price>49.99</price>
   </item>
   <item id="F114">
      <name>Pedestal Bowl</name>
      <price>49.99</price>
   </item>
   <item id="F115">
      <name>Summer Vase</name>
      <price>69.99</price>
   </item>
   <item id="F116">
      <name>Dizzy with Daisies</name>
      <price>44.99</price>
   </item>
   <item id="F117">
      <name>Fragrant Pink Lillies</name>
      <price>72.99</price>
   </item>
   <item id="F118">
      <name>Medley Basket</name>
      <price>54.99</price>
   </item>
   <item id="F119">
      <name>Romantic Vase</name>
      <price>67.99</price>
   </item>
   <item id="F120">
      <name>Spring Fling Flowers</name>
      <price>59.99</price>
   </item>
   <item id="F121">
      <name>Fragrant Lillies</name>
      <price>74.99</price>
   </item>
   <item id="F122">
      <name>Spring Flower Basket</name>
      <price>54.99</price>
   </item>
   <item id="F123">
      <name>Enchanted Roses</name>
      <price>59.99</price>
   </item>
   <item id="F124">
      <name>Large Flower Vase Arrangement</name>
      <price>159.99</price>
   </item>
   <item id="F125">
      <name>Spring Blooms</name>
      <price>54.99</price>
   </item>
   <item id="F126">
      <name>White Bear Bouquet</name>
      <price>49.99</price>
   </item>
   <item id="F127">
      <name>Golden Basket</name>
      <price>69.99</price>
   </item>
   <item id="F128">
      <name>Regal Iris Vase</name>
      <price>57.99</price>
   </item>
   <item id="F129">
      <name>Flowers of Europe</name>
      <price>69.99</price>
   </item>
   <item id="F130">
      <name>Fragrant Blooms</name>
      <price>59.99</price>
   </item>
   <item id="F131">
      <name>Pretty in Pink</name>
      <price>49.99</price>
   </item>
   <item id="F132">
      <name>Spray of Roses</name>
      <price>69.99</price>
   </item>
   <item id="F133">
      <name>Yellow Sunflowers</name>
      <price>59.99</price>
   </item>
   <item id="F134">
      <name>Bright Spring Vase</name>
      <price>43.99</price>
   </item>
   <item id="F135">
      <name>Yellow Daisy Vase</name>
      <price>49.99</price>
   </item>
   <item id="F136">
      <name>Spring Compote</name>
      <price>109.99</price>
   </item>
   <item id="F137">
      <name>Country Garden Basket</name>
      <price>59.99</price>
   </item>
   <item id="F138">
      <name>Sunflower Basket</name>
      <price>56.99</price>
   </item>
   <item id="F139">
      <name>Medium Ginger Jar</name>
      <price>44.99</price>
   </item>
   <item id="F140">
      <name>Pleasant Basket</name>
      <price>99.99</price>
   </item>
</items>

Any help would really be appreciated, be it references to the correct way to do this or just pointing out errors. Thank you in advance!

A: Run your XSLT/XML through a validator to get more information on this but from my initial run, the first issue is on the key tag. Ensure you enclose the values of your attributes in quotes as shown below:
<key id="ID" name="itemID" />

<key id="ID" name="custID" />

<key id="date" name="date" />

XML validator: http://bit.ly/1nl0BFa

A: The line which is referring to the xml document should be
<xsl:variable name="items" select="document(items.xml)">

instead of
<xsl:variable name="items" select="items.xml">

In case if you have kept ur xml file somewhere in other location, in that case you need to specify the full path Ex:
<xsl:variable name='ref_file' select="document('C:/../../Desktop/ref.xml')"/>

Note that you are supposed to use forward slash

/

Apart from this your code is having few more errors, so please have a look before moving further.

A: I think you need to look carefully at your approach to writing code and solving problems when it doesn't work.
Your errors here are very basic. That's not a problem, we all make basic errors when we start. The difference between good programmers and bad programmers is in how efficient they are at discovering the cause of the errors and fixing them.
A lot of these errors would not have happened if you were using the right tools; like a spell-checker when creating documents, a development tool that understands XSLT will flag your errors as you make them, and will offer you automatic content completion that effectively corrects the basic errors as you type. Because I'm on Mac, I use oXygen, but there are other tools available.
Also, a lot of the errors would not have happened if you had spent a few hours reading a good introduction to the language, and working through its examples, before starting to write code. I've probably written in 20 different programming languages in my time, and I would never write code in a new language without first spending an evening reading a book on the subject.
Finally, diagnostics are important! I always wonder about people who post questions saying that something didn't work, without actually saying what went wrong (e.g. error messages). Perhaps you're not seeing the error messages because you're using an inappropriate environment (e.g. running XSLT in the browser without first testing it somewhere else). Perhaps the error messages are there, but you're ignoring them because you don't understand them (and you don't understand them because you haven't spent time learning the concepts and the vocabulary by reading up about the language before you start). Or perhaps you just haven't learnt the methodology of problem solving from the evidence, of which the error messages are the most important part.
The one plus point is that you're prepared to ask for help. I would suggest, however, that asking your teachers and fellow students for help at this stage is more productive than asking the internet.


text:
Q: Sorting Descending order: Java Map What I want to do is sort a map by value. I went over many questions that are available on the stackoverflow site and found out following solution that does what I want but missing a small thing.
Link1: Sorting Map
But the issue I am running into is that by default this is sorted by ascending order by value. I want to order it by descending order:
So what I did was I created a class that implements a comparator
class MyComparator implements Comparator {
    Map map;
    public MyComparator(Map map) {
        this.map = map;
    }
    public int compare(Object o1, Object o2) {
        return ((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
    }
}

And then I pass my map to the treemap,
MyComparator comp = new MyComparator(myMap);
Map<String, Integer> newMap = new TreeMap(comp);
newMap.putAll(myMap);

This seems like bad approach because I feel this is inefficient. Is there a way to change the solution in the link to do ordering on descending order by default.

A:     TreeMap<Long,String> treeMap = new TreeMap<Long,String>();

    NavigableMap <Long, String> nmap = treeMap.descendingMap();

    Set<Long, String> set = nmap.entrySet();

    Iterator<Long, String> iterator = set.iterator();

now u can iterate over iterator and extract the value using  iterator.hasNext() and iterator.next() methods ......

A: This will work :
      TreeMap<Integer, Integer> reverseInteger=new TreeMap<>(new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2>o1?1:o2==o1?0:-1;
        }
    });

A: You could simply invert the return value of your compare method by adding a minus sign at the beginning:
return -((Integer) map.get(o2)).compareTo((Integer) map.get(o1));

A: You should use new TreeMap<>(Collections.reverseOrder());.
Map<String, Integer> newMap = new TreeMap<>(Collections.reverseOrder());
newMap.putAll(myMap);

or to reverse an existing comparator like the value-comparator Collections.reverseOrder(comparator). It works like your approach swapping the two objects before invoking compare/compareTo.

A: To change the solution in the link to sort by descending order, just reverse the condition:
...
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
    if (base.get(a) >= base.get(b)) {
        return 1; // For ascending, return -1;
    } else {
        return -1; // For ascending, return 1;
    } // returning 0 would merge keys
}
...


text:
Q: Why does Composer Install a Different Package? I've been working with the Magento Firegento custom Composer installer, and I ran into this odd bit of Composer behavior I don't understand.
Consider the following dead simple composer.json file
{
    "require": {
        "magento-hackathon/magento-composer-installer": "*"
    }
}

If I run compser.phar install with this composer.json file, I get the following.
$ composer.phar install --no-dev
Loading composer repositories with package information
Installing dependencies
  - Installing aoepeople/composer-installers (v0.0.1)
    Loading from cache

Writing lock file
Generating autoload files

From my mostly lay-person's understanding composer.phar, I've said

Hey, composer, please install the magento-hackathon/magento-composer-installer package from packagist.org

And composer has said back to me

Sir, yes sir!  Here's the aoepeople/composer-installers package

I don't understand why composer installed aoepeople/composer-installers, when I asked for magento-hackathon/magento-composer-installer.
To be clear: I understand the reason magento-hackathon/magento-composer-installer wasn't installed is this is a package that lives in a different composer repository.  My original mistake was not including this repository in my composer.json file.
However, it doesn't make sense to me that composer would install a different package than the one I asked for.  When I search packagist there's no magento-hackathon/magento-composer-installer extension.
Why does packagist install a different extension?  What's happening behind the scenes to make magento-hackathon/magento-composer-installer resolve to aoepeople/composer-installers?  How/where in the composer source could I debug this sort of thing myself in the future?

A: Vinai published a great writeup on Magento and Composer here.
Quoting from there

Composer will use packagist.org to look where to get the libraries. Because Magento modules aren't listed there, you will have to add the packages.firegento.org repository to the configuration as follows [...]

So you will need the repository
   "repositories":[
     {
       "type":"composer",
       "url":"http://packages.firegento.com"
     }
   ],

to get the magento composer installer.
And yes composer offers replacements. On the packaging entry for aoepeople/composer-installers you will notice the replaces section:

And since magento-hackathon/magento-composer-installer is not available on packagist composer will deliver you aoepeople/composer-installers.

A: OK, so that's a weird behavior :) I'm the author of the aoepeople/composer-installers package and the idea behind this is that this package provides an alternative (very basic and simplified implementation of the composer package-type magento-module - and adds another type magento-source. I only want the installer to put the package in the right place - keeping it simple. That's why I decided to come up with an alternative package.
The reason why the aoepeople/composer-installer replaces the magento-hackathon/magento-composer-installer is because many Magento modules already come with a composer.json that requires the magento-hackathon/magento-composer-installer. In order to be able to seamlessly use the simpler installer that one is "pretending" to be the hackathon-installer. But unless you actively require aoepeople/composer-installers in your project's composer.json you should continue using the original installer as no Magento module's composer.json out there (not even ours) is directly referring to aoepeople/composer-installers.
The fact that packagist tries to be "smart" and returns a package that replaces a package that's not registered is new to me and - to be honest - very disturbing. While this might be intended behavior I share the opinion that this could easily be abused. I start liking Alan's idea to bypass packagist completely using "packagist":"disabled". Especially in the case of Magento modules this seems to happen easily because most of the Magento modules are unknown to packagist while being registered at packages.firegento.com only.
A simple quickfix/workaround to this specific situation could be to register magento-hackathon/magento-composer-installer on packagist.org.

A: The Packagist package at https://packagist.org/packages/aoepeople/composer-installers has metadata saying that it replaces the magento-hackathon/magento-composer-installer package. Packagist would then install this as it's the package that replaces what you asked for.
Docs here: https://getcomposer.org/doc/04-schema.md#replace


text:
Q: How to build a Grails Plugin and deploy it to local Ivy repository? Is there a way to build a Grails Plugin and deploy the artifacts to the local Ivy repository?
With Maven, I would do this:
mvn install

A: Use the ivy publish task
<ivy:publish resolver="local" pubrevision="1.0">
   <artifacts pattern="build/[artifact].[ext]" />
</ivy:publish>

Note 1
Your ivy file must list the artifacts you plan to publish
<ivy-module version="2.0">
  <info organisation="myorg" module="mymodule"/>
  <publications>
    <artifact name="mymodule" type="zip"/>
  </publications>
</ivy-module>

Maven derives this information from the module declaration in the POM file. One of the advantages of using ivy is that you can publish more than one artifact.
Note 2
The ivy local repository is located in the following location by default:
${user.dir}/.ivy2/local

You can of course create your own custom repositories by declaring alternative resolvers in you settings file


text:
Q: jQuery trigger function when mousedown or touchend event happen outside selector area Scenario: user clicks on a element, then drags it. Dragging ends elsewhere though. I noticed that when this happens, if I listen to the element that's being dragged, it won't trigger anything unless the cursor is released on the same element when dragging finishes.
How do I trigger an event that starts on an element but ends anywhere else on document?
$('#hotels-slider-handle').on('mouseup touchend click', function() {
    $('#booking-input').trigger('change');
});

A: in answer to Cerlin Boss who commented to my original post above... this is what I came up with and works well (what I need to trigger gets triggered just fine) - I was looking for more efficient solutions though (ignore the jQuery delays, they're necessary in my scope)
var bookingFormInputs = $('#booking-input'),
    hotelsSlider = $('#hotels-slider');
$('#hotels-slider-handle').on('mousedown touchstart', function() {
    $(document).delay(300).one('mouseup touchend', function() {
        $(bookingFormInputs).delay(600).trigger('change');
    });
    $(hotelsSlider).delay(300).one('mouseleave', function() {
        $(document).on('mouseup touchend', function() {
            $(bookingFormInputs).delay(300).trigger('change');
        });
    });
});


text:
Q: element.getAttribute() returns null when attribute has value The value of elParentAttr is 'level4' the first time traverseUp is called but every time after is null. Why is this? Fiddle here.
JavaScript:
function traverseUp(el, attr) {
    var elParent = el.parentNode,
        elParentAttr = el.parentNode.getAttribute(attr);

    console.log(elParent);
    console.log(elParentAttr);

    traverseUp(elParent);
}

traverseUp((document.getElementsByClassName('level5'))[0], 'class');

Document:

A: When you're calling it with the loop, aren't you missing the second parameter?
from traverseUp(elParent); to traverseUp(elParent, attr); ?


text:
Q: How to use he/she (or another word) when we dont know what the other person is a man or woman? So in meetings, text, documents etc, and speaking to other people we discuss what users should do or will do.
So for example,  a sentence could be 'the user enter his/her username and then he/she needs to click on the button to continue'
Each time do we need to use he/she , or there is another way to write the same ?


text:
Q: Get posts from post author - WordPress I'm trying to make a section that shows the posts created by the user that created the current post. I need to show them obviously excluding the current post and according to a certain type of post (event).
I have this code, but it is not working. Can someone think of how to help me?
<?php

    $args = array(
    'author'        =>  $post->post_author;
    'type'          => $post_meta['_listing_type'][0] == 'event',
    'order'         =>  'ASC',
    'posts_per_page' => -1
    );

    $eventos = get_posts( $args );

    foreach ( $eventos as $evento ) {
        $output .= '
'.$evento.'
';
    endforeach;

    if(!empty($eventos)) : ?>

<?php esc_html_e('Eventos del artista','listeo_core'); ?>

                    <?php echo $output; ?>

    <?php endif ?>

A: You've got a couple of things. You've got an illegal semi-colon in your $args array, type should be post_type, I'm also not entirely sure you need that weird comparison operator in there?
Try this:
$args = array(
    'author'         => $post->post_author,
    'post_type'      => 'event',
    'order'          => 'ASC',
    'posts_per_page' => -1
);

Also make sure that $post is set, depending on where you're calling this, there may not be an instantiated/global $post object.
This is also assuming you're using an actual post_type called event, otherwise if you're checking regular posts for the meta field '_listing_type', you'll need to drop the post_type argument, and add a meta_query argument instead - note that this is inherently slow on large databases because the postmeta table isn't indexed by default. Also note that meta_query is an array of arrays.
That query would end up looking something like this:
$args = array(
    'author'         => $post->post_author,
    'order'          => 'ASC',
    'posts_per_page' => -1,
    'meta_query'     => array(
        array(
            'meta_key'   => '_listing_type',
            'meta_value' => 'event'
        )
    )
);


text:
Q: Name of iOS ui element How does this half screen scrollable pop up elememt is called in iOS? Have seen it in many apps so I guess it should be native one.

A: Even though it's common, it is not a standard UIKit element. It's a custom presented view controller (not a standard configuration). You'll need a custom transition animation and presentation controller along with gesture recognizers for dismissal. (There are lots of tutorials showing you how to do that.)
New in iOS 13, all presented view controllers have this general configuration by default (called "sheet" or "card"), but not half-screen like the one you've shown (they almost fill the screen).


text: Q: Chromium problems on xubuntu I had been running Chromium under xubuntu with no problems whatsoever. Now, when I try to start Chromium, I get the "Restore Pages? Chromium did not shut down correctly" box. No matter what I do from this point, Chromium just shuts down. Any ideas?


text:
Q: I want to log every message from one server to one file but i gets error I want to log every message from one server to one file but i get error can someone help me please
Code
@client.event
async def on_message(message):
    async for message in message.channel.history(limit=1):
        file1 = open("MyFile.txt","a")
        file1.write("msg: "+str(message.content)+" " +str(message.channel)+" "+str(message.author))
        file1.close()

Error
Traceback (most recent call last):
  File "C:\Users\vikto\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\vikto\OneDrive\Desktop\selfbot\main.py", line 73, in on_message
    file1.write("msg: "+str(message.content)+" " +str(message.channel)+" "+str(message.author))
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 39-40: character maps to <undefined>
Ignoring exception in on_message
Traceback (most recent call last):```

A: Why not use the logging module with something like?
import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.addHandler(RotatingFileHandler('MyFile.log', maxBytes=1e+7, delay=True))
logger.setLevel(logging.INFO)

@client.event
async def on_message(message):
    async for message in message.channel.history(limit=1):
        logger.info("msg %s %s %s", message.content, message.channel, message.author)

A: Look's like your charmap codec, you might want to try adding "encoding to utf-8 while opening MyFile.txt
@client.event
async def on_message(message):
    async for message in message.channel.history(limit=1):
        file1 = open("MyFile.txt","a", encoding="utf-8")
        file1.write("msg: "+str(message.content)+" " +str(message.channel)+" "+str(message.author)+"\n")
        file1.close()

I also suggest you adding a new line at the end, but this is up to you


text:
Q: Zend Framework 2: active menu items Build navigation from config:
'navigation' => array(
    'default' => array(
        'admin' => array(
                'label' => 'Administration',
                'controller' => 'index',
                'action' => 'index',
                'route' => 'admin/default',
              ),
         'album' => array(
                'label' => 'Album',
                'controller' => 'index',
                'action' => 'index',
                'route' => 'album/default',
              ),
  /* ... */

Routing is configured like it is true. Navigation in the menu works. Links menu lead to the desired controller/action of the desired module. But while introducing menu and a transition to one or another menuitem, active marked both points simultaneously and 'Administration' and 'Album'. As I understand it, for the reason that match the names of controllers and actions with them, but there's still the 'route' and it's different... not for nothing that the generated different url for each item... but somehow, despite this, they both are marked as active.
Routing config:
    'router' => array(
    'routes' => array(
        'admin' => array(
            'type'    => 'Literal',
            'options' => array(
                'route'    => '/admin',
                'defaults' => array(
                    '__NAMESPACE__' => 'Admin\Controller',
                    'controller'    => 'Index',
                    'action'        => 'index',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'default' => array(
                    'type'    => 'Segment',
                    'options' => array(
                        'route'    => '/[:controller][/:action[/id:id]]',
                        'constraints' => array(
                            'controller'    => '[a-zA-Z][a-zA-Z0-9_-]*',
                            'action'        => '[a-zA-Z][a-zA-Z0-9_-]*',
                            'id'            => '[0-9]+',
                        ),
                        'defaults' => array(
                        ),
                    ),
                ),

Album routing config similar...
Why this is happening? Thanks.

A: Looks like it's how ZF2 works (read isActive() function in Zend\Navigation\Page\Mvc.php). Initially it checks matching of route/controller/action, but if it fails, ZF2 again check for just controller/action pair. So there are three possible ways:

*

*Open a ticket at https://github.com/zendframework/zf2/issues and wait for response.

*Override \Zend\Navigation\Page\Mvc.

*Choose different names for controllers (and don't use index name because it's default name for controller in Mvc.php).

A: If you make your controller names include the the namespace then they will be unique and won't clash:
Admin\Controller\IndexController
Album\Controller\IndexController

Rather than
Index
Index


text:
Q: Automating an object repository for a game Hello guys i am having trouble designing an object repository for a game:
class ObjectRepository
{

private readonly LevelType _levelType;

private readonly BaseObject[] _darkForestObjects = new BaseObject[]
                { new DarkForestTreeA(), new DarkForestTreeB(), new DarkForestTreeC() };

private readonly BaseObject[] _lightForestObjects = new BaseObject[]
                { new LightForestTreeA(), new LightForestTreeB(), new LightForestTreeC() };

public ObjectRepository(LevelType lt)
{
    _levelType = lt;
}

public BaseObject GetObject(int obj)
{
    if (obj < 0 || obj > _darkForestObjects.Length)
    {
        Debug.LogError("Object does not exist.");
        return null;
    }

    switch (_levelType)
    {
        case LevelType.DarkForest:
           return _darkForestObjects[obj];
        case LevelType.LightForest:
           return _lightForestObjects[obj];
    }

    return null;
}
}

public enum LevelType
{
    DarkForest = 0,
    LightForest = 1,
}

I am searching for a way of automating this class.By automating it i mean that i don't want every time i create a new object deriving from BaseObject to come inside the Repository class and modify arrays.It just doesn't seem natural.Can anybody point me out a suggestion for automation?

A: I'll take a gander at this, so please let me know if I'm assuming things wrong.
You'll need:

*

*A repository that'll hold your BaseObject-derived instances;

*Said repository must be accessible by the BaseObject class;

*Whenever a BaseObject is created, it adds itself to the repository.

Now, I've noticed that you hold instances for both dark and light versions of your objects. So I'd additionally suggest a holder class for both light and dark versions of a given 'object'. Like this:
class CompoundObject
{
    public BaseObject LightVersion;
    public BaseObject DarkVersion;
}

Your repository then hold CompoundObject-derived objects, and instead of BaseObject objects adding themselves at creation time, CompoundObject objects would do it.
Now about Array manipulations, you may be right; it can be somewhat clunky. I'd suggest the adoption of List<CompoundObject> instead of CompoundObject[]. A generic List offer very handy methods like Add and Remove that can streamline your collection manipulation.

A: If I were you, I would opt for a more generic solution using interfaces.
Considering your example, I assume that you have multiple level types which have their own specific TreeA, TreeB and TreeC implementations.
If I understood right, I would rather use interface for each tree type. Example for TreeA :
public interface ITreeA
{
  // any common public members here
}

public class DarkForestTreeA : ITreeA, BaseObject
{
    ...
}

public class LightForestTreeA : ITreeA, BaseObject
{
    ...
}

This way, you can ask your repository to provide the ITreeA implementation specific to the level type. Something like :
public T GetObject<T>() // where T could be ITreeA, ITreeB...
{
    ...
}

So you could call myRepo.GetObject() and get a DarkForestTreeA object if level type is DarkForest for example.
To have this behavior "automated", you could declare all the specific implementations of DarkForest in a unique namespace and then use reflexion to find the class of the namespace that implements ITreeA for example. This may not be very efficient in terms of performance but it gives you great flexibility as you will just have to add new classes in your namespace to have them available from the repository. However, it can also bring other problems (for example, what would happen if you have two classes implementing ITreeA in the same namespace ?).
See Getting all types in a namespace via reflection and Getting all types that implement an interface with C# 3.0 for implementation details.
I have to admit it isn't the simplest solution.
You could consider simpler thing like defining a dictionary for object type (treeA, treeB) and then define a dictionary for each level type mapping the object type to its concrete implementation.
For example :
public enum ObjectType
{
    TreeA,
    TreeB,
    TreeC,
}

Dictionary<ObjectType, Type> DarkForestObjectTypes = new Dictionary<ObjectType, Type>()
{
    { ObjectType.TreeA, typeof(DarkForestTreeA) },
    { ObjectType.TreeB, typeof(DarkForestTreeB) }
    ...
}

I won't go into more details as this answer looks a bit messy but hopefully it will give you ideas to go on with.


text:
Q: UIPageViewController last page bounce effect? I am using a UIPageViewController to flip through multiple page of content, currently I don't do anything when the user flips to the last page of the UIPageViewController because there is no more page to switch to, how would I achieve a bounce effect like scrolling to the end of the UIScrollView, so that it gives user some feedback it is the end of the sequence?

A: Try this!

*

*Add an empty page before your 'first' page (and optionally set it to be hidden)

*After you have made the setup for your UIPageViewController, manually go to the second page, your 'first' page.

*In the pageViewController:viewControllerBeforeViewController: delegate method, check if the view will be the empty page. If so,

*

*manually go to the second page again, maybe after some delay. Or

*In some sort of way, disable the UIPanGestureRecognizer in your UIPageViewController

This may not be the perfect solution, but hopefully acceptable.
I'm also going to do something like this later, so I'll maybe explain more then and try it out myself. Good luck!

//Edit
Ah.. if you want to have the bounce effect last instead (I recommend you to do both)..

*

*Skip this.

*Add an extra (or two if you have an odd number of pages and double-sided view) empty page(s) after all your other pages (and optionally set it/them to be hidden)

*In the pageViewController:viewControllerAfterViewController: delegate method, check if the view will be the (last) empty page. If so,

*

*manually go to the previous page, maybe after some delay. Or

*In some sort of way, disable the UIPanGestureRecognizer in your UIPageViewController

In (3), if you haven't disable the UITapGestureRecognizer, you will have to decide if it is the tap gesture, and then choose (3.1), else take the (3.2) route!


text:
Q: PostGIS testing if point intersects scaled polygon sometimes gets wrong answer I need an algorithm where I can check if a point falls within a polygon within a small tolerance (meaning the point is completely within the polygon or sufficiently close to the border). To implement this, I was planning on using the st_scale function to expand the polygon by a factor, then check the point with st_within. Note that I can't use st_buffer because st_buffer expects an absolute radius of the buffer but I need a relative radius (ex. Determine if the point is within the polygon or within the polygon that has been scaled up by 5%).
To accomplish this, I've written the following tester code. I take a polygon, scale it up by 5%, and then test to see if the original polygon's centroid falls within the scaled-up polygon:
SELECT ST_within(
  st_centroid(polygon),
  st_scale(
    polygon,
    'POINT(1.05 1.05)'::geometry,
    st_centroid(polygon)
));

However, sometimes this function fails for no apparent reason (meaning it says the polygon's centroid is not within the scaled-up polygon) and I have no idea why. This feels like it's buggy, but I can't imagine I've found a bug in postGIS.
Passing testcases:
-- drawing a 1x1 box at the origin of the x-y plane
SELECT ST_Within(
  st_centroid('MULTIPOLYGON(((0 0, 1 0, 1 1, 0 1, 0 0)))'::geometry),
  st_scale(
    'MULTIPOLYGON(((0 0, 1 0, 1 1, 0 1, 0 0)))'::geometry,
    'POINT(1.05 1.05)'::geometry,
    st_centroid('MULTIPOLYGON(((0 0, 1 0, 1 1, 0 1, 0 0)))'::geometry))
);

-- box in the first quadrant at an origin of (10, 10)
SELECT ST_Within(
  st_centroid('MULTIPOLYGON(((10 10, 11 10, 11 11, 10 11, 10 10)))'::geometry),
  st_scale(
    'MULTIPOLYGON(((10 10, 11 10, 11 11, 10 11, 10 10)))'::geometry,
    'POINT(1.05 1.05)'::geometry,
    st_centroid('MULTIPOLYGON(((10 10, 11 10, 11 11, 10 11, 10 10)))'::geometry))
);

Failing testcase:
-- 1x1 box with the bottom left corner at (98, 28)
SELECT ST_within(
  st_centroid('MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry),
  st_scale(
    'MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry,
    'POINT(1.05 1.05)'::geometry,
    st_centroid('MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry))
);

Interestingly, though, casting the scaled shape to WKT and then back to a geometry DOES work.
-- 1x1 box with the bottom left corner at (98, 28)
SELECT ST_within(
  st_centroid('MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry),
  st_geomfromewkt(st_asewkt(st_scale(
    'MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry,
    'POINT(1.05 1.05)'::geometry,
    st_centroid('MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry))))
);

So, yeah, what is going on here???? Have I found a bug in PostGIS?

A: I think you've found a bug in older versions of postgis. I used docker and some servers to test with several versions of postgres and postgis. With version 3.1.4 the code works properly.
In the past I've stumbled in some corner cases were postgis gave unexpected results. Those were related to GEOS, that according to the manual is the library that implements the ST_Within function, but in this case the GEOS library is the same in all tests.
From what your working query that transforms to ewkt and back shows, this should be related with an internal operation in postgis that got corrected. I tried but did not find a bug that I could relate to this.
I post two of the tests that I've done:
postgres 12, postgis 3.0.0
The bug is present:
test=# select postgis_full_version();
                                                                                postgis_full_version
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 POSTGIS="3.0.0 r17983" [EXTENSION] PGSQL="120" GEOS="3.7.1-CAPI-1.11.1 27a5e771" PROJ="Rel. 5.2.0, September 15th, 2018" LIBXML="2.9.4" LIBJSON="0.12.1" LIBPROTOBUF="1.3.1" WAGYU="0.4.3 (Internal)" TOPOLOGY
(1 row)

test=# SELECT ST_within(
  st_centroid('MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry),
  st_scale(
    'MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry,
    'POINT(1.05 1.05)'::geometry,
    st_centroid('MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry))
);
 st_within
-----------
 f
(1 row)

postgres 13, postgis 3.1.4
The code works as expected:
test=# select postgis_full_version();
                                                                                postgis_full_version
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 POSTGIS="3.1.4 ded6c34" [EXTENSION] PGSQL="130" GEOS="3.7.1-CAPI-1.11.1 27a5e771" PROJ="Rel. 5.2.0, September 15th, 2018" LIBXML="2.9.4" LIBJSON="0.12.1" LIBPROTOBUF="1.3.1" WAGYU="0.5.0 (Internal)" TOPOLOGY
(1 row)

test=# SELECT ST_within(
  st_centroid('MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry),
  st_scale(
    'MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry,
    'POINT(1.05 1.05)'::geometry,
    st_centroid('MULTIPOLYGON(((98 28,99 28,99 29,98 29,98 28)))'::geometry))
);
 st_within
-----------
 t
(1 row)


text:
Q: html drop down menus not working in firefox and everything is wrong in older versions of IE Good evening everybody I am having trouble with my drop down menu's in firefox and IE.
I mistakenly developed this page and tested everything on chrome but when a buddy was checking it for me he used firefox and said he was not able to use my navigation. Could somebody please point me in the right direction Thanks.
And if anybody could point me in the right direction on getting my page to look good on IE that would be great
here is the code

Home

Register/login

Register

Login

Forgot Password

Email Password

Answer Security Questions

Contact Us

Email

Forum

Contact Us

Email

Forum

Contact Us

Email

Forum

Contact Us

Email

Forum

here is the css
nav {
    height:80px;
    width:1024px;
    }
ul {
    padding:0;
    margin:0;
    list-style:none;
    }
nav ul ul {
    display: none;
    }
nav ul li:hover > ul {
    display: block;
    }
nav ul {
    background: #efefef;
    background: linear-gradient(top, #efefef 0%, #bbbbbb 100%);
    background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
    background: -webkit-linear-gradient(top, #efefef 0%,#bbbbbb 100%);
    box-shadow: 0px 0px 9px rgba(0,0,0,0.15);
    padding: 0 75px;
    border-radius: 10px;
    list-style: none;
    position: relative;
    display: inline-table;
    z-index:100;
    }
nav ul:after {
    content: ""; clear: both; display: block;
    }
li {
    float: left;
    }
nav ul li:hover {
    background: #4b545f;
    background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
    background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
    background: -webkit-linear-gradient(top, #4f5964 0%,#5f6975 40%);
    }
nav ul li:hover a {
    color: #fff;
    }
nav ul li a {
    display: block; padding: 25px 40px;
    color: #757575; text-decoration: none;
    }
nav ul ul {
    background: #5f6975; border-radius: 0px; padding: 0;
    position: absolute; top: 100%;
    }
nav ul ul li {
    float: none;
    border-top: 1px solid #6b727c;
    border-bottom: 1px solid #575f6a;
    position: relative;
    }
nav ul ul li a {
    padding: 15px 40px;
    color: #fff;
    }
nav ul ul li a:hover {
    background: #4b545f;}
}
nav ul ul ul {
    position: absolute; left: 100%; top:0;
    }
li ul {
    display: none;
    position: absolute;
    top: 1em;
    left: 0;
    }
li > ul {
    top: auto;
    left: auto;
    }
li:hover ul, li.over ul{ display: block; }

#article{
    height:500px;
    width:1024px;
    background:#FFFFFF;
    }
#article>h1 {
    text-align:center;
    }
#legaljibjab {
    height:30px;
    width:1024px;
    border:black solid thin;
    background:#FFFFFF;
    }

A: Older browsers do not support the new styles of HTML5 certain things may be out of order because of the older support for the html try IE 10 or Chrome then see what happens.
Your html and css looks right but to be sure download a newer browser. Also try taking out the  element.

A: Could it be the invalid html of this line?
Register/login

A: I see that your second
 tag has a random html tag in there which probably isn't helping. Running your code through an html validator will work wonders for you. A quick Google search will provide you with many different options.
The  tag is an html5 tag and is not supported by IE8 and older. I'm guessing your friend was probably using an older version of IE. When developing for cross browser compatability you need to keep in mind that some tags & techniques differ in compatability. There are many sites out there that you can use to check this. In school, I often used - Caniuse.com
As for Firefox not working, I can't really say. Firefox is compatible with the  tag so that should be working. Are you getting any errors in your browser's error console?


text:
Q: Weird  symbol after every word in database I can't figure out what this  symbol is.  I have a webpage with some textboxes that allow users to submit info to a database. A few of the users are copying and pasting sentences from Microsoft Word.  Could it be Word that is inserting these?

A: This is an encoding issue.  UTF-8 will correctly display a non-breaking space   rather than displaying Â.
Add the following code inside <head></head> to indicate the webpage is UTF-8.
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />


text:
Q: Unable to fetch all text file names recursively from a directory I'm trying to fetch all text files from a directory in a recursive manner (i.e. search all sub-folders):
let fs = require("fs");

function getPathNames(dirName) {
    let pathNames = [];
    for (let fileName of fs.readdirSync(dirName)) {
        let pathName = dirName + "/" + fileName;
        if (fs.statSync(pathName).isDirectory())
            pathNames.concat(getPathNames(pathName));
        else if (pathName.endsWith(".txt"))
            pathNames.push(pathName);
    }
    return pathNames;
}

However, when I call getPathNames("."), I get only the name of the first file.
It works fine if I take the return-value out of the function, and update a global variable instead:
let fs = require("fs");

let pathNames = [];

function getPathNames(dirName) {
    for (let fileName of fs.readdirSync(dirName)) {
        let pathName = dirName + "/" + fileName;
        if (fs.statSync(pathName).isDirectory())
            getPathNames(pathName);
        else if (pathName.endsWith(".txt"))
            pathNames.push(pathName);
    }
}

Does anyone spot anything wrong with the first method?

A: Well, concat is not an in place mutation, but returns you a new array instead, so I would say you should do this instead
pathNames = pathNames.concat(getPathNames(pathName));


text:
Q: Authentication of User on Firebase in C# I am searching for one week on the topic of how to authenticate a specific user on firebase using email and password and then retrieve data for that specific user if it is registered in C# app?
I tried a lot but unable to find the correct way.


text:
Q: How to extract SSL certificate properties I want a tool which can run on a server, that would extract and return specified properties from an already installed SSL certificate. I am specifically interested in the "issuer" and "thumbprint" properties. I know that I can simply open the certificate's properties dialog and copy these, and then paste them into my app, but to avoid a possibly error-prone manual process when others will be doing this at multiple sites, i would like a tool or script I can call that would simply return the value of a specified property from a specified certificate. I am fine if i need to make a separate call for each desired property. The more turnkey this is, the better. Are there any suggestions, please?

A: You want to do something like this:
Get-ChildItem Cert:\LocalMachine\Root\ | Select Issuer,Thumbprint

Here is a list of properties you can easily get from System.Security.Cryptography.X509Certificates.X509Certificate2 objects(common certificates).
Name                 MemberType     Definition
----                 ----------     ----------
Archived             Property       bool Archived {get;set;}
Extensions           Property       System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions {get;}
FriendlyName         Property       string FriendlyName {get;set;}
Handle               Property       System.IntPtr Handle {get;}
HasPrivateKey        Property       bool HasPrivateKey {get;}
Issuer               Property       string Issuer {get;}
IssuerName           Property       System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName {get;}
NotAfter             Property       datetime NotAfter {get;}
NotBefore            Property       datetime NotBefore {get;}
PrivateKey           Property       System.Security.Cryptography.AsymmetricAlgorithm PrivateKey {get;set;}
PublicKey            Property       System.Security.Cryptography.X509Certificates.PublicKey PublicKey {get;}
RawData              Property       byte[] RawData {get;}
SerialNumber         Property       string SerialNumber {get;}
SignatureAlgorithm   Property       System.Security.Cryptography.Oid SignatureAlgorithm {get;}
Subject              Property       string Subject {get;}
SubjectName          Property       System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName {get;}
Thumbprint           Property       string Thumbprint {get;}
Version              Property       int Version {get;}
DnsNameList          ScriptProperty System.Object DnsNameList {get=,(new-object Microsoft.Powershell.Commands.DnsNameProperty -argumentlist $this).DnsNameList;;}
EnhancedKeyUsageList ScriptProperty System.Object EnhancedKeyUsageList {get=,(new-object Microsoft.Powershell.Commands.EnhancedKeyUsageProperty -argumentlist $this).EnhancedKeyUsageList;;}
SendAsTrustedIssuer  ScriptProperty System.Object SendAsTrustedIssuer {get=[Microsoft.Powershell.Commands.SendAsTrustedIssuerProperty]::ReadSendAsTrustedIssuerProperty($this);set=$sendAsTrustedIssuer = $args[0]...


text:
Q: Generate numbered forms in Word where the number is shown twice Is it possible to make Word generate a piece of text (with tables) n number of times and have it include the number in each piece of text twice?
I have tried using the sequence field, but then I can't get the number in there twice:

I need both top numbers to be "1" in this case, but in a next rendering it should be 2, then 3, etc.
As you can see, I'm trying to generate order forms for a local event (I simplified the layout a bit here).
Ideally, I could tell Word to give me 100 of this forms, and it would render them all, numbered. Or if I could just copy-paste the block, and have Word increase both numbers on every paste. Or paste the block and then update the sequence, but currently I can't find a way of duplicating the number.
Is this even possible in Word?

A: In the second SEQ field for the form (ie currently showing as 2 in your diagram above), add the switch \c (which is the preceding number in sequence, in this case your first SEQ field for each form).  You may need to select all and update fields after you copy and paste.


text:
Q: Convert 12 hours to 24 hours from varchar column in SQL Server In my existing SQL Server database, there is a column like this:

*

*Column name and type: meeting_time varchar(22)

*Values stored: 02:30:PM
Now I want to convert it into 24 hours format. i.e., it should convert to 14.30
When I tried this:
SELECT
    CONVERT(VARCHAR(8), meeting_time, 1)
FROM
    group_info
WHERE
    MGI_Id = 1

It will return the same value which stored in this column. When I tried with converting it into time or datetime, it throws exception.
Can anyone please help me!
Thanks in advance.

A: This should work:
select convert(time, stuff(meeting_time, 6,  1, ' '))

Not sure if it works with all locales / languages, so you should check that first.
This assumes that your date is always in the same format, that the extra : is in the 6th character.


text:
Q: How can I optimize my syntax highlighting? I am making a text editor in Android and I want to add syntax highlighting to it. With my current implementation, the UI is laggy when I type something. I need help with optimizing my current implementation.
private void onEditorListener() {

    edtEditor.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            if (timer != null) {
                timer.cancel();
            }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(final Editable s) {

            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // do your actual work here
                    MaineActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                        }
                    });

                    try {

                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    MaineActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textHighLighter(s);
                        }
                    });
                }
            }, 600);

        }

    });
}

private void textHighLighter(Editable s) {

    // Check the matcher for general keywords..
    Matcher a = Patterns.GENERAL_KEYWORDS.matcher(s.toString());
    // Check the matcher for html tags..
    Matcher b = Patterns.HTML_TAGS.matcher(s.toString());
    // Check the matcher for html attribute..
    Matcher c = Patterns.HTML_ATTRS.matcher(s.toString());
    // Check the matcher for symbol..
    Matcher d = Patterns.SYMBOLS.matcher(s.toString());
    // Check the matcher for general strings..
    Matcher e = Patterns.GENERAL_STRINGS.matcher(s.toString());
    // Find all the general key words and change the text color...
    // Find all the html tags words and change the text color...
    while (b.find()) {
        s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.orchid)), b.start(), b.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //android.util.Log.i("VINCE", b.toString());
    }

    while (a.find()) {
        s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.bounded)), a.start(), a.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //android.util.Log.i("VINCE", b.toString());
    }

    while (c.find()) {
        s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.henn)), c.start(), c.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //android.util.Log.i("VINCE", b.toString());
    }

    while (d.find()) {
        s.setSpan(new ForegroundColorSpan(Color.WHITE), d.start(), d.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //android.util.Log.i("VINCE", b.toString());
    }

    while (e.find()) {
        s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.general_str)), e.start(), e.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //android.util.Log.i("VINCE", b.toString());
    }

}

A: Here are some suggestions:
Use a Handler and a Runnable instead of TimerTask. I'm assuming you want to wait n milliseconds before calling textHighLighter(Editable s) after afterTextChanged(final Editable s) is invoked. To do this, use handler.postDelayed(Runnable r, long delay) and handler.removeCallbacks(Runnable).
Remove Thread.sleep(2000).
An Editable extends CharSequence. Do no call toString() on your Editable, just pass it as an argument to Pattern#matcher(CharSequence).

A: @Jared Rummler here is my code

@Overrideenter code here
            public void afterTextChanged(final Editable s) {
                last_text_edit = System.currentTimeMillis();
                handler.postDelayed(runnable, idle_min);
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (System.currentTimeMillis() >= (last_text_edit + idle_min - 500)) {
                                // user hasn't changed the EditText for longer than
                                // the min delay (with half second buffer window)

                                textHighLighter(s);  // your queries
                                if (!already_queried) { // don't do this stuff twice.
                                    already_queried = true;
                                    //textHighLighter(s);  // your queries
                                    android.util.Log.i("VINCE", "already_queried");
                                }
                            }

                            //already_queried = false;
                            handler.removeCallbacks(runnable);
                            android.util.Log.i("VINCE", "Cancelled");
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                };


text:
Q: How to install wifi driver iwlwifi 4.2.0-16-generic I have no wifi driver on 14.04. I discovered by running a live usb of 15.10 that  wifi driver iwlwifi 4.2.0-16-generic works. I am wondering if there is a way to install this on 14.04? I have tried the obvious google searches but I'm still new at this and probably not looking in the right places.
I can't update to 15.10 because a program I need to use is not supported.
lspci -nn | grep 0280 gives
01:00.0 Network controller [0280]: Intel Corporation Device [8086:3165] (rev 79)

Thank you!

A: You can install backports from 4.3 kernel to Ubuntu 14.04.
I suggest removing un-official kernels and run in terminal:
sudo apt-get install build-essential
wget https://www.kernel.org/pub/linux/kernel/projects/backports/2015/09/03/backports-20150903.tar.gz
tar -zxvf backports-20150903.tar.gz
cd backports-20150903
make defconfig-iwlwifi
sudo make install

This should install a correct driver. But you will have to re-install it after each kernel upgrade by running the last three commands.
You may also need firmware for this adapter. You can install the firmware package from 15.10 this way:
wget http://mirrors.kernel.org/ubuntu/pool/main/l/linux-firmware/linux-firmware_1.149.1_all.deb
sudo dpkg -i linux-firmware_1.149.1_all.deb

or you can install kernel 4.3.


text:
Q: RegEx to extract URL from CSS background styling I have a string in this form:
url("http://www.example.com/imgs/backgrounds/bg80.jpg") repeat scroll 10% 0% transparent

This is from a CSS styling  for a certain element that at the moment isn't visible on the page. What I need to do is preload that background image, but to do this I need it's URL, and I'm trying to write a regular expression find it.
I know the http://www.example.com/imgs/backgrounds/ part remains constant, the only thing changing is the image name itself, which can end with either .jpg or .png.
This was one attempt:
(http:\/\/www.example.com\/imgs\/backgrounds\/)[\w\.\-]*

The problem with this being that only the http://www.example.com/imgs/backgrounds/ part was being picked up. So I tried this, but this doesn't work at all!
(http:\/\/www.example.com\/imgs\/backgrounds\/)[\w\.\-]*(.jpg|.png)

What am I doing wrong?
Thank you for any help!

A: I feel like Gaby's answer is almost correct, but according to this answer, unquoted CSS URLs can include escaped characters (ex: background-image: url(http://foobar.com?\'\() is a valid way to load a background image with the url http://foobar.com?').  A more accurate expression for capturing all URLs in a stylesheet (tests here):
/[:,\s]\s*url\s*\(\s*(?:'(\S*?)'|"(\S*?)"|((?:\\\s|\\\)|\\\"|\\\'|\S)*?))\s*\)/gi
var urlMatchingRegex = /[:,\s]\s*url\s*\(\s*(?:'(\S*?)'|"(\S*?)"|((?:\\\s|\\\)|\\\"|\\\'|\S)*?))\s*\)/gi;

myStylesheetString.replace(urlMatchingRegex, function(fullMatch, url) {
  //Replacement handler
});

A: A background url can have ' or " or none around the url inside the parenthesis
Valid urls

*

*url("http://www.example.com/imgs/backgrounds/bg80.jpg")

*url('http://www.example.com/imgs/backgrounds/bg80.jpg')

*url(http://www.example.com/imgs/backgrounds/bg80.jpg)
So for a generic solution you could use
var background = 'url("http://www.example.com/imgs/backgrounds/bg80.jpg") repeat scroll 10% 0% transparent',
    reg = /(?:\(['"]?)(.*?)(?:['"]?\))/,
    extracterUrl = reg.exec(background)[1];

A: Just capture anything between ( and )
var url = str.match(/\((.*?)\)/)[1].replace(/('|")/g,'');

var image = new Image();
image.src = url;

FIDDLE

A: I just do it now and I get to this page so I think so my pattern its simply and absolutely:
/url(?:\([\'"\s]?)((?!data|http|\/\/)(\.\.?\/|\/))(.*?)(?:[\'"\s]?\))/g

A: So here's a cleaned up version that only focuses on images & converts found images relative paths to absolute. This way you can preload easily. This code creates an array with original URL and absolute URL. You can simply loop through the result and preload the absolute URL images
var myString = " \
    background: url(../images/magnifier-ico.png) no-repeat left center; \
    background: url(../../images/globe-ico.png) no-repeat; \
    background: url(../images/magnifier-ico.png) no-repeat left center; \
";

var myRegexp = /(?:\(['|"]?)(.*?\.(png|jpg|gif|jpeg|tiff){1})(?:['|"]?\))/gi;

// Set location of CSS file being read
var cssFile = "/css/mobile/style.css";

// Figure out depth of the css file in relation to root
var cssPath = cssFile.split("/").filter(function(item){return item.length>0;});
var depth = (cssPath.length);

// Array to store found images
var images = [];

// Start search
var match = myRegexp.exec(myString);
while (match) {
  // get image
  var foundImage = match[1];

  // Look for next one
  match = myRegexp.exec(myString);

  // Convert relative path to absolute
  var relativeDepth = 0;
  var pathRegexp = /\.\.\//gi;
  var pathMatch = pathRegexp.exec(foundImage);
  while(pathMatch){
    relativeDepth++;
    pathMatch = pathRegexp.exec(foundImage);
  }
  // Strip the relativity
  var pathlessImage = foundImage.split("../").join("");
  // Now to the final conversion
  var absolute = "";
  for(var i=0;i<depth-relativeDepth-1;i++)
    // Reconstruct it all back
    absolute += "/" + cssPath[i];

  // Now add image name
  absolute += "/" + pathlessImage;

  // Store final cleaned up product
  images.push({original:foundImage,absolute:absolute});
}

console.log(images);

Here's working JSbin
http://jsbin.com/nalimaruvu/2/


text:
Q: Asterisk instantly terminates WebRTC (JSSIP) call I'm running Asterisk 11.2.2 with SRTP and STUN support under Calculate Linux (Gentoo-based distribution).
When I try to call from one WebRTC instance to another, using JSSIP, the call passes, but if i answer it on another instance, the call suddenly terminates. Using Asterisk debug mode, i can catch 488 error (Not acceptable here).
If I use one SIP phone (Ekiga) instance instead of WebRTC, then I can call JSSIP from it, and everything works fine. Nevertheless, I can't call Ekiga from JSSIP, and this makes me confused.
Can you advise me, what have I do to localize this bug?

A: The problem was in my Asterisk: it had some WebRTC issues in 11.2.2 version. Upgrading to 11.4.0 makes everything works fine.

A: I just encountered the same issue, for me it was codecs issue. I was allowing only G729 in sip.conf file and hence it was throwing 488 error. For now, I fixed it by setting allow=all (I would check later on which particular codec does it needs).