text:
Q: C# - Double gets unwantedly converted to null I'm trying to submit 3 doubles in a form while use C#. Whenever i input integers in the form everything works fine, but when i set doubles as the input they automatically are getting converted to null when i submit my form? I also dont see any exceptions getting caught..
Here's my controller code that i use:
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(int? mainRiskanalysisId, int? categoryId, int? zoneId, int? equipmentId, int? taskId,
        string activity, string action, string descriptionPotentialRisk, int? dangerId, int? consequenceId,
        int? dangerousEnergiesId, string preventionMeasures, string safetyProcedures, double? preSeriousness,
        double? preProbability, double? preExposure, double? preRiskDegree, double? preRiskCategory, IFormCollection collection)
    {
        try
        {
            Riskanalysis riskanalysis = new Riskanalysis()
            {
                mainRiskanalysisId = mainRiskanalysisId,
                categoryId = categoryId,
                zoneId = zoneId,
                equipmentId = equipmentId,
                taskId = taskId,
                activity = activity,
                action = action,
                descriptionPotentialRisk = descriptionPotentialRisk,
                dangerId = dangerId,
                consequenceId = consequenceId,
                dangerousEnergiesId = dangerousEnergiesId,
                preventionMeasures = preventionMeasures,
                safetyProcedures = safetyProcedures,
                preSeriousness = preSeriousness,
                preProbability = preProbability,
                preExposure = preExposure,
                preRiskDegree = preRiskDegree,
                preRiskCategory = preRiskCategory
            };

            _manager.InsertRiskanalysis(riskanalysis);

            return RedirectToAction(nameof(Create));
        }
        catch (FormatException fe)
        {
            Console.WriteLine(fe.ToString());
        }
        catch(Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        return null;
    }

Here are my inputs i use for the doubles:

                <input asp-for="preSeriousness" id="preSeriousnessInput" class="form-control" type="text" />

                <input asp-for="preProbability" id="preProbabilityInput" class="form-control" type="text" />

                <input asp-for="preExposure" id="preExposureInput" class="form-control" type="text" />

The doubles i'm talking about are: preSeriouness, preProbability, preExposure.
Anyone has a clue of what could be wrong?

A: This code
    catch (Exception e)
    {
        return View();
    }

Is actively swallowing Exceptions, without logging them. While it is one thing to not tell the user in a WebApplication the exception, also not logging them is a critical fault. You propably get an exception, you just went out of your way to hide it from yourself.
There are two articles on Exception handling. One is a classification, so you know what to catch and what not to catch. The other is general advice on handling and (re)throwing Exceptions.
I am confident that once you read through them and fixed cases like the above code, you get a Exception that will tell you exactly what is going wrong.


text:
Q: How to loop two variables simultaneously in PLSQL I have two tables have relationship to each other, an owner and an owned table, now I want to query both tables and return data from these two tables. But when I try to query results from two tables, the select will return extra data to me.
Below shows how I create the two tables
create table owner(
    id         integer not null,
    name        varchar2(22) not null,
    primary key (id) );

create table owned(
    id         integer not null,
    restaurantId       char(10) not null,
    resgisterCode      integer not null,
    primary key (id, restaurantId),
    foreign key (aid) references owner(id),
    foreign key (restaurantId) references restaurant(restaunrantId) );

I want to get the owner name and the corresponding resgisterCode and this is what I tried
Cursor get_ownerId_registerCode(OwnerID owner.id%type) is
select owner.name, owned.resgisterCode INTO name, code from owner, owned where owner.id = Id AND owned.aid = owner.aid Order By owned.registerCode desc;

A: Well, code you posted can't work anyway (not that it "returns extra data") as INTO clause can't be used in a cursor declaration.
Problem you specified ("extra data") is due to wrong parameter name. This is what you did:
where owner.id = Id
                 --
                 this is a parameter, isn't it?
                 (you should've posted the whole PL/SQL procedure to avoid confusion)

For Oracle, it is just the same as if you used where owner.id = owner.id or even where 1 = 1 so query returned everything. You shouldn't name parameters the same as column names - precede their names with a prefix, e.g. par_id or p_id or whatever you find appropriate.
Apart from that, I'd suggest you to use a cursor FOR loop because - if you do -  final code is much simpler as you don't have to open the cursor, fetch from it, pay attention about exiting the loop or closing the cursor - Oracle does that for you.
Therefore, consider something like this:
create or replace procedure p_test (par_id in owner.id%type) is
begin
  for cur_r in (select owner.name, owned.resgisterCode
                -- INTO name, code -- no INTO clause in cursor!
                from owner join owned on owned.aid = owner.aid
                where owner.id = par_id    -- parameter is used here
                order by owned.registercode desc
               )
    dbms_output.put_Line(cur_r.name ||', '|| cur_r.registercode);
  end loop;
end;
/

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the limitations of highlighting in elasticsearch In my elasticSearch index, I have a field that stores too-long texts which is 100000 words.
If I search for multiple words with query_string then I am getting results but all the search terms are not getting highlighted.
Example query:
GET test_index/_search
{
   "track_total_hits":true,
   "timeout":"5s",
   "_source":{
      "includes":[
         "_id"
      ]
   },
   "highlight":{
      "require_field_match":true,
      "fields":{
         "*":{

         }
      },
      "pre_tags":[
         "<b>"
      ],
      "post_tags":[
         "</b>"
      ],
      "max_analyzed_offset":200974
   },
   "query":{
      "bool":{
         "should":[
            {
               "query_string":{
                  "default_field":"*",
                  "query":"\"sample test search\"~200000",
                  "default_operator":"AND",
                  "lenient":true
               }
            }
         ]
      }
   },
   "sort":{
      "filedDate":"desc",
      "caseId":"desc"
   }
}

So what I want to know is, is there any limitations in highlighting like

*

*Maximum number of words that can be highlighted

*Maximum distance between the matched search terms
..etc


text:
Q: CAKEPHP SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cms_database.users' doesn't exist. iam using cakephp 4 SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cms_database.users' doesn't exist
Could this be caused by using Auto-Tables?
Some of the Table objects in your application were created by instantiating "Cake\ORM\Table" instead of any other specific subclass.
This could be the cause for this exception. Auto-Tables are created for you under the following circumstances:
The class for the specified table does not exist.
The Table was created with a typo: $this->getTableLocator()->get('Atricles');
The class file has a typo in the name or incorrect namespace: class Atricles extends Table
The file containing the class has a typo or incorrect casing: Atricles.php
The Table was used using associations but the association has a typo: $this->belongsTo('Atricles')
The table class resides in a Plugin but no plugin notation was used in the association definition.
Please try correcting the issue for the following table aliases:
Users

A: Thanks for your concern..
I solved my error..
I place this resolver method code in my Application.php file to change default users table to admins table. here is the code-
$authenticationService->loadIdentifier('Authentication.Password', [
    'fields' => [
        'username' => 'username',
        'password' => 'password',

    ],

    'resolver' => [
    'className' => 'Authentication.Orm',
    'userModel' => 'Admins',
    ]
]);


text:
Q: Permit requests for GET request I have a Spring Cloud application with OAuth2 authorization:
@RestController
@RequestMapping("/product")
public class ProductController {

    @GetMapping("/categories")
    public ResponseEntity<Map<Integer, CategoryFullDTO>> getCategoriesList() {

        .......
    }
}

I added this security configuration:
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(final HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(HttpMethod.POST, "/oauth/token").permitAll()
                .antMatchers(HttpMethod.GET, "/product/categories").permitAll()

                .anyRequest().authenticated()
                .and()
                .httpBasic().disable()
                .formLogin()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                .and().csrf().disable();
    }
}

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(HttpMethod.POST, "/oauth/token").permitAll()
                .antMatchers(HttpMethod.GET, "/product/categories").permitAll()

                .anyRequest().authenticated()
                .and()
                .httpBasic().disable()
                .formLogin()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                .and().csrf().disable();

//        http.requiresChannel()
//                .anyRequest().requiresInsecure();
    }
}

Github: https://github.com/rcbandit111/OAuth2/blob/master/src/main/java/org/engine/security/WebSecurityConfig.java
When I open Angular application I get access error: Failed to load resource: the server responded with a status of 401 () for /product/categories
Do you know what configuration I need to apply in order to make this path public without mandatory authorization?
P.S when I use Postman to make request it's working. It does return data without authorization. But looks like if you have auth_token still present and it has been expired, it seems that my authorization interceptor still catches it and apply it to the request which causes the error.
Looks like JWT token verification logic returns the error. How I can solve this?

A: If your Angular application uses an interceptor that injects headers with your token, you could use HttpBackend to prevent going through the interceptor chain:
https://angular.io/api/common/http/HttpBackend


text:
Q: How to add the same event handler to more than one element in D3 I made a bar chart where a numeric value is displayed as a <text> element inside the bar.
When a mouse hovers on a bar, additional info is displayed. However, when mouse cursor hovers over the text, the display doesn't show because the event handler is only attached to the <rect>.
I tried d3.selectAll(rect text), but doesn't seem to work.
The only other way I can think of is to place them inside <g> and add event handler to the <g>.
Is there a more efficient way?
http://jbk1109.github.io/tennisMapWithPlayersListOnHover.html


text:
Q: Difference between Entry Type "keyEntry" and "trustedCertEntry" in a keystore I don't have much knowledge in this area, but i have still tried to do things by googling. Here is the problem i am facing.
Case 1(Works):
I have a CA signed certificate and i would like to use it in my Web Application. I first created a keystore. I see that it creates an entry type "keyEntry" in the keystore. Then i import the CA signed certificate to the keystore created.
Here are the steps:
keytool -genkeypair  -keystore keystore.jks

I see an entry in the keystore of type "keyEntry" of alias "mykey"
Now i import the certificate:
keytool -importcert -alias abc -file cert.crt -keystore keystore.jks

Now i see another entry of trype "trustedcertEntry".
With this keystore i am able to access my web application when i uploaded it.
Case 2 (doesn't work):
I create a keystore on the fly while importing the certificate.
keytool -importcert  -alias abc -file cert.crt -keystore keystore2.jks

Here i see only one entry type which is "trustedcertEntry"
With this keystore i am not able to access my web application.
Question:
What is key entry type "keyEntry" and "trustedcertEntry"  and why does my keystore works only when i have the entry type "keyEntry"

A: My understanding of keytool is tenuous at best but I think the trick is that with Case 2, by omitting the -genkeypair, you're not generating the necessary private key.
In Case 1, the steps you're using are: create a private key pair (public key and private key), and then import a certificate into the trusted certificates for the keystore. Presumably you have another certificate in the keystore that's joining with the private key though it's possible the trusted cert is acting as the cert or your application isn't using a joined keypair/cert in the same file.
I can say that a 'trustedCertEntry' is a certificate which is trusted by the keystore. This is essential for allowing certificate chains (ex: Root-CA signs Intermediate-CA1 which signs End-Cert1. Without having both Root-CA and Intermediate-CA1 as trustedCertEntry, the keystore doesn't trust the end cert). TrustedCertEntry do not have private keys associated with them, only the public key the certificate contains.
A keyEntry (I think!) is a public/private key pair without the certificate.
A privateKeyEntry is a public/private key pair with an associated CA-signed or self-signed certificate.


text:
Q: Upgrading Rails 2.3.11 to 3.1.3 - trying to replace proxy_owner with proxy_association.owner Working on upgrading an internal gem from Rails 2.3.11 to 3.1.3 - have the following piece of code which models a channel of actions:
  has_many :actions, :class_name => 'Streamer::Model::Action', :through => :action_channel_entries, :order => 'actions.id desc' do
    def publish(action)
      proxy_association.owner.publish(action)
    end

    def subscriptions
      proxy_association.owner.subscriptions
    end
  end

Instead of a CollectionProxy the self in this has_many is an ActiveRecord::Relation as the error from my unit test demonstrates:
undefined local variable or method `proxy_association' for #<ActiveRecord::Relation:0x106d60f68>
from /Users/brett/.rvm/gems/ree-1.8.7-2011.03@ncsl_r313/gems/activerecord-3.1.3/lib/active_record/relation.rb:459:in `method_missing'
from /Users/brett/Projects/ncsl/app/lib/streamer/model/action_channel.rb:11:in `subscriptions'
from (irb):10

Right now I'm just looking for suggestions on how to investigate this further and perhaps some understanding of the different uses of CollectionProxy and ActiveRecord::Relation.

A: You can try something like this:
@association.owner

A: The problem was fixed via this issue: https://github.com/rails/rails/issues/3890


text:
Q: How to get ratio of scale image, when it's autoscaled by background-cover? I have some problems:
I need to bind some text to positions om image (you know, like marks on redpen.io an other services). Text is binded to big image, well, like 1900x1200px.
Then on other pages I add this image to background of element, stretched to all window:
#backg {
    width: 100%;
    height: 100%;
    background-image: 'url-to-big-image.jpg'
    background-repeat: no-repeat;
    background-size: cover;
}

And then i have troubles: I can't bind my saved marks to this element!
First, I divide original height and width of element to window height and width: Qh and Qw.
I take original top and left css of mark, then multiply top*Qh and Qw*left.
It works for width, but not for height! It's somehow scaled by browser, and position of elements on image doesn't match.
How can I get ratio of height scaling, to position my marks?
Thanks in advance!

A: It is hard to help you with so few lines of code.
I tried to provide a simple improvment by changing this following CSS lines:
#backg {
    background-size: 100% 100%;
    position: relative;
}

You can play with it on this jsfiddle.
Is it what you are looking for?

[UPDATE]
You can use the padding-top trick to have a container that fit to the image size.
#backg {
    height: 0;
    padding-top: <image-ratio>%;
}

You can play with it on this updated jsfiddle.
Cheers,
Thomas.

A: Despite the 'Hard' issue, the answer was quite simple, though not obvious :) All the matter between scales:
First, we need to find coefficients of ratio between "real" height and width of picture and shown in the background:
var imgSize = new Image();
imgSize.onload = function() {
    $('#ourdiv').css('background-image', 'url("' + imgSize.src + '")');
    h_real = this.height;
    w_real = this.width;

    q_h = h_real / $(window).height();
    q_w = w_real / $(window).width();
};
imgSize.src = 'path_to_img.jpg';

Then, divide our "real" positions of element to coef's. However,depending on whether the coefficient is greater, we should divide on another:
if (q_w > q_h)
    {
        top_d = Math.round(top_d / q_h);
        left_d = Math.round(left_d / q_h);
    }
else
    {
        top_d = Math.round(top_d / q_w);
        left_d = Math.round(left_d / q_w);
    }

And voila! - all elements on same places!


text:
Q: How to retrieve intermediary state in TensorFlow RNN I am running an RNN on a signal in fixed-size segments. The following code allows me to preserve the final state of the previous batch to initialize the initial state of the next batch.
rnn_outputs, final_state = tf.contrib.rnn.static_rnn(cell, rnn_inputs, initial_state=init_state)

This works when the batches are non-overlapping. For example, my first batch processes samples 0:124 and final_state is the state after this processing. Then, the next batch processes samples 124:256, setting init_state to final_state.
My question is how to retrieve an intermediary state when the batches are overlapping. First, I process samples 0:124, then 10:134, 20:144, so the hop size is 10. I would like to retrieve not the final_state but the state after processing 10 samples.
Is it possible in TF to keep the intermediary state? The documentation shows that the return value consists only of the final state.
The image shows the issue I am facing due to state discontinuity. In my program, the RNN segment length is 215 and the hop length is 20.

Update: the easiest turned out to be what David Parks described:
rnn_outputs_one, mid_state = tf.contrib.rnn.static_rnn(cell, rnn_inputs_one, initial_state=rnn_tuple_state)
rnn_outputs_two, final_state = tf.contrib.rnn.static_rnn(cell, rnn_inputs_two, initial_state=mid_state)
rnn_outputs = rnn_outputs_one + rnn_outputs_two

and
prev_state = sess.run(mid_state)

Now, after just a few iterations, the results look much better.

A: In tensorflow the only thing that is kept after returning from a call to sess.run are variables. You should create a variable for the state, then use tf.assign to assign the result from your RNN cell to that variable. You can then use that Variable in the same way as any other tensor.
If you need to initialize the variable to something other than 0 you can call sess.run once with a placeholder and tf.assign specifically to setup the variable.

Added detail:
If you need an intermediate state, let's say you ran for timesteps 0:124 and you want step 10, you should split that up into 2 RNN cells, one that processes the first 10 timesteps and the second that continues processing the next 114 timesteps. This shouldn't affect training and back propagation as long as you use the same cell (LSTM or other cell) in both static_rnn functions. The cell is where your weights are defined, and that has to remain constant. Your gradient will flow backwards through the second cell and then finally the first appropriately.

A: So, I came here looking for an answer earlier, but I ended up creating one.
Similar to above posters about making it assignable...
When you build your graph, make a list of sequence placeholders like..
my_states = [None] * int(sequence_length + 1)

my_states[0] = cell.zero_state()

for step in steps:
    cell_out, my_states[step+1] = cell( )

Then outside of your graph after the sess.run() you say
new_states = my_states[1:]

model.my_states = new_states

This situation is for stepping 1 timestep at a time, but it could easily be made for steps of 10. Just slice the list of states after sess.run() and make those the initial states.
Good luck!


text:
Q: Managing Descriptive URLs I have noticed that many blogs use URLs that look like this:
http://www.hanselman.com/blog/VirtualCamaraderieAPersistentVideoPortalForTheRemoteWorker.aspx
I assume this is done for search engine optimization.
How is this read from the underlying data model?  Do you really search for
VirtualCamaraderieAPersistentVideoPortalForTheRemoteWorker

in the database?
If so, how is the description managed?  If it is a key, is the rule that it can never be changed once it is created, without breaking web links?

A: You are correct that it is done for search engine optimization.  It works best if you separate the individual words with dashes or underscores however.
These SE-friendly url portions are often called slugs or url slugs.  A slug must be unique in your application, and generally the function that creates or checks them must take this into account.
Just like anything else, there are multiple ways to implement something like this.  Generally you store a string of text about a database item, eg. an article title.  You can convert this into the url slug at load time dynamically if you don't want to store it, or you can save the real title and the url slug at insert/update time, and use the slug as your database selection criteria when loading the relevant page.
If you want to be super-robust with your app, you could automatically save a slug history, and generate "301 Moved Permanently" headers whenever a slug changed.

A: Typically when the article is created, that string is stored in the database as a key, yes. Some blog engines like Wordpress allow you (the author) to manually change what that string is, and after you do that, links to the old string will no longer function.
In Wordpress, they call this the "permalink," although different engines have their own names for it. I don't think there is a universal term for it.

A: There are different strategies for search engine friendly URLs. Given your example URL, you could for example search for the whole string, or use the C# hash value as (probably non-unique) key. Either way links to this page will break if the title is changed. One solution is to embed an additional unique key in the URL (see amazon.com for examples).
If you're interested in the way dasBlog handles URLs, you can get the full source code at http://www.dasblog.info/ .

A: There's no reason why VirtualCamaraderieAPersistentVideoPortalForTheRemoteWorker couldn't be a key in the 'posts' table, given that even a really big blog won't have more than, say a couple of thousand rows in the post table.
If you did decide to rewrite it, then you could create a 301 redirect for that url without a lot of damage SEO-wise.
But, as I discussed in the comments to your question, the bearing of static urls like this on SEO is no longer relevant. The real benefit is for the user to have a structure that's visually easier to navigate ('hackable' urls).
Google wouldn't care if the url said:
hanselman.com/blog/index.aspx?id=123

or
hanselman.com/blog/foobar.aspx

The ranking would be the same, regardless.

A: Read up on Dynamic URLs and Apache mod_rewrite.
Also check this mod_rewrite rule generator out.
As an example of what mod_rewrite can do for you as far as descriptive URLs, The permalink might be thought of as the url:
 http://www.somesite.com/catalog.php?cat=widgets&product_id=1234

And the rewrite module will create the much more descriptive and simpler:
 http://www.somesite.com/catalog/widgets-1234.html

dynamically as needed. I am not sure if any of these mappings are cached server-side for future use, but I don't imagine it uses a huge amount of overhead to process the rules.
Here is the rule that did the above rewrite which is placed in a .htaccess file:
 RewriteEngine On
 RewriteBase /
 RewriteCond %{QUERY_STRING} ^cat\=([^&]+)\&product_id\=([^&]+)$
 RewriteRule ^$ /catalog/%1-%2.html [R=301,

This example was found here.
It does not take much overhead to dynamically generate a descriptive URL on the fly and have it serve the permalink content. I don't think they are worrying about storing or caching the rules in a database at all.
It seems to be highly recommended by SEO enthusiasts that you create a google sitemap.xml to assist in google indexing these (possibly infinite, or to the upper bound of URL length which is undefined but > 2000 char URL won't work in many browsers) statically generated pages. As long as the rules are deterministic they might as well be permalinks.


text:
Q: ValueError: Input data must be a pandas object to reorder     ValueError                                Traceback (most recent call last)
Cell In[49], line 2
1 #построен для спальни
----> 2 sns.countplot(data.bedrooms,order=data['bedrooms'].value_counts().index)
File c:\Users\brazz\AppData\Local\Programs\Python\Python311\Lib\site-packages\seaborn\categorical.py:2943, in countplot(data, x, y, hue, order, hue_order, orient, color, palette, saturation, width, dodge, ax, **kwargs)
   2940 elif x is not None and y is not None:
   2941     raise ValueError("Cannot pass values for both `x` and `y`")
-> 2943 plotter = _CountPlotter(
   2944     x, y, hue, data, order, hue_order,
   2945     estimator, errorbar, n_boot, units, seed,
   2946     orient, color, palette, saturation,
   2947     width, errcolor, errwidth, capsize, dodge
   2948 )
   2950 plotter.value_label = "count"
   2952 if ax is None:

File c:\Users\brazz\AppData\Local\Programs\Python\Python311\Lib\site-packages\seaborn\categorical.py:1530, in _BarPlotter.__init__(self, x, y, hue, data, order, hue_order, estimator, errorbar, n_boot, units, seed, orient, color, palette, saturation, width, errcolor, errwidth, capsize, dodge)
   1525 def __init__(self, x, y, hue, data, order, hue_order,
   1526              estimator, errorbar, n_boot, units, seed,
   1527              orient, color, palette, saturation, width,
   1528              errcolor, errwidth, capsize, dodge):
   1529     """Initialize the plotter."""
-> 1530     self.establish_variables(x, y, hue, data, orient,
   1531                              order, hue_order, units)
   1532     self.establish_colors(color, palette, saturation)
   1533     self.estimate_statistic(estimator, errorbar, n_boot, seed)

File c:\Users\brazz\AppData\Local\Programs\Python\Python311\Lib\site-packages\seaborn\categorical.py:481, in _CategoricalPlotter.establish_variables(self, x, y, hue, data, orient, order, hue_order, units)
    479 if order is not None:
    480     error = "Input data must be a pandas object to reorder"
--> 481     raise ValueError(error)
    483 # The input data is an array
    484 if hasattr(data, "shape"):

ValueError: Input data must be a pandas object to reorder


text:
Q: Low pass filter implementation Correct or wrong? I've been working on 2 sensors signals measuring vibrations of a rotating shaft. Since there is residual noise in the signal. I tried to filter it by detrending, zero padding and applying low pass filter. Below I'm attaching the graphs of the signal before and after filtering. There is a huge variation in the signal after filtering that makes me think if I'm really doing it in the right way.

My Matlab code is
X = xlsread(filename,'F:F');
Y = xlsread(filename,'G:G');

%Calculate frequency axis
fs = 1e6  ; % Sampling frequency (Hz)
NFFT = 2^nextpow2(length(X));  % Zero padding to nearest N power 2
df = fs/NFFT;
dt = 1/df;
%Frequency Axis defintion
f = (-(fs-df)/2:df:(fs-df)/2)';

X(2^ceil(log2(length(X))))=0;
Y(2^ceil(log2(length(Y))))=0;

%calculate time axis
T = (dt:dt:(length(X)*dt))';

subplot(2,2,1)
plot(T,X);
xlabel('Time(s)')
ylabel('X amplitude')
title('X signal before filtering')
subplot(2,2,2)
plot(T,Y);
xlabel('Time(s)')
ylabel('Y amplitude')
title('Y signal before filtering')

 X = detrend(X,0); % Removing DC Offset
 Y = detrend(Y,0); % Removing DC Offset

 % Filter parameters:
 M = length(X);    % signal length
 L = M;          % filter length
 fc = 2*(38000/60);   % cutoff frequency

 % Design the filter using the window method:
 hsupp = (-(L-1)/2:(L-1)/2);
 hideal = (2*fc/fs)*sinc(2*fc*hsupp/fs);
 h = hamming(L)' .* hideal; % h is our filter

 % Zero pad the signal and impulse response:
 X(2^ceil(log2(M)))=0;
 xzp = X;
 hzp = [ h zeros(1,NFFT-L) ];

 % Transform the signal and the filter:
 X = fft(xzp);
 H = fft(hzp)';
 X = X .* H;
 X = ifft(X);
 relrmserrX = norm(imag(X))/norm(X); % checked... this for zero
 X = real(X)';

 % Zero pad the signal and impulse response:
 Y(2^ceil(log2(M)))=0;
 xzp = Y;
 hzp = [ h zeros(1,NFFT-L) ];

 % Transform the signal and the filter:
 Y = fft(xzp);
 H = fft(hzp)';
 Y = Y .* H;
 Y = ifft(Y);
 relrmserrY = norm(imag(Y))/norm(Y); % check... should be zero
 Y = real(Y)';

I plotted the after filtering and as you can see in the picture there is a clear deviation. I want to only filter noise but the signal seem to loose other components and I'm little confused if thats the right way of doing filtering.
Any suggestion, hints or ideas would be helpful.
In the end I want to plot X vs Y to give orbits of the shaft vibration. Please also find below another picture of the unfiltered and filtered orbit. As you can see in the picture there is also change in the orbits from the original one (left image with lot of noise).

P.S.: I don't have DSP tool box

A: There is no problem with your FFT and IFFT.
You can test your code with a simple sine wave, with a very low frequency.  The final output should be (almost) the same sine wave, since you are low-pass filtering it.
You've defined X (and Y) from 0 to some value.  However, you've defined H from - (L-1)/2 to some positive value.  Mathematically, this is fine, but you are simply taking an fft of H.  Matlab thinks this has the same time-scale as X, when you multiply the ffts together!
So, in reality, you've taken the fft of XHfft(delta(t-d)), where d is the resulting time-shift.  You can either undo this time-shift in the frequency domain, or the time-domain.


text:
Q: Saitek x45 HOTAS range values not mapping properly I have a saitek x45 HOTAS. I have the drivers downloaded from saiteks ftp server here. I've done the built in windows joystick calibration wizard, and shows as operating perfectly fine with a normal range of motion.
How ever in game (elite dangerous) and on html5 Gamepad Tester, the values my stick is outputting seem to be off. my joystick's entire range of motion becomes confined to the Upper right quadrant of its range of motion. On the Gamepad tester, every value outputted by the stick is in the -9,-9 range. And the midpoint on my throttle and dials are all way off.
I thought windows calibration was supposed to account for this, but neither seems to agree. Any ideas on what I can do to restore full range of motion and functionality?

A: Figured it out. Went into regedit and searched for saitek and deleted anything that came up. maybe reckless but effective. Also went to Sys32 and deleted all dlls that started with the string "saic". after this was done, i uninstalled the controller, unplugged it, and plugged it back in. windows went into some autoinstaller and pulled drivers from the web. when it was complete, it registered my hats as a bunch of buttons instead of hats but they still work perfectly. analog range of motion was restored and a quick calibration got everything working.


text:
Q: Cannot get Scala to run I've tried on two separate occasions to get Scala installed on my MacBook Air and have run into the same problem both times.
The first stime I installed scala, I moved all the appropriate files into the bin, lib, & src directories. When I type "scala" in the Terminal I get the following error:
Error occurred during initialization of VM
java/lang/ClassNotFoundException: error in opening JAR file /usr/lib/charset.alias

So I have poked around and tried to figure it out. The problem I'm running into is this seems to be a fairly common error (and I understand what causes this error) but I can't figure out what is actually causing this to happen. I made sure I had all the proper .jar files in my lib directory. After a while, I decided to try installing Scala using Homebrew. After successfully installing Scala using Homebrew, I get the same error above when I type "scala" in the Terminal.
What am I missing? Thanks in advance!

A: Try installing via HomeBrew. You can get SBT that way, too,
Edit:
D'Oh! You did... In which case, I'd look into whether you Java / JVM / JRE / JDK installation is intact. The name of the file it's complaining about is suspect for a Mac.
Edit the next:
I really shouldn't shoot from the hip so much. My MacBook does have that file! It contains this:
# This file contains a table of character encoding aliases,
# suitable for operating system 'darwin10.0'.
# It was automatically generated from config.charset.
# Packages using this file:
* UTF-8


text:
Q: Word Document.Close and Thread Abort Exception Windows 7 I have a project type office 2010 word document.
In ribbon there is a button which does some logic.
On the end of this logic there is a line like:
Globals.ThisDocument.Application.ActiveDocument.Close(ref dowdSaveChanges, ref oMissing, ref oMissing);

On Windows XP everything worked ok but when a user tries to work with this document on Windows 7 this line of code throws exception like:
System.Threading.ThreadAbortException: The thread was beeing aborted.
   w Document35.WorkflowRibbon.Button1Click(Object sender, RibbonControlEventArgs e) w D:\_DEV\WorkflowCS2_WordTemplatest_Office2010\Document35\WorkflowRibbon.cs:wiersz

What could be the reason?

A: This seems to be an issue of the AppDomain unloading and returning execution from unmanaged to managed code. See MSDN forums which discusses this ThreadAbortExcpetion behavior. Potentially you just need to update the VSTO Runtime.

A: try this:
    private void Button1Click(object sender, RibbonControlEventArgs e)
    {
        object oMissing = System.Reflection.Missing.Value;
        object dowdSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
        try
        {
             Globals.ThisDocument.Application.ActiveDocument.Close(ref dowdSaveChanges, ref oMissing, ref oMissing);
        }
        catch (ThreadAbortException t)
        {
            Globals.ThisDocument.ThisApplication.Quit(ref dowdSaveChanges, ref oMissing, ref oMissing);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }


text:
Q: How widespread is the pronunciation of "Parmesan" as /ˈpɑɹ.məˌʒɑn/ instead of /ˈpɑɹ.məˌzɑn/? The letter s in the word Parmesan (meaning the cheese, named after the Parma region of Italy) is pronounced quite widely (Br & Aus AFAIK) as a /z/, per Wiktionary:

*

*UK, also found in the US: /ˈpɑɹ.məˌzɑn/

*found in the US: /ˈpɑɹ.məˌʒɑn/
And in Australia (no reference, just experience) it's /ˈpɑɹ.məˌzɑn/ (maybe heading for /ˈpɑɹ.məˌsɑn/).
However, in Seattle WA and Portland OR, the locals all (IME) pronounce it with a soft /ʒ/ sound, like in the French je, so /ˈpɑɹ.məˌʒɑn/
Is this a "northwest only" variation? How much of the US says /ˈpɑɹ.məˌʒɑn/?
Does this also occur in other countries?
I note that Merriam Webster includes the spelling pronunciation "-zhan" (albeit last) as an alternative pronunciation.


text:
Q: c++ destructor called before cout #include <iostream>
#include <string.h>
using namespace std;

class Location
{
double lat, lon;
char *emi;

public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
void print () const;
friend ostream& operator<< (ostream&, const Location &);
void operator! ();

protected: ;

private:
};

Location::Location(int lat, int lon, const char *emi)
{
this->lat=lat;
this->lon=lon;
if (emi!=NULL)
{
this->emi=new char [strlen (emi)+1];
strcpy (this->emi, emi);
}

}

Location::~Location()
{
if (emi!=NULL)
delete []emi;

}

Location::Location(const Location &l)
{
lat=l.lat;
lon=l.lon;
if (l.emi!=NULL)
{
emi=new char [strlen (l.emi)+1];
strcpy (emi, l.emi);
}
}
void Location::operator! ()
{
if (!(strcmp(this->emi, "north")))
strcpy (this->emi, "south");
else strcpy (this->emi, "north");
}

void Location::print() const
{
cout<<this->emi<<endl;
cout<<this->lon<<endl;
cout<<this->lat<<endl;
cout<<endl;
}
class Adress
{
char *des;
Location l1;
char *country;
public:
Adress(char *,const Location &, char *);
virtual ~Adress();
friend ostream& operator<< (ostream&, const Adress &);

protected:

private:
};

Adress::Adress(char *des,const  Location &l1, char *country)
{
if (des!=NULL)
{
this->des=new char [strlen (des)+1];
strcpy (this->des, des);
}
if (country!=NULL)
{
this->country=new char [strlen (country)+1];
strcpy (this->country, country);
}
this->l1=l1;
}

Adress::~Adress()
{
if (country!=NULL)
delete []country;
if (des!=NULL)
delete []des;
}
ostream& operator<< (ostream &os, const Adress& a){
os <<"Descrition: " << a.des<<endl;
os<<"Country: "<<a.country<<endl;
a.l1.print();
return os;
}

int main ()
{
Adress a1 ("dsad", Location (323, 34, "fdsf"), "fsdf");
cout<<a1;
}

The problem is that when I create an Adress object and display it, all the fields are correct , but the "emi" which is messed up, showing a random character. I think the destructor is called before I display it. If I remove the Location destructor it works. How should I resolve it? I'm sorry for my mistakes but I am a newbie.

A: First of all, it would be better to use std::string rather than char* but I will explain your problem for the education goal.
You must ensure after constructing an object, all of its member variables are initialized. In the case of Location class for example; you did not initialize the emi member variable if the third argument of the constructor is nullptr. so I changed it a little:
Location::Location(int _lat, int _lon, const char* _emi)
    : lat(_lat)
    , lon(_lon)
    , emi(nullptr)
{
    if (_emi != nullptr)
    {
        emi = new char[strlen(_emi) + 1];
        strcpy(emi, _emi);
    }
}

Next, you have a raw pointer in your class and you can not simply copy or assign it. You have to implement the assignment operator as well as the copy constructor.
Location& Location::operator=(const Location& other)
{
    if (this != &other)
    {
        lat = other.lat;
        lon = other.lon;
        if (emi) delete[] emi;
        emi = new char[strlen(other.emi) + 1];
        strcpy(emi, other.emi);
    }
    return *this;
}


text:
Q: Celery tasks get blocked by SSE client I am running a SSE consumer in order to update a few tables like this
@app.task(ignore_result=True)
@worker_ready.connect
def xx_sse_nodes_uptime_info_consumer(sender, **kwargs):
   update_tables...

By some reason, other tasks are not triggered when we have a .delay calling other tasks. If I remove the task above, other tasks will work normally.
Also, when CELERY_TASK_ALWAYS_EAGER=True and CELERY_TASK_EAGER_PROPAGATES=True everything runs fine.
Since the SSE consumer uses stream=True the xx_sse_nodes_uptime_info_consumer never ends. I am not sure why this blocks others tasks tho as there are enough threads.

A: Solved creating a function for that
@worker_ready.connect
def at_worker_ready(sender, **k):
    with sender.app.connection() as conn:
        sender.app.send_task('nodeinfo.tasks.xx_sse_nodes_uptime_info_consumer', connection=conn)


text:
Q: Apache Beam/Dataflow doesn't discard late data from Pub/Sub I'm having a hard time understand how Beam's windowing is supposed to work related to discarding late data.
Here is my pipeline:
pipeline
| ReadFromPubSub()
| WindowInto(
    FixedWindow(60),
    trigger=AfterWatermark(
      early=AfterCount(1000),
      late=AfterProcessingTime(60),
    ),
    accumulation_mode=AccumulationMode.DISCARDING,
    allowed_lateness=10*60,
  )
| GroupByKey()
| SomeTransform()
| Map(print)

How I understand this is that data elements from Pub/Sub are assigned with the timestamp at which  they're published to a subscription.
When I start my pipeline to consume data from Pub/Sub, which also included old data, I expected that only data from the last 10 minutes (as set at the allowed_lateness param of WindowInto) are printed out. But the result is that all of the data from the subscription are printed out.
Am I missing something or do i understand Windowing wrong?
I use Python and Beam 2.42.0

A: In the above pipeline, there is no late data.
Data is only late when compared to the watermark. To calculate the watermark, Beam uses the timestamp of the messages being read. In your case, the timestamp of the messages when they are generated in the ReadFromPubsub transform.
Pubsub messages have attributes in addition to the payload. Beam uses these attributes to read and set the timestamp of each message. If you don't specify any, Beam uses the publish time to set that timestamp. So in your case you are actually working in processing time (timestamp set to current processing time), and therefore it is impossible to have late data. The watermark will always be very close to the current timestamp of the messages being processed.
See this question in SO for more details on how the timestamp attribute is used with Pubsub (for Python, check the parameter timestamp_attribute in ReadFromPubsub)
If there is no timestamp attribute in the messages you are reading, but they contain a field (in the payload) with the timestamp, you can use it to generate a timestamped value (parsing the payload and then using a DoFn that emits TimestampedValue, or the WithTimestamps transform).


text:
Q: Making template type LinkedList i have recently started studying linkedlist in c++. Although i am finding it pretty confusing but i made some functions to insert and delete and element from the linkedlist.
The program worked fine with int data type. But i want to create a linkedlist of template type and i cannot understand how to do it.
I have tried to create a function to insert the node at the first position of link list but it gives me errors like access specifier needed before node etc ...
#include <iostream>
#include<conio.h>
using namespace std;

template<class T>
class node
{
    public:
    T data;
    node *next;
};

template<class T>
class linklist
{
    public:
    node <int>*head;

    linklist()
    {
        head = NULL;
    }

    bool Is_Empty(node <T>*ptr)
    {
        if(ptr==NULL)
        {
           return true;
        }
        return false;
    }

    void insert_at_head(T num)
    {
        if(Is_Empty(head))
        {
            node <T>*temp = new node; // error is on this line. it says access specifier needed before node.
            temp->data = num;
            head = temp;
            temp->next = NULL;
        }

        else
        {
            node *temp = new node;
            temp->data = num;
            head = temp;
            temp->next = head->next;
        }

    }

    void show_list(node <T>*ptr)
    {
        cout<<"\nElements in the List are : ";
        while(ptr!=NULL)
        {
            cout<<ptr->data<<" ";
            ptr = ptr->next;
        }
    }
};

int main()
{
    cout << "Hello world!" << endl;
    getch()
}


text:
Q: Windows 8 Restore Problems I created a Windows 8 system image backup on a separate drive before I installed Linux, and during the Linux installation process I accidentally wiped out Windows.  I now want to restore my Windows 8 backup that I have on the separate drive.  I created a repair USB stick and I followed the directions according to this article.  After selecting the image on the hard drive, I get this error: "To restore this computer, Windows needs to format the hard drive."  I don't know what this means!  The drive partitions are different now then they were when I backup up, so I don't know if that matters.  I re-installed Windows and I can restore my files from this backup, but I don't think this covers the registry, etc.  I want a full restore.  Does anyone know how to fix this problem, or how to restore in a different way?  Thanks!

A: It is a good thing you did a backup first. You need not worry what you want is the format first. Just choose the option to reformat and continue from there. If you want to try out Linux I suggest you do a little studying first about its basics so you don't run into this problem again. It is very confusing to a new user. I suggest trying out Ubuntu it is a popular distro for beginners. Installation information is here Some useful info here. Good luck. :)


text:
Q: ArcGIS 10.2 Model Builder If no selection is made, then do not append to empty feature class I'm creating a model in model builder that is very easy to construct and understand. However, I ran into a slight problem. The logic of the model is that it will take user selected features from a layer and append those selected features to an empty feature class with the same schema and field definitions. The problem here is that by default, all feature rows are returned in the Append tool if no selection is made. Is there any way to tell model builder to not append any features if there is no selection made? The final output in the empty feature classes should only be user selected features. I want to keep this automated, so I am open to a python script workaround if such a statement in python exists.

A: You can use the Get Count tool as a precondition to a tool. In the model below the buffer tool will only run if count is greater than zero and it's only greater than zero if the select by attribute tool actually selects anything.

A: Use the Get Count tool in Model Builder as a Pre-Condition.  If nothing is selected the tool won't continue as the condition (something selected) isn't met.
From the Get Count Help page:

In ModelBuilder, Get Count is often used to set up a precondition, as
  illustrated below. In this model, Get Count counts the number of
  records returned by the Select tool. If the count is zero, Buffer will
  not run due to the precondition


text:
Q: Funny symbols showing in a website Simple question I'm hoping, on Server A everything shows okay, but on Server B it shows as follows

Hello, how are you - Allo, comment vas-tu?  How much does it cost? -
  Combien �a coute? or Quel est le prix de...?

Before my client kills me - How can I fix that? :)

A: Most likely your file is encoded in some encoding (say Latin-1) and your web server is configured to announce a different encoding in the HTTP header (say UTF-8), so the browser is misinterpreting the page's encoding. Make sure those two match, i.e. either change your server to send the correct HTTP header or encode your files in the matching encoding. Since you have given no detail of either I can't tell you how to do that in detail.

A: You need to use these codes instead. I this case I think you need the latin small letter c with cedilla written as
ç

A: Try using html codes you fint them here : http://www.usewisdom.com/computer/internet/html/chars.html
Or you could do it with a function like this
$text = "This a text with weird characters @#$%^&*";
echo htmlentities($text);
or if the site is in UTF-8 charset
echo utf_decode($text);


text:
Q: app to mail form data to my inbox doesn't work correctly on Firebase I think I'm missing something very simple here. I have a simple, one page node.js app that uses nodemailer to email any form data to my inbox.
My index.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'myemail@gmail.com',
        pass: 'mypassword'
    }
});

app.use(express.static('public')); //public folder with my html files
app.get('', function (req, res) {
    res.sendFile(__dirname + "/");
})

app.post('/', function (req, res) {
    response = {
        name: req.body.name,
        email: req.body.email,
        message: req.body.message
    };
    var mailClient = {
        from: 'myemail@gmail.com',
        to: 'myemail@gmail.com',
        subject: `Message from ${response.name}`,
        text: 'MyMessage'
    };
    transporter.sendMail(mailClient, function (error, info) {
        if (error) {
            console.log(error); //not happening
        } else {
            res.redirect("/success.html"); //also not happening
        }
    });
})

var server = app.listen(80, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("App listening at http://%s:%s", host, port)
})

When I run this on my local machine using npm start in the root directory, the app runs perfectly fine on localhost. Nodemailer works properly; when I submit, my form data gets emailed to myself and I get redirected to my success page.
However, when I deploy this to Firebase, it seems the nodemailer part doesn't work. The page loads in with my static files, but when I try to submit anything via the form, the page simply refreshes (like when you have a submit button with bare html), instead of redirecting me to my success page and emailing data.
Is there something I need to change in my code to make it work with firebase?
Edit - no logs:

A: Google requires a paid account in order to make use of "Outbound Networking". The Free Tier does not allow you to make outbound calls. This would include sending mail to a remote mail server (like sending an email to a Yahoo, Gmail, or Outlook account).
See their pricing page for more info.
Look for "Outbound Networking".
If you'd like to leverage Gmail's API, you should still be able to use nodemailer with firebase functions and achieve what you're looking for and remain on the Free Tier. A fully working example is already available in the firebase-samples repository! I would like to highlight what the linked tutorial mentions, which is that Gmail does have an email sending quota that you should be aware of.

A: I tried to figure out problem in your code but didn't found any, I also have functionality to send email with verification code for authenticate/verify email id. For that I create one gmail id and gave that id/password for sending mail. Mails are sent from that gmail id with node.js when ever user register is email id we send email with veirfication code. My code is as under:
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
var bodyParser = require('body-parser');
var users = require('./users/route');

const app = express();
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = 'myapp@gmail.com';
const gmailPassword = 'password';
const gcm = require('node-gcm');
const mailTransport = nodemailer.createTransport(
        `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://myapp.firebaseio.com"
});
//admin.initializeApp(functions.config().firebase);

// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header.
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this:
// `Authorization: Bearer <Firebase ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.
const authenticate = (req, res, next) => {
    if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer')) {
        res.status(403).send('Unauthorized');
        return;
    }
    const idToken = req.headers.authorization.split('Bearer ')[1];
    admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
        req.user = decodedIdToken;
        next();
    }).catch(error => {
        res.status(403).send('Unauthorized');
    });
};

app.get("/token", (req, res) => {

    res.status(200).send(admin.auth().applicationDefault());
    admin.auth().createCustomToken(req.query.uid)
            .then(function (customToken) {
                res.status(200).send(customToken);
            })
            .catch(function (error) {
                console.log("Error creating custom token:", error);
            });

});

// GET /api/verifyEmail?code="1234"
app.get('/verifyEmail', (req, res) => {

    // Get the one-time code from the query parameter.
    var verificationCode = req.query.code;
    var displayName = req.query.displayName;
    var email = req.query.email; //If GET request
    const mailOptions = {
        from: `Linkuni <noreply@firebase.com>`,
        to: email
    };

    // The user subscribed to the newsletter.
    mailOptions.subject = `Welcome to Linkuni`;
    mailOptions.text = `Hi ${displayName || ''}\n\n Welcome to Linkuni. We hope you will enjoy our service. Please enter this code:${verificationCode} into the app.\n\nThank you,\nLinkuni Team`;

    return mailTransport.sendMail(mailOptions).then(() => {
        console.log('Verification email sent to:', email);
    });
});

Hope this helps!! :)


text:
Q: Probability from log-normal distribution Stock price relative change can be modeled with random variable $R-1$ where random variable $R$ follows log-normal distribution. Meaning $\log(R)$ (log as natural logarithm follows normal distribution. Random variables $\log(R)$ estimated values for mean and standard deviation are $\mu=5.1$ and $\sigma = 3$
What is probability for relative stock price dropping more than 4% from it's current value within one day.

A: Our relative stock price change is modeled with random variable $R-1$, we can set our random variable to $x=(R-1)$.
We want to find out probability for: $$P(X \le -0.04)$$
Since we want drop that is larger than $-0.04$. Larger drop means larger negative percentile which is $P(x\le -0.04)$ (same as smaller).
$$P((R-1) \le -0.04)$$
$$P(R\le -0.04 + 1)$$
$$P(R \le 0.96)|\log()$$
$$P(\log(R)\le \log(0.96))$$
log is natural logirthm in this case.
We know that $log(R)$ follows normal distribution so by normalizing value of $log(0.96)$ we can get our probability
$$Z=\frac{x-\mu}{\sigma}$$
plugging in values gives us:
$$Z=\frac{\log(0.96-5.1)}{3}≈-1.71360$$
Z is standardized normal. By looking at value for z from standardized normal table.
$$P(X\le -0.04)≈\phi(-1.71)$$
$$P(X\le -0.04)≈0.0436≈4.36\%$$

A: $$\ln(x)\sim N(5.1,9)$$
As given by WolframAlpha, the CDF is
$$F_X(x)=\Phi(\frac{\ln(x)-5.1}{3})$$
$\Phi$ is the CDF of the Standard Normal.
Now one plugs in values to this formula.  Your $x$-value is 4, so plugging this in will give you your answer.  Remember to subtract this value from $1$ as you are considering when the price is dropping more than $4$% and the CDF gives you less than $4$%.
I am only considering the absolute value of $x$ (even thought you said it was a drop), because $\ln(x)$ does not take on negative values.


text:
Q: Firebase push() in iOS Is there any equivalent of Firebase.push() method for iOS API which is available in API for Javascript or Java ?
I couldn't find it in API reference for iOS.
What I need is to push data to the new child location based on timestamp (I prefer server not client timestamp) and return that reference in the block.

A: Yes!  We renamed it childByAutoId to be more consistent with iOS naming conventions, but it behaves the same as ref.push().  If you want to set data (equivalent of ref.push(data)), you can do [[ref childByAutoId] setValue:data]


text:
Q: GET method with list of paramethers as body or POST method? I need to create an endpoint which will provide a list of objects, I need to pass as request body list of ID's of objects I want to retrieve. As far I know this should be done by GET method since it's only retrieving the object and not modifying them, but when I want to call it from client side using RestTemplate, it does not have any method for GET to pass body. However, this is achievable with POST method. Should I use POST instead of GET or is there another solution?
EDIT: for everyone with the simmilar problem, this thread helps a lot:
HTTP GET with request body

A: If you want to stick to GET which is semantically more correct you need to pass the list of IDs as a Request parameter instead of body because GET doesn't define a body.
Using POST in which case you can pass the list in the body, is generally fine also though some sticklers will state that it isn't semantically correct.
Note that POST is sometimes preferred depending how complex or long the query data is.

A: RFC 7231

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

That eliminates GET as an option; HTTP simply doesn't support what you want to do.

i need to pass as request body list of ID's of objects i want to retrieve.

GraphQL is gaining some traction as a querying language for web apis.  It's the same sort of problem; a complicated query.  Github, for instance, is implementing a graphQL endpoint that supports the POST method.
This does produce an api that is more RPC than REST.  So it goes.
The point, as this applies to your problem, is that query via POST as a pattern does exist as a pattern.

is there other solution?

There are some alternative designs that might serve you better
How does a web page load multiple images?  One at a time.  An advantage to this approach is caching - the web page can re-use the representation of the images it has seen before.  This affords some of the improved scaling promised by the REST architectural constraints.
Compare this with asking for a representation of a list of objects, where the representation necessarily changes each time you change the items in the list, or each time any individual item changes its representation.
You can use the ids themselves as part of the URI, which is to say that if what you want is a representation of a list of objects, then perhaps the list of objects is its own concept (resource) with its own identifier.
This approach might manifest in one of two ways.  You might might keep the list of ids explicit (making the concept itself implicit), in other words, by enumerating the ids in the URI itself.
Alternatively, you might try making the concept explicit in your design - figure out why the client is asking for that particular combination of ids, and create a resource that represents that concept.  For example: if the client is picking the ids because they have some property in common (all open tickets), then the concept is a collection filtering on that property -- so you would create an open ticket resource.
Similarly, if the list of ids comes about because the client is paging through results, then you can make the paging explicit (this approach is common with feeds, see AtomSyndication).
In short, you may be having trouble finding a good answer for REST because you have the wrong problem.


text:
Q: Objective C vs Xamarin iOS C# obfuscation Is it really required to obfuscate Xamarin iOS code ?
What is difference between code written in Objective C vs C# Xamarin obfuscation?
I have gone through lot of post but answer is not clear.
Many thanks!

A:
Is it really required to obfuscate xamarin iOS code ?

The answer I provided to MonoTouch: How to protect my application should cover everything. If not then you'll need to be more specific in your question.

What is difference between code written in Obective C vs C# Xamarin obfuscation?

That's not a valid comparison, i.e. ObjC does not compare with obfuscation and Xamarin does not offer (by itself) obfuscation.
However if you compare both ObjC compiler and Xamarin's AOT compiler code then you'll find that both produce native ARM[64] binaries.
In most cases developers use obfuscations tools (on .NET) because they ship the IL (intermediate code) with their application. That's required for a JIT (just in time compiler to work) but not for a AOT (ahead of time compiler) which Xamarin.iOS uses.


text:
Q: Don't show hidden files in a directory listview I have code that generates a listview directory of my computer. When I open the C directory it shows $RECYCLE.Bin. Is there anyway to have it where it doesn't show these files?
foreach (string dir in folders)
{
    dirData[0] = dir.ToString();
    dirData[1] = dir.Length.ToString();
    dirData[2] = File.GetLastAccessTime(dir).ToString();
    ListViewItem lv = new ListViewItem(dirData, imageList1.Images.Count - 1);
    lv.Tag = dir;

    imageList1.Images.Add(BlackFox.Win32.Icons.IconFromExtensionShell(".*", BlackFox.Win32.Icons.SystemIconSize.Small).ToBitmap());

    listView1.SmallImageList = imageList1;
    listView1.Items.Add(lv);
}

A: var dirs = Directory.GetDirectories(@"C:\")
             .Select(d => new { Attr = new DirectoryInfo(d).Attributes, Dir = d })
             .Where(x => !x.Attr.HasFlag(FileAttributes.System))
             .Where(x => !x.Attr.HasFlag(FileAttributes.Hidden))
             .Select(x => x.Dir)
             .ToList();

This will not only ignore System+Hidden directories like C:\$Recycle.Bin but also C:\$AVG8.VAULT$ which is not a System directory and used by virus scanner.

A: Run an iterate over the listview items and remove items which they extension is .bin.
you can find .bin with this piece of code (pseudonymous):
for(int i=0;i<items_count;i++)
{
  if(listview1.items[i].Substring(listview1.items[i].length-3,listview1.items[i].length)=="bin")
   listview1.items.remove(i);
}

another pseudonymous :
if you want to generalize this , you should use file attribute class like this for a list view item :
string filePath = listview1.items[i];

// get file attributes
System.IO.FileAttributes fileAttributes = System.IO.File.GetAttributes(filePath);

Now you should check if fileAttributes is hidden , remove the correspond item.
Note : Next Time , Please send some of your code lines , it is better for problem salvation.

A: Something like this should work
var folders = Directory.GetDirectories(@"C:\")
.Where(d => !new DirectoryInfo(d).Attributes.HasFlag(FileAttributes.System | FileAttributes.Hidden));

foreach (string dir in folders)
{
   .....

Let me expand on the answer as some people may find it difficult to understand, This will ignore SystemHidden directrories.
ie:
"C:\\$Recycle.Bin"
"C:\\Documents and Settings"
"C:\\System Volume Information"
If you want to ignore all hidden directories you can simply omit the FileAttributes.System attribute from the linq statement but this would result in losing directories like ProgramData  in your ListView which I'm not sure you want.


text:
Q: How to load data from another table/model Having just started with Cake, I'm now very frustrated having already spent several hours reading examples etc What I want to do seems so simple, but I can't make enough sense of the documentation to find out how to do this. It's very simple:
I have 2 tables:

*

*items

*categories (eg books, cd)

New items will be created constantly, each has a category.
All I want to do is create a dropdown filter in the items list view. But to do this I need to load the list of categories.
So the basic problem is, how do I access the categories table from the items table?

A: Finally a solution.
In the items controller:
$this->loadModel('Categories');

$categories = $this->Categories->find()->all();

Or to remove all the cake crud from the returned object:
 $categories = $this->Categories->find("list", array("fields"=>array("Categories.title")))->all();


text:
Q: Sum of ideals in the polynomial ring
Could someone explain to me how to find a sum of ideals where $I=(x+y)$ and $J=(x)$? The answer to this is $I+J=(x,y)$ and we work in the polynomial ring $k[x,y]/(xy)$.

I know that the definition of the sum of ideals is $I+J=\{i+j\mid i\in I,j\in J\}$.
I know that for the ring $\mathbb{Z}$ the sum of ideals is the greatest common divisor of them but how does it work for polynomial rings?

A: HINT:
Show the two inclusions $I+J\subseteq(x,y)$ and $(x,y)\subseteq I+J$ separately.
The first one should be obvious.
For the second one, all boils down to show that $y$ is in $I+J$, i.e. that $y$ can be recovered from $x$ and $x+y$ via sums and products.

A: I'd just like to add to Andrea's excellent answer:
If $R$ is a PID (that is, principal ideal domain), and if $x,y\in R$, then the sum of the ideals they generate, $(x)+(y)$, is an ideal in $R$. Of course, this ideal is principal so there exists $z\in R$ such that $(z)=(x)+(y)$. You might think of $z$ as the "Greatest Common Divisor" (GCD) of $x$ and $y$ in $R$. (If $R=\mathbb{Z}$, then this agrees with the usual definition of "GCD" up to sign.)
Unfortunately, if $R$ is not a PID, then this construction fails. For example, in the polynomial ring $k[x,y]$ ($k$ is a field), the sum of the ideals $(x)$ and $(y)$ is the ideal $(x,y)$ which isn't principal! You might say that $x$ and $y$ don't have a GCD in $k[x,y]$. So that's why it's not as easy to add two ideals in $k[x,y]$ as it is to add ideals in $\mathbb{Z}$!
The good news is that a polynomial ring $k[x]$ over a field $k$ is a PID so you can speak of the notion of GCD (again, up to multiplication by a unit, i.e., an element of $k$).
I'll sign off by noting that there are general notions such as that of "Bezout domain" (my apologies to Bezout; I don't know how to add an accent on the "e") and "GCD domain" which generalize these ideas.
I hope this helps!


text:
Q: Can I assign same value to multiple variables in C? I tried like
int a=b=3;

but the compiler says 'b' undeclared.
Please help, thanks.

A: You can use , to declare the variables in a single line first
int a, b, c, ... , last;

and then you can assign to them all at once
a = b = c = ... = last = 3;

note that
int a = b = 3;

which is equivalent to
int a = (b = 3);

will declare a and initialize it with the result b = 3, which in turn will assign 3 to b, which is UNDECLARED

A: No you can't do this because the compiler interprets that the value 3 to bshould be assigned and b is undeclared
You can do
int b;

int a=b=3;


text:
Q: Contraposition's value is rigorous logical reasoning I don't remember where but I read in the past that contrapositive proofs should be avoided when possible. fast forward and I became almost obsessed with why contraposition is still used when it has so many flaws (Hempel's raven for example).
For example, while there are some awfully simple proofs for the law of contraposition, proving both ways of the equivalence ultimately boils down to double negation elimination, which, by itself, doesn't feel very convincing. For example, the law of non-contradiction feels perfectly fine but the law of excluded middle is frowned upon by intuitionistic (aka constructive) logic (along with double negation elimination since both could be derived from each other in classical logic. please correct me if I'm wrong). So:

*

*Is there any proof, in classical logic, for the law of contraposition that proves, using pure logical constructs, both sides of the equivalence without using double negation elimination or the law of excluded middle? I'm not strictly a fan of intuitionistic logic but it will be reassuring if there is anything like an intuition-friendly proof in classical logic.

*Are contrapositive proofs really avoided in the real world?

*Any special cases (like statements of form X) that are perfectly fine to prove using contraposition without invoking logical leaps? like the case mentioned here.

A: An answer to your question can be given in intuitionistic logic. If you are not a fan of intuitionistic logic and don't know much about it; it's enough to know that the law of excluded middle ($\mathsf{LEM}$) can not be shown in said logic.
What you can however show in intuitionistic logic is that $\mathsf{LEM}$ and and Contraposition ($\mathsf{CP}$) are equivalent and in this precise sense, $\mathsf{CP}$ is "just as bad" a $\mathsf{LEM}$.

Let me expand on my answer, more specifically addressing the bullet-points.

*

*Yes there is a proof of the equivalence between $\mathsf{LEM}$ and $\mathsf{CP}$ which, upon inspection, does not use double negation elimination ($\mathsf{DNE}$). Actually, from the start, we can slightly change our classical proof system and completely remove the possibility to use $\mathsf{DNE}$, which guarantees that we don't use it by accident. There is even a name for this variation of classical logic and you might have guessed it by now: it's intuitionistic logic.

*Yes. There are good reasons for people to avoid proofs which use $\mathsf{LEM}$ and since it is equivalent to $\mathsf{CP}$, this also means we are trying to avoide $\mathsf{CP}$.

*Yes there are instances where $(\neg B \rightarrow \neg A) \rightarrow (A \rightarrow B)$ can be proven and therefore be used, just as there are instances of a statement that has the form $X \lor \neg X$ which can be proven and therefore be used. For example, if you have the finite set $B = \{0, 1\}$ you can (without using $\mathsf{LEM}$ or the likes) show that $\forall x, y \in B : ~ x = y \lor \neg (x = y)$.

Here are proofs for $\mathsf{CP} \Rightarrow \mathsf{DNE} \Rightarrow \mathsf{LEM}$ and lastly $\mathsf{LEM} \Rightarrow \mathsf{CP}$ in intuitionistic logic. Rember that in intuitionistic logic (just like in classical logic) there are the always false proposition $\bot$ and the always true proposition $\top$ and negation is defined by $\neg P := P \rightarrow \bot$.

*

*Assume $\mathsf{CP}$. This means for any propositions $A, B$ we have $(\neg B \rightarrow \neg A) \rightarrow (A \rightarrow B)$.
So in particular for $A = \neg \neg X$ and $B = X$ we get
$$
  (\neg X \rightarrow \neg \neg \neg X) \rightarrow (\neg \neg X \rightarrow X)
$$
So $\neg \neg X \rightarrow X$ follows from $\neg X \rightarrow \neg \neg \neg X$ where this latter statement is true since by definition it is the same as $(\neg X) \rightarrow \neg (\neg X) \rightarrow \bot$ which is more obviously true.

*For the second implication we now assume $\mathsf{DNE}$. This means for every $A$ we have $\neg \neg A \rightarrow A$, which means in order to show $X \lor \neg X$ it suffices to show $\neg \neg (X \lor \neg X)$.
So assume $H_1 : \neg (X \lor \neg X)$ and try to get a contradiction to it. With $H_1$ we can show $H_2 : \neg X$ (since assume we had $X$, then we also have $X \lor \neg X$; in contradiction to $H_1$). Now that we have $H_2$ this too implies $X \lor \neg X$ and we therefore get the desired contradiction to $H_1$.

*Assume $\mathsf{LEM}$, meaning for every $X$ we have $X \lor \neg X$. We want to show $(\neg B \rightarrow \neg A) \rightarrow (A \rightarrow B)$, so we assume $H_1 : (\neg B \rightarrow \neg A)$ and $H_2 : A$ and try to show $B$. Because of $\mathsf{LEM}$ we either have $B$ or $\neg B$. In the first case it is trivial to show $B$. In the second case we have $\neg B$ which, by using $H_1$ gets us $\neg A$ which by $H_2$ gets us $\bot$. So by explosion we can again conclude $B$.

By request fom the comments, here is also the implication $\mathsf{LEM} \Rightarrow \mathsf{DNE}$.
We are trying to show $\neg \neg X \to X$, so assume $H : \neg \neg X$ and try to get $X$. By $\mathsf{LEM}$ we know that $X \lor \neg X$ so we get two cases:

*

*If $X$ then we are done.

*If $\neg X$ then we get $\bot$ because of $H$ and therefore $X$ by explosion.


text:
Q: Figure out the PID of exact node.js application Here is an output of my ps aux:
ps aux | grep "node"
root      2501  0.0  3.4 720400 68512 ?        Sl   16:09   0:03 node /etc/skbx/host/skbx.js 8081 tula13 8082 8084 8085 10.8.0.6
root     20586  0.0  0.1  17396  2664 pts/16   S+   21:29   0:00 grep --color=auto node

Disregard the second one, we have a node process. I need to figure out in bash the PID of the node process that is executing skbx.js exactly.
How could I do this? Thanks.

A: In general, if you are looking for the PID of a known command line, pgrep is preferable to ps | grep because you don't need to filter the output to extract the PID. You can use pgrep with -f to match the full command line:
pgrep -f 'node /etc/skbx/host/skbx.js'

You can also target processes by parent process ID and controlling terminal, among other criteria.

If you don't have pgrep installed, you can use grep in a pipeline. In the following example, we use a character class in the pattern supplied to grep to prevent grep itself from appearing in the output. This is less typing than piping the output to grep -v grep or similar:
ps aux | grep '[n]ode /etc/skbx/host/skbx.js' | awk '{print $2}'

The grep command listed in the ps output will include square bracket literals which are not matched in the resulting pattern used by grep.


text:
Q: Regular Expression for URL The regular expression posted below is used to pick up URLs, including ones in the format such as example.com. However, I want it only to pick up on URLs that have a www. or http, https, etc. in the front. In other words, it should pick up www.example.com. It should not pick up example.com.
((((ht|f)tp(s?))\://)?((www.|[a-zA-Z])([a-zA-Z0-9\-]+\.)([a-zA-Z]{2,8}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*)

A: Hmmm try
(((((ht|f)tp(s?))\://)|(www\.))((|[a-zA-Z])([a-zA-Z0-9-]+.)([a-zA-Z]{2,8}))(\:[0-9]+)*(/($|[a-zA-Z0-9.\,\;\?\'\+&%\$#\=~_-]+))*)
EDIT:
Yeah, I didn't really test that one. Ok, I didn't test this one either but I looked at it REALLY carefully ;)
(((((ht|f)tp(s?))\://)|(www\.))(([a-zA-Z0-9-]+.)?([a-zA-Z0-9]+\.)([a-zA-Z]{2,8}))(\:[0-9]+)*(/($|[a-zA-Z0-9.\,\;\?\'\+&%\$#\=~_-]+))*)
You should look into a good regex tester. I usually use Expresso but there are many others out there.

A: Validate that the URI is well-formed with a regexp--use the one out of RFC 3986.    Validate that it is plausible with code.  Trying to combine the check for well-formed and plausible into one regexp is too difficult to get right.  See: Need a regex to validating a Url...

A: I modified your expression:
((((ht|f)tp(s?))\://)?((www\.)([a-zA-Z0-9-]+\.)([a-zA-Z]{2,8}))(\:[0-9]+)*(/($|[a-zA-Z0-9.\,\;\?\'\+&%\$#\=~_-]+))*)

A pretty good website to check your expressions here: http://gskinner.com/RegExr/

A: Here you go:
\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»""''\s]))

It's the revised Liberal URL Regex from Daring Fireball.


text:
Q: Is there a way to only show the first record in a Crystal Report that does not meet a specified condition? Say I have data formatted as follows in a Crystal Report:
Job: 1

Asm      Opr      LbrQty
0        10       0.0
0        10       60.0
0        10       60.0
0        20       65.0
0        30       0.0
0        30       20.0
0        30       40.0

Job: 2

Asm      Opr      LbrQty
0        10       60.0
0        10       60.0
0        10       75.0
0        20       0.0
0        20       165.0
0        30       0.0
0        30       20.0
0        30       40.0
0        40       60.0
1        10       60.0
1        10       60.0
1        10       75.0
1        20       0.0
1        20       165.0
1        30       0.0
1        30       20.0
1        40       0.0
1        40       60.0

I only want the report to show the first Opr within an Asm where LbrQty is NOT zero, as below:
Job: 1

Asm      Opr      LbrQty
0        10       60.0
0        20       65.0
0        30       20.0

Job: 2

Asm      Opr      LbrQty
0        10       60.0
0        20       165.0
0        30       20.0
0        40       60.0
1        10       60.0
1        20       165.0
1        30       20.0
1        40       60.0

I've attempted to use the following as my Supression Formula, which works for the most part, but still occasionally displays multiple records with the same Opr:
(
    Previous ({OprSeq}) = ({OprSeq}) and
    Previous ({JobNum}) = ({JobNum}) and
    Previous ({LaborQty}) <> 0
) or

(
    ({LaborQty}) = 0
)

How can I change my formula to give me the behavior I require?

A: Try below way:
Create a running total with following criteria:

*

*In field to summairze take lbrqty and take count as summary option

*In  evalute use option formula and write below code:
{lbrqty}>0

*In Reset use option On change of field opr
Now use this running total to supress.. Now in supress of the section write below code:
if {#RTotal1}=1
then false
else true


text:
Q: Which dynamic container type to use? I'm writing code for a router (aka gateway), and as I'm receiving and sending packets I need to use a type of container that can support the logic of a router. When receiving a packet I want to place it in the end of the dynamic container (here from and on known as DC). When taking the packet out of the DC for processing I want to take it from the front of the DC.
Any suggestion on which one to use?
I've heard that a vector would be a good idea but I'm not quite sure if they are dynamic..
EDIT: The type of element that it should contain is a raw packet of type "unsigned char *". How would I write the code for the DC to contain such a type?

A: std::deque<unsigned char *> is the obvious choice here, since it supports efficient FIFO semantics (use push_back and pop_front, or push_front and pop_back, the performance should be the same).
In my experience the std::queue (which is a container adapter normally built over std::deque) is not worth the effort, it only restricts the interface without adding anything useful.

A: For a router, you probably should use a fixed size custom container (probably based around std::array or a C array). You can then introduce some logic to allow it to be used as a circular buffer. The fixed size is extremely important because you need to deal with the scenario where packets are coming in faster than you can send them off. When you reach your size limit, you then flow off.
With dynamically re-sizable containers, your may end up running out of memory or introducing unacceptable amounts of latency into the system.

A: You can use std::queue. You insert elements at the end using push() and remove elements from the front using pop(). front() returns the front element.
To store unsigned char* elements, you'd declare a queue like this:
std::queue<unsigned char*> packetQueue;


text:
Q: Object cloning with cyclic reference chain I'm running some operations on a graph in memory, which modify the graph itself. I need to repeat these operations some number of times, and subsequent repetitions must work on a fresh copy of the graph. Since the graph is generated by parsing a file, I don't really want to spend time re-parsing the file for every repetition, so I've gone down the route of cloning the original graph.
My node, edge and graph types are all implementing ICloneable, but I have an issue with a cyclic reference chain.
Node stores a list of directed Edges coming from it. Edge stores the weight and the Node it points to. When two nodes share a bi-directional edge, I get a StackOverflowException when I attempt to clone either node, since cloning the list of edges of either node invariably means cloning the other node.
What would be the best approach to resolve this cyclic reference for the purposes of cloning?


text:
Q: How to make 2 tensors the same length by mean | median imputation of the shortest tensor? I'm trying to subclass a the base Keras layer to create a layer that will merge the rank 1 output of 2 layers of a skip connection by outputting the Dot product of 2 tensors. The 2 incoming tensors are created by Dense layers parsed by a Neural Architecture Search algorithm that randomly selects the number of Dense units and hence the length of the 2 tensors. These of course will usually not be of the same length. I am trying an experiment to see if casting them to the same length by means of appending the shorter tensor with a mathematically meaningful imputation: [e.g. mean | median | hypotenuse | cos | ... etc] then merging them by means of the dot product will outperform Add or Concatenate merging strategies. To make them the same length:
I try the overall strategy:

*

*Find the shorter tensor.

*Pass it to tf.reduce_mean() (aliasing the resulting mean as "rm" for the sake of discussion).

*Create a list of [rm for rm in range(['difference in length of the longer tensor and the shorter tensor']). Cast as a tensor if necessary.

*[pad | concatenate] the shorter tensor with the result of the operation above to make it equal in length.

Here is where I am running into a dead wall:
Since the tf operation reduce_mean is returning a future with its shape set as None (not assumed to be a scalar of 1), they are in a state of having a shape of '(None,)', which the tf.keras.layers.Dot layer refuses to ingest and throws a ValueError, as it does not see them as being the same length, though they always will be:
KerasTensor(type_spec=TensorSpec(shape=(None,), dtype=tf.float32, name=None), name='tf.math.reduce_mean/Mean:0', description="created by layer 'tf.math.reduce_mean'")
ValueError: A Concatenate layer should be called on a list of at least 1 input. Received: input_shape=[[(None,), (None,)], [(None, 3)]]
My code (in the package/module):
import tensorflow as tf
import numpy as np

class Linear1dDot(tf.keras.layers.Layer):
    def __init__(self, input_dim=None,):
        super(Linear1dDot, self).__init__()

    def __call__(self, inputs):
        max_len = tf.reduce_max(tf.Variable(
            [inp.shape[1] for inp in inputs]))
        print(f"max_len:{max_len}")
        for i in range(len(inputs)):
            inp = inputs[i]
            print(inp.shape)
            inp_lenght = inp.shape[1]
            if inp_lenght < max_len:
                print(f"{inp_lenght} < {max_len}")
                # pad_with = inp.reduce_mean()
                pad_with = tf.reduce_mean(inp, axis=1)
                print(pad_with)
                padding = [pad_with for _ in range(max_len - inp_lenght)]
                inputs[i] = tf.keras.layers.concatenate([padding, [inp]])
                # inputs[i] = tf.reshape(
                # tf.pad(inp, padding, mode="constant"), (None, max_len))

        print(inputs)

        return tf.keras.layers.Dot(axes=1)(inputs)

...
# Alternatively substituting the last few lines with:

                pad_with = tf.reduce_mean(inp, axis=1, keepdims=True)
                print(pad_with)
                padding = tf.keras.layers.concatenate(
                    [pad_with for _ in range(max_len - inp_lenght)])
                inputs[i] = tf.keras.layers.concatenate([padding, [inp]])
                # inputs[i] = tf.reshape(
                # tf.pad(inp, padding, mode="constant"), (None, max_len))

        print(inputs)

        return tf.keras.layers.Dot(axes=1)(inputs)

... and countless other permutations of attempts ...
Does anyone know a workaround or have any advice? (other than 'Don't try to do this.')?
In the parent folder of this module's package ...
Test to simulate a skip connection merging into the current layer:
from linearoneddot.linear_one_d_dot import Linear1dDot
x = tf.constant([1, 2, 3, 4, 5])
y = tf.constant([0, 9, 8])

inp1 = tf.keras.layers.Input(shape=3)
inp2 = tf.keras.layers.Input(shape=5)
xd = tf.keras.layers.Dense(3, "relu")(inp1)
yd = tf.keras.layers.Dense(5, 'elu')(inp2)
combined = Linear1dDot()([xd, yd])  # tf.keras.layers.Dot(axes=1)([xd, yd])

z = tf.keras.layers.Dense(2)(combined)
model = tf.keras.Model(inputs=[inp1, inp2], outputs=z)    # outputs=z)

print(model([x, y]))

print(model([np.random.random((3, 3)), np.random.random((3, 5))]))

Does anyone know a workaround that will be able to get the mean of the shorter rank 1 tensor as a scalar, which I can then append / pad to the shorter tensor to a set intended langth (same length as the longer tensor).

A: Try this, hope this will work, Try to padd the shortest input with 1, and then concat it with the input then take the dot product, then finally subtract the extra ones which were added in the dot product...
class Linear1dDot(tf.keras.layers.Layer):
    def __init__(self,**kwargs):
        super(Linear1dDot, self).__init__()

    def __call__(self, inputs):
        _input1 , _input2  = inputs
        _input1_shape = _input1.shape[1]
        _input2_shape = _input2.shape[1]

        difference = tf.math.abs(_input1_shape - _input2_shape)
        padded_input = tf.ones(shape=(1,difference))

        if _input1_shape > _input2_shape:
            padded_tensor = tf.concat([_input2 ,padded_input],axis=1)
            scaled_output =  tf.keras.layers.Dot(axes=1)([padded_tensor, _input1])
            scaled_output -= tf.reduce_sum(padded_input)
            return scaled_output
        else:
            padded_tensor = tf.concat([_input1 , padded_input],axis=1)
            scaled_output = tf.keras.layers.Dot(axes=1)([padded_tensor, _input2])
            scaled_output -= tf.reduce_sum(padded_input)
            return scaled_output

x = tf.constant([[1, 2, 3, 4, 5, 9]])
y = tf.constant([[0, 9, 8]])

inp1 = tf.keras.layers.Input(shape=3)
inp2 = tf.keras.layers.Input(shape=5)
xd = tf.keras.layers.Dense(5, "relu")(x)
yd = tf.keras.layers.Dense(3, 'elu')(y)
combined = Linear1dDot()([xd, yd])  # tf.keras.layers.Dot(axes=1)([xd, yd])

Output:
<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[4.4694786]], dtype=float32)>


text:
Q: Woocommerce REST API - Nginx - Error 404 Not Found I'm trying to use the Woocommerce (v 3.5.4) Rest Api on my VPS (debian 9, Nginx).
Everything works well in my local machine (windows 10, XAMPP).
wpbop/ is the folder (var/www/wpbop/) where the wordpress files are stored.
The next basic URL in a browser should send the endpoints of the API (no need of athentication for this first step) :
http://my-public-ip/wpbop/wp-json/wc/v3
Or a curl in command line
curl http://127.0.0.1/wpbop/wp-json/wc/v3
in both cases, i get error 404 Not Found.
I can acces to the blog / admin blog without any problems ( http://my-public-ip/wpbop )
My permalinks are set on "Postname" in wordpress admin panel, this is recommanded by many people in same case.

EDIT - SOLUTION :
Since my Wordpress installation is in a sub-domain,
try_files $uri $uri/ /index.php$is_args$args;
can't find index.php. Just change this line by :
try_files $uri $uri/ /wpbop/index.php$is_args$args;
and it works !

Perhaps problem is coming from my Nginx conf file ?
server {
  server_name localhost;
  listen 80;
  root /var/www;

    location /wpbop {

        index index.php;

        access_log /var/log/nginx/blog.access.log;
        error_log /var/log/nginx/blog.error.log;

        try_files $uri $uri/ /index.php$is_args$args;

            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_index index.php;
            fastcgi_pass 127.0.0.1:7000;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
        }
    }
}

I tried many things without any results, and I'm stuck for several days. Can someone help me ?
Thanks for reading me.

A: This case need a simple fix in the NGINX configuration file. This is related to the path of my wordpress installation.
Since my Wordpress installation is in a sub-domain,
try_files $uri $uri/ /index.php$is_args$args;

--> can't find index.php. Just change this line by :
try_files $uri $uri/ /wpbop/index.php$is_args$args;

A: when you get 404 code. try to access http://yoursite/?rest_route=/wp/v2/posts
Official documents https://developer.wordpress.org/rest-api/key-concepts

A: Move root /var/www/; by one level up (to server context). It is not being inherited.


text:
Q: how to Style a Spinner I am new to Android and was working with Spinner. I wanted to know that how can we style the Spinner items? Change the fontFamily of the items, textColor, textSize. Can anyone help? Thank you.

A: Make a custom layout
my_spinner_layout.xml
<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fontFamily="@font/clear_sans_regular"
    android:gravity="left"
    android:padding="5dip"
    android:textColor="@color/tealish"
    android:textSize="14sp" />

here you can customize according to your need , and then use it inside your adapter
Spinner yourSpinner = (Spinner) findViewById(R.id.your_spinner_id;
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
    R.layout.my_spinner_layout, list);   //use your custom layout like this
dataAdapter.setDropDownViewResource(R.layout.my_spinner_layout);
yourSpinner.setAdapter(dataAdapter);


text:
Q: React Bootstrap Link and params New to React,
I'm trying to pass an ID from one component to another into an API and then display the data from the API based on that particular ID,  using react Link bootstrap but I'm not getting any data. Any help will be appreciated.
I'm able to get all the data from the API in read.js but I can not get data of a particular object based on the ID after clicking View Link
I have tried using  const {id} = useParams() then pass the id to the API but nothing working
App.js
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import "./App.css";
import Read from "./components/read";
import User from "./components/User";
import Header from "./components/navBar";

import "bootstrap/dist/css/bootstrap.min.css";

function App() {
  return (
    <Router>

        <Switch>
          <Route exact path="/" component={Read} />

          <Route path="/Crud/:id" component={User} />
        </Switch>

    </Router>
  );
}

export default App;

read.js;
import React, { useState, useEffect } from "react";
import Table from "react-bootstrap/Table";
import { Button } from "react-bootstrap";
import axios from "axios";
import { Link } from "react-router-dom";

export default function Read() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios
      .get("https://6239f849bbe20c3f66cd0857.mockapi.io/Crud")
      .then((response) => {
        setUsers(response.data);
        console.log(users);
      });
  }, [users]);

  return (

            ID
            First Name
            Last Name
            View
            Edit
            Delete

          {users.map((response) => {
            return (

                {response.id}
                {response.firstName}
                {response.lastName}

                  <Link to={`/Crud/${response.id}`} variant="info">
                    view{" "}
                  </Link>

                  <Button variant="primary">edit </Button>

                  <Button variant="danger">delete </Button>

            );
          })}

  );
}

User.js;

import React, { useState, useEffect } from "react";
import Table from "react-bootstrap/Table";
import { Button } from "react-bootstrap";
import axios from "axios";
import { Link } from "react-router-dom";
import { useParams } from "react-router-dom";

export default function User() {
  const [user, setUser] = useState();

  useEffect(() => {
    const { id } = useParams();
    axios
      .get(`https://6239f849bbe20c3f66cd0857.mockapi.io/Crud/${id}`)
      .then((response) => {
        setUser(response.data);
      });
  }, []);

  return
{user &&
{user.name}
}
;
}


text:
Q: Horrendous Performance in a Simple Java2D App I've just finished my entry  for the 14th Ludum Dare 48-hours game making competition yesterday, and decided to do it in java using java2d for the graphics.
I'm not that familiar with the API and haven't done a lot of graphics programming, but my game is quite small (only a dozen or so very small moving object) so I assumed I could program it naively and still encounter no performance problems.
Needless to say, I was wrong.  The game performs alright most of the time but once there are a bit too many 'enemies' moving around on the screen or the resolution is cranked up too high it start getting visibly slower.
I've determined the performance bottleneck to be the screen drawing functions, when those are commented out the game is very fast.
Could someone give me a heads up on what I might be doing wrong here?  The (very short) source code is located here with most of it the Main class, with the usual suspects being the draw() function that is called in the inner game loop.
I already use a BufferStrategy to update the screen, so that shouldn't be the problem unless I'm doing it wrong.
Thanks in advance,
Ido.

A: A few observations, although I don't think any of them will help much.
The main thing is that you're painting off of the AWT thread.  Override paintComponent() and instead call repaint() on the object.  This can cause all sorts of problems otherwise.
You recreate colors every frame.  This may or may not be one of those things that you want to cache.  I don't think though that having a constant for your colors is likely to screw up GCing and will make things easier to keep straight when you want to reuse colors later.
You redraw the entire window every frame.  You just need to repaint the sections that changed.
You don't need to draw the background.  Set the background color and let the parent take care of everything.
As a design thing, the bodies should be in charge of drawing themselves.  Their owner should notify them that they need to be drawn rather than drawing them.
The bodies recreate their state every time.  Consider having them store it between times and mutate them as needed.  You may be spending a lot of time doing trig calculations in the drawCircleBody()
Something to consider is setting up a timer rather than using a sleep in a while loop.  This will get you a more consistent frame rate, but you need to make sure that you can actually meet your obligations (or coalesce multiple frames into one if you miss a deadline) or you'll end up creating too many threads.
Consider using a SwingWorker to do the calculations, then update the state in the done() method, finishing by calling repaint().
These are just a few things.  You should experiment to see what works and what doesn't.  It's been a while since I've done Java graphics drawing.

A: Your code isn't following the single threading rule:
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
I'm not sure if this will cause the specific performance problems that you are seeing, but it stands out as a big potential problem, imo.

A: Well, just from a brief look at your draw() function, it seems that you're declaring a number of new objects (especially in drawPolygonBody). Try to reuse objects instead of declaring a new ones each time.
EDIT: instanceof has overhead. It would be a better idea to extend Body to have a draw(Graphics g) function that draws itself. eg:
public class Circle extends Body
{
    // override
    public void draw(Graphics g)
    {
        ...
    }
}

...

void drawBody(Body body)
{
    body.draw();
}

A: Have you tried profiling it to see where in the drawing functions the bottleneck is?
It's hard to say much just by looking at it, but I'm wondering why you're both drawing and filling the polygon in drawPolygonBody.
Also, in drawBoxBody, you're drawing four lines separately instead of just calling drawRect().