text:
Q: (Real Discrete) Fourier Series: Normalisation Factor If you have the equation:
$$f(t) = \sum_{k=0}^N \left( A_k \cos \omega_k t + B \sin \omega_k t\right)$$
To compute the $A_k$ Fourier coefficient you have two cases:
$$A_k = \color{\red}{{2 \over T}} \int_{-T/2}^{T/2} f(t) \cos \omega_k t dt$$
for $k \neq 0$ and
$$A_0 = \color{\red}{{1 \over T}} \int_{-T/2}^{T/2} f(t) dt.$$
I am interested in the normalization coefficients in red. I know where they come from:
$$\scriptsize\int_0^T \cos \left({2 \pi m t \over T}\right)\cos \left({2 \pi n t \over T}\right) dt = \begin{cases}0 & \mbox{ for } n \ne m,\\ T/2 & \mbox{ for } n = m \ne 0,\\T & \mbox{ for } n = m = 0.\end{cases}$$
But my question actually concerns the case where you deal with real signal (no imaginary part). You can write the equation for computing the coefficients as:
$$a[k] = \sum_{x=0}^{N-1} s[x] \cos(\omega_k x)$$
for $k = \{1,...,{N \over 2}\}$, where $N$ is the number of samples making up the discrete signal.
However in this case you need to normalize the coefficients by $1 \over N$ for $A_0$ and $A_{N/2}$ and $2 \over N$ otherwise. So I can imagine the reason why $A_0$ is normalized by $1 \over N$ but I am not sure to understand clearly why it is also the case for the last coefficient in the series $A_{N/2}$. Could someone please explain?
Thank you very much.


text:
Q: Clear server's cached files If I load up a file to my server (an apache) via FTP, the file is correctly uploadet, but when I open it in any browser, an older version of that file is shown (btw, it's a php file). I think, resetting the servers cache will solve the problem, but how can I do this?
Can I use php for this? I've found somethin called htcacheclear in the web, but I don't understand. how to use it. The main problem is, that I have no access to a Terminal or Console, that would be a kind of easy...
Any solution?

A: 1) Simply changing the file name serve new files.
OR
2) You can use Apache httpd.conf to do this.
   Enable mod_headers.so module from httpd.conf and apply those settings at the end of file.
<IfModule mod_headers.c>
    ExpiresActive On
    <FilesMatch "!.(gif|jpe?g|png|js|css|php)$">
        ExpiresACtive On
        ExpiresDefault "access plus 1 year"
        Header unset Cookie
        Header unset Set-Cookie
        php_value session.cookie_domain example.com
    </FilesMatch>
    <FilesMatch "\\.(x?html?|php)$">
        Header set Cache-Control "max-age=600, private, must-revalidate"
    </FilesMatch>
    <FilesMatch "\\.(ico|jpe?g|png|gif|swf|woff)$">
        Header set Cache-Control "max-age=31536000, public"
        Header unset Cookie
        Header unset Set-Cookie
    </FilesMatch>
    <FilesMatch "\\.(css)$">
        Header set Cache-Control "max-age=2692000, public"
        #ExpiresDefault A29030400
    </FilesMatch>
    <FilesMatch "\.(js)$">
        #Header set Cache-Control "max-age=2692000, public"
        ExpiresDefault A29030400
    </FilesMatch>
    <FilesMatch "\\.(js|css|xml|gz)$">
        Header append Vary: Accept-Encoding
    </FilesMatch>
    Header unset Pragma
    FileETag None
    Header unset ETag
    Header append Cache-Control "public"
</IfModule>

redpajama_set_name: RedPajamaStackExchange


text:
Q: XCode 5 Testing symbol "rT" means what? I have 2 test classes in a XCode 5 project:
ABCDataModelTests.{h,m}
- (void)testAlwaysPassing { ... }

ABCDataModelListColorsTests.m which inherits from ABCDataModelTests.
- (void)testNumberOfListColorsGreaterThan7 { ... }

When I ran the test, I noticed that there is a symbol "rT" underneath the subclass's tests as shown in the picture.
What does "rT" stand for? Note that the subclass inherits the test method "testAlwaysPassing."
I can't find anything in the Apple documentation for "New Features in XCode 5/5.0.1" Is there any documentation for what all the symbols stand for?

A: I found this information on some forums:

The standard way to do things in SenTestingKit/OCUnit/XCTest is to declare your tests in code. If you do, Xcode will discover them statically (ie. not at runtime) using the index. Once Xcode these tests are discovered, they show up in the test navigator with a "t" icon. So far so good.
Now, the SenTestingKit/OCUnit/XCTest frameworks also allow you to create tests on the fly at runtime. Some of our users make creative user of this capability, perhaps to wrap an external testing system or to create tests to represent a dynamic set of data. Xcode cannot discover these tests statically, and only find out about their existence when they are returning resutls during a test run. When discovered, they will show up in the test navigator with a "rT" icon. "rT" being short for "runtime discovered tests".
Finally. If there's anything wrong / unusual about your project that prevents indexing from completing or from properly parsing your test classes, then your tests wouldn't be statically discovered. You may still successfully build and run them, in which case Xcode would end up treating them as runtime discovered tests, and give them the "rT" icon.

A: I agree with what @everyday_productive said
"rT" usually means something wrong with indexing, to fix this go to terminal and type the following:
$ cd ~/Library/Developer/Xcode/

Make sure your Xcode is terminated then delete "Derived Data" folder.

A: Interesting. I have been very annoyed by the same problem with a test class I created by duplicating another file in the IDE. I have duplicated other test files before so that doesn't seem to be the problem.
The test class has only a single test inside it and another side-effect of the purple icon and classification of it as a runtime test is that you can't trigger the test with the little triangle icon offered in the test runner for the other tests or test classes.
The contextual menu in the test explorer offers Test "testBlah" which seems to exercise the test.
Quitting XCode, deleting the xcuserdata folder and rebuilding made the test recognised again as a normal test.
I am getting reminders of older Visual Studio versions which used to have caching problems and needed regular deletion of their local context data!

A: Deleting derived data didn't help me to get rid of running these tests. So I've created a small category on XCTestCase and it worked:
#import "XCTestCase+TestCaseSwizzling.h"
@import ObjectiveC.runtime;

static NSMutableSet* alreadyRunTests = nil;

@implementation XCTestCase (TestCaseSwizzling)

+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{

    alreadyRunTests = [NSMutableSet set];

    Class class = [self class];

    SEL originalSelector = @selector(invokeTest);
    SEL swizzledSelector = @selector(swizzledInvokeTest);

    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

    method_exchangeImplementations(originalMethod, swizzledMethod);
});
}

- (void)swizzledInvokeTest
{
     NSString* selectorString = NSStringFromSelector(self.invocation.selector);

     if (![alreadyRunTests containsObject:selectorString])
     {
         [alreadyRunTests addObject:selectorString];
         [self swizzledInvokeTest];
     }
 }

 @end

A: Delete the references to the files from the project, then re-added them.


text:
Q: AWS IAM Role in EC2 and access to S3 from JupyterHub In JupyterHub, installed in an EC2 instance with an IAM role which allows access to a specific S3 bucket when I try to access a file in that bucket with this code:
s3nRdd = spark.sparkContext.textFile("s3n://bucket/file")

I get this error:

IllegalArgumentException: u'AWS Access Key ID and Secret Access Key
  must be specified as the username or password (respectively) of a s3n
  URL, or by setting the fs.s3n.awsAccessKeyId or
  fs.s3n.awsSecretAccessKey properties (respectively).'

However, when I export the AWS access key id and secret access key in the kernel configuration having the same policy as that role, the read for that file succeeds.
As the best practice is to use IAM roles, why doesn't the EC2 role work in this situation?
--update--
The EC2 IAM role has these 2 policies:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1488892557621",
            "Action": "s3:*",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::<bucket_name>",
                "arn:aws:s3:::<bucket_name>/*"
            ]
        }
    ]
}

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "ec2:*",
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Sid": "Stmt1480684159000",
            "Effect": "Allow",
            "Action": [
                "iam:PassRole"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

Also, I am using hadoop version 2.4.0 which doesn't support s3a protocol and updating is not an option.

A: You must create a bucket policy to allow access from particular IAM roles. Since S3 doesn't trust the roles, the API just fallback and ask for access key.
Just add soemthing like this in your bucket policy, replace all the custom <> parameter with your own values.
{
    "Version": "2012-10-17",
    "Id": "EC2IAMaccesss",
    "Statement": [{
            "Sid": "MyAppIAMRolesAccess",
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::<acc_id>:role/<yourIAMroleName>"
                ]
            },
            "Action": [
                "s3:ListBucket",
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::<yourbucket>/*",
                "arn:aws:s3:::<yourbucket>"
            ]
        }
    ]
}

(updates)

*

*Make sure you give proper policy to the EC2 IAM Roles, because IAM roles is very powerful, no Policy is attach to it out of the box. You must assign a policy, e.g. for minimal S3 access, add AWSS3ReadOnly policy to the roles.

*You may encounter issues of spark problematic interaction with IAM roles. Please check the documentation on spark access through s3n:// schema. Otherwise, use s3a://

A: S3n doesn't support IAM roles, and 2.4 is a very outdated version anyway. Not as buggy as 2.5 when it comes to s3n, but still less than perfect.
If you want to use IAM roles, you are going to have to switch to S3a, and yes, for you, that does mean upgrading Hadoop. sorry.


text:
Q: Ошибка при сборке docker образа Всем привет.
Птыаюсь собрать образ ASP.NET Core решения, состоящего из 3 проектов.
В корневой папке у меня 3 проекта (Common, Data, Web)
DockerFile кидал и в корень этих 3 проектов и в папке Web.
Но при сборке командой "docker build -t name ." получаю ошибку

[build 4/7] RUN dotnet restore "IPN.IPCP.Web/IPN.IPCP.Web.csproj":
#12 3.202   Determining projects to restore...
#12 3.209   Skipping project "/src/IPN.IPCP.Common/IPN.IPCP.Common.csproj" because it was not found.
#12 3.209   Skipping project "/src/IPN.IPCP.Data/IPN.IPCP.Data.csproj" because it was not found.
#12 3.214   Skipping project "/src/IPN.IPCP.Common/IPN.IPCP.Common.csproj" because it was not found.
#12 3.214   Skipping project "/src/IPN.IPCP.Data/IPN.IPCP.Data.csproj" because it was not found.
#12 71.15 /src/IPN.IPCP.Web/IPN.IPCP.Web.csproj : error NU1101: Unable to find package APRF.DialConnector.Client. No packages exist with this id in source(s): nuget.org
#12 71.15 /src/IPN.IPCP.Web/IPN.IPCP.Web.csproj : error NU1101: Unable to find package APRF.DialConnector.Contract. No packages exist with this id in source(s): nuget.org
#12 71.36 /src/IPN.IPCP.Web/IPN.IPCP.Web.csproj : warning NU1701: Package 'NReco.VideoConverter 1.1.3' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net6.0'. This package may not be fully compatible with your project.
#12 71.49   Failed to restore /src/IPN.IPCP.Web/IPN.IPCP.Web.csproj (in 1.13 min).

Код докерфайла следующий:
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["Web/Web.csproj", "Web/"]
RUN dotnet restore "Web/Web.csproj"
COPY . .
WORKDIR "/src/Web"
RUN dotnet build "Web.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Web.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Web.dll"]

Что делаю не так ?


text:
Q: Automating Adding Tables Fast to LateX from R?
Possible Duplicate:
How can I use a table generated by R in LaTeX?

I use a lot of tables from R, and I find it cumbersome and very slow to type the "&" and "\" etc. to get the tables translated into LaTeX. Is there some way to have a table like that below automatically formatted for LaTeX?
      Df Deviance Resid. Df Resid. Dev
NULL                      74    1233.55
inflat  1     4.13        73    1229.42
inc     1   907.24        72     322.18
Analysis of Deviance Table

       Df Deviance Resid. Df Resid. Dev
NULL                      59    1450.07
inflat  1    99.44        58    1350.63
inc     1   861.93        57     488.69
Analysis of Deviance Table

       Df Deviance Resid. Df Resid. Dev
NULL                     158    28963.3
inflat  1   3302.4       157    25660.9
inc     1  23996.2       156     1664.8

A: Using the XTable package as Alan commented.  There's a good set of example tables as part of the  CRAN XTable vignette.  You may also want to look at the descr package which has helper function to produce some other usefull tables.
Xtable can either just produce the latex code that you can copy/paste into a tex file, or you can use it within a sweave document to produce the tables automatically as part of your analysis.


text:
Q: Precision in python How can write a print statement in python that will print exactly 2 digits after decimal?

A: x = 4.12121212
print '%.2f' % x

Basically, the same way you'd do it in C with printf.

A:  f = 4.55556
 print "{0:.2f}".format(f)

There is also a special module for fixed point decimals. More: http://docs.python.org/library/decimal.html

A: print "{0:.2f}".format(your_number)

This is explained in detail in the Python Documentation.

A: this is django float format template tag, that may be interest for you to reading ...
at line 92 :
django float format template tag

A: Another efficient way of doing this is:
import sys
a = 0.5
sys.stdout.write(str('%0.2f'%a))


text:
Q: RubyMotion: losing superview after opening a new screen I'm using a combination of ProMotion, Teacup, and MMDrawerController. When I load the app, everything works fine, but when I try to change from one screen to another, I'm getting an error with Teacup because the superview is nil. The Teacup error is:
*** Terminating app due to uncaught exception 'NoMethodError', reason: 'calculations.rb:15:in calculate:': undefined method 'bounds' for nil:NilClass (NoMethodError). That's being thrown because view.superview is null.
I'm a beginner, but it feels like the Teacup error is just the symptom of a bigger problem with the way I've set everything up, or possibly, an incompatibility with MMDrawerController.
So, the app loads, goes to WeekScreen, and on WeekScreen, I add a navbar with a button to go back to WeekScreen. When I click that button, I get the error. (I've simplified the code here -- I really don't have a one page app with a button to go back to the same screen)
screens/root_screen.rb
class RootScreen < MMDrawerController
  include PM::ScreenModule

  title 'Schedule'

  def self.new(args = {})
    alloc.init.tap do |root_screen|
      root_screen.on_create(args)
    end
  end

  def centerViewController=(centerViewController)
    super
    self.title = centerViewController.title
  end

  def on_create(args={})
    super

    self.leftDrawerViewController   = Screen::MenuScreen.new(nav_bar: false)
    self.rightDrawerViewController  = nil
    self.centerViewController = week_screen

    leftDrawerButton = MMDrawerBarButtonItem.alloc.initWithTarget self, action:"show_menu:"
    navigationItem.setLeftBarButtonItem leftDrawerButton, animated:true
  end

  def will_appear
    self.title = centerViewController.title
  end

  def show_menu(sender)
    toggleDrawerSide MMDrawerSideLeft, animated:true, completion: nil
  end

  def week_screen
    @week_screen ||= Screen::WeekScreen.new
  end
end

screens/week_screen.rb
module Screen
  class WeekScreen < PM::Screen

    title ''
    stylesheet :week_styles
    include Teacup::TableViewDelegate

    @@cell_identifier = nil
    @selected_date = nil

    def will_appear
      super

      # mm_drawerController.title = title
      view.subviews.each &:removeFromSuperview

      layout(view, :main_view) do |main_view|
        week_table

        subview(UIView, :program_nav) do
          @week_btn = subview(UIButton.buttonWithType(UIButtonTypeRoundedRect), :week_btn)
        end

        @week_btn.when_tapped do
          open WeekScreen.new(nav_bar: true)
        end
      end
    end

    # a bunch of table stuff removed here to keep this clean-ish
  end
end

styles/week_styles.rb
Teacup::Stylesheet.new :week_styles do
  style :main_view,
    frame: [[0,30], ["100%", "100% - 30]]

  style :program_nav,
    frame: [[0, "100% - 78"], ["100%", 78]],
    backgroundColor: "#f1f2f2".to_color,
    autoresizingMask: (UIViewAutoresizingFlexibleLeftMargin |
                   UIViewAutoresizingFlexibleRightMargin |
                   UIViewAutoresizingFlexibleTopMargin)

  style :week_btn,
    center_x: '50%',
    center_y: '50%',
    width: 36,
    height: 36,
    backgroundImage: UIImage.imageNamed("week-view-btn")
end

A: Try moving the call to on_create to inside on_load.  The screen's view property is nil inside your init.tap block.


text:
Q: How to get Received Signal Strength Indicator (RSSI) of a bluetooth device? I want to recognize bluetooth device with in my bluetooth device range that means i want to get particular device received signal strength indicator (RSSI).
Is any Java API for getting RSSI of a particular device?
If such exist, please give information about that Java API.

A: There's a list of Java BlueTooth APIs at the Wikipedia Article: Java APIs for BlueTooth.
I'm sure most of them have facilities to read RSSI.

I had a look at bluecove.org's API for instance and found this:

*

*RemoteDeviceHelper.readRSSI

A: I found this code but I don't know how to get the values , maybe there is a class to be imported:
please  check and let me know.
public static int calculateSignalLevel(int rssi, int numLevels)
 { if (rssi <= MIN_RSSI)
 {return 0;} else if (rssi >= MAX_RSSI) { return numLevels - 1; }
 else { int partitionSize
 = (MAX_RSSI - MIN_RSSI) / (numLevels - 1);  return (rssi - MIN_RSSI) / partitionSize;   }
 }


text:
Q: React Native - How to detect view screen is scrollable? Main Question : how to keep scrollbar of ScrollView visible?
and this question isn't answered my question
similar question : How can i detect if a content of view height is higher than device height? so i can setState if the screen is scrollable
I have tried using onLayout with this code:
<View onLayout={(event)=>{var {x, y, width, height}=event.nativeEvent.layout}}>
  //Long Content higher than device height
</View>

but I got the height of view in device screen and not the height of a content itself
Is there a way to answering my question?

A: I dont know how to get height inside a View but inside ScrollView you can use onContentSizeChange.
import React, { Component } from "react";
import { View, Text, StyleSheet, Dimensions, ScrollView, Image } from "react-native";

const images =
    [
        { image: 'https://www.lens-rumors.com/wp-content/uploads/2014/10/Nikon-AF-S-DX-Nikkor-18-140mm-f3.5-5.6G-ED-VR-sample-images1.jpg', text: 'hello' },
        { image: 'https://www.lens-rumors.com/wp-content/uploads/2014/10/Nikon-AF-S-DX-Nikkor-18-140mm-f3.5-5.6G-ED-VR-sample-images1.jpg', text: 'hello' },
        { image: 'https://www.lens-rumors.com/wp-content/uploads/2014/10/Nikon-AF-S-DX-Nikkor-18-140mm-f3.5-5.6G-ED-VR-sample-images1.jpg', text: 'hello' },
        { image: 'https://www.lens-rumors.com/wp-content/uploads/2014/10/Nikon-AF-S-DX-Nikkor-18-140mm-f3.5-5.6G-ED-VR-sample-images1.jpg', text: 'hello' }];

class Test extends Component {
    find_dimesions(width,height) {
        const deviceHeight = Dimensions.get("window").height;
        const deviceWidth = Dimensions.get("window").width;
        console.log(" view width:" + width + "  " + "view height:" + height);
        console.log(
            "device width:" + deviceWidth + "  " + " device height:" + deviceHeight
        );
    }

    render() {
        return (
            <ScrollView
            onContentSizeChange={(width, height) => {
                this.find_dimesions(width,height)
              }}
                style={styles.container}
            >
                {images.map((data, index) => {
                   return <View key={index} style={{ flex: 1 }}>
                        <Image style={{height:200,width:200}} source={{ uri: data.image }} />
                    </View>
                })}
            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex:1,
        // justifyContent: "center",
        // alignItems: "center",
        backgroundColor: "#F5FCFF",

    }
});

export default Test;


text:
Q: How to add custom shortcuts in tinyMCE 3.5 "Ctrl + A = Select All
Ctrl + C = Copy
Ctrl + V = Paste
Ctrl + Z = Undo
Ctrl+Shift+> =Increase Font Size
Ctrl+Alt+> = Standard Size
Ctrl+Shift+> = Increase Font size
Ctrl+Shift+< = Decrease Font Size
Ctrl+Shift+B = Bold
Ctrl+Shift+I = Italic
Ctrl+Shift+U = Underline
Ctrl+Shift+C = Center Align
Ctrl+Shift+J = Justify
Ctrl+Shift+L = Left Align
Ctrl+Shift+R = Right Align
Ctrl+Shift+/ = Strikethrough
Ctrl+Shift+V = Reverse
Ctrl+T = Character Specs
Ctrl+Shift+K = All Caps
Ctrl+\ = Subscript
Ctrl+Shift+\ = Superscript
Ctrl+M = Paragraph
Ctrl+I = Indents/Tabs
Ctrl+3 = Define Style
Ctrl+U = File & Stroke
Alt + Ctrl+F = Frame Option
Ctr+} = Bring To Front
Ctrl+{ = Send To Back
Ctrl+Shift+} = Send Backward
Ctrl+Shift+{ = Bring Forward
Ctrl+Shift+E = Align Object
Ctrl+Alt+E = Text Wrap
Ctrl+G = Group Ctrl+Shift+G = Ungroup
Ctrl+F = Find"


text:
Q: How to Encrypt/Decrypt data in Angular and Java - CryptoJS I found this code
package com.sumant.springboot.learning.springcloudgateway;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptDecryptHelper {

    private static final String SECRET_KEY = "Thisisatestkeyfortesting";

    private static SecretKeySpec secretKey;
    private static byte[] key;

    public static String encrypt(String strToEncrypt){
        return encrypt(strToEncrypt, SECRET_KEY);
    }

    public static String decrypt(String strToDecrypt){
        return decrypt(strToDecrypt, SECRET_KEY);
    }

    public static void setKey(String myKey)
    {
        MessageDigest sha = null;
        try {
            key = myKey.getBytes("UTF-8");
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
//          System.out.println(key);
            key = Arrays.copyOf(key, 16);
            secretKey = new SecretKeySpec(key, "AES");
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String strToEncrypt, String secret)
    {
        try
        {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        }
        catch (Exception e)
        {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

    public static String decrypt(String strToDecrypt, String secret)
    {
        try
        {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        }
        catch (Exception e)
        {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }

    public static void main(String[] args) {

        String key = "Thisisatestkeyfortesting";

        //language=JSON
        String data = "{\"title\": \"TestTitle1\",\"author\": \"TestAuthor1\"}";

        System.out.println("Original String: " + data);

        String encryptedString = EncryptDecryptHelper.encrypt(data, key);

        System.out.println("Encrypted String: " + encryptedString);

        String decryptedString = EncryptDecryptHelper.decrypt(encryptedString, key);

        System.out.println("Decrypted String: " + decryptedString);

    }
}

This generates encryption string

Encrypted String:
Qua63XoZnGDpvBYtmoEZipALDamRw6EvmB0oWLD+wgi80PzmMZw2WTX4CIP6R79+

How can I encrypt/decrypt in angular using crypto-js
The code to encrypt on angular side (using encrypt on both sides to confirm settings are ok)
 public message: string= "{\"title\": \"TestTitle1\",\"author\": \"TestAuthor1\"}";
  public password: string ="Thisisatestkeyfortesting";

  public decryptedMessage: string;

    const key = CryptoJS.enc.Utf8.parse(this.password);
    const iv = CryptoJS.enc.Utf8.parse(this.password);
    const encrypted = CryptoJS.AES.encrypt(this.message, key, {
      keySize: 16,
      iv: iv,
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    console.log('Encrypted :' + encrypted);

Encrypted
:peUrphsVZzpQbi5GF8JWgQ3mWY0tGCE5m9VHM/dYibizS37hUarfHzoFXrKbJZsv

What is wrong in the above code ? why the encrypted text are different? Please suggest the fix
Main goal is to encrypt on angular and decrypt on java/spring , and vise versa


text:
Q: Queuing for Heroic Burning Crusade in WoW Dungeon FInder I started playing WoW again after 10 or so years and the Dungeon Finder is kind of new to me, so help me out. I'm level 80. I can use the Dungeon Finder to queue for Burning Crusade Normal, Wrath of the Lich King Normal and WotLK Heroic... but I can't queue for Burning Crusade Heroic. Why not? I want to run a Heroic BC dungeon to build some rep, but the BC Heroic section doesn't even show up in my options.

A: You only get to see the dungeons within your level range. If you exceed the max level of that dungeon they will disappear from the dungeon browser. Heroic dungeons have a stricter level requirement than normal dungeons (max and min level), so they disappear sooner.
In your case you have reached the range of WOTLK and only get to see the heroics from there. And you're too high for BC and too low for cata heroics, so they're not there. You can still access lower heroic dungeons by going there directly, but not queue for them on your own*.
Some examples:
Level 90

Level 110

* - You CAN join the other dungeons.

*

*Go there directly. Just walk in and you can clear them (solo or with a pre made group).

*Group up with someone within qualified level range (e.g. level 70 for BC heroics) and start a party sync. Let them queue up for a dungeon and you can join them. The dungeon will be scaled to match your level (wihtout affecting the other people) and you won't be able to use skills, talents, etc higher than allowed by the dungeon, so you should feel perfectly like you're in a "real" dungeon. Due to the low amount of people doing this you have to expect longer waiting times.

*Time walking weekly events work as well. They basically eliminate the max level requirement. If a certain event is up you can queue for it and it will be exactly like the heroic version of those dungeons, except that you have all your current skills and spells available. Higher gear will be scaled down to match the level of the dungeon, so they can't be outgeared that easily.


text:
Q: How do I make Bootstrap navbar change active state? I'm new to HTML and JavaScript and right now I'm faced with a problem that I assume many of you have been dealing with yourself.
I have a nav-bar that doesn't by default changes the active-state when I click on a different page-reference.
The 'Home' nav-item is by default active, and I want to change the active state when I click on other nav-items. But I don't know how to do it? As far is I understand this isn't too many lines of code, but I'd love to get some assistance here.
Here's my code:

    <meta charset="UTF-8">
    <title>MaU Movie database</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://bootswatch.com/4/cyborg/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="mumdblogo.png">

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02"
            aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    Home
                        (current)

                    Library

                    Uploads

                    About

Search Movie!

            <form id="searchForm">
                <input type="text" class="form-control" id="searchText" placeholder="Search for any movie...">
            </form>

A: You can do this one an the end of your code. Just below

And them instead of follow by link (event.preventDefault()) eg. about.html OR uploads.html this snipet of code change active class for clicked item.

EDIT 1:
For static pages (or served eg. by php) you don't need any aditional js code, BUT you should tweak nav to looks like in below examples (look where 'active' class is, sr-only span current is optional, but well placed in examples).
index.html (your base code)

        Home(current)

        Library

        Uploads

        About

library.html

        Home

        Library(current)

        Uploads

        About

uploads.html

        Home

        Library

        Uploads(current)

        About

about.html

        Home

        Library

        Uploads

        About(current)

A: I think that the easiest solution is to check the pathname of in the location object of the window and change the nabber state accordingly.
Something like this would work:
var pathname = window.location.pathname,
pages = ['home', 'library', 'uploads','about'];

$('.nav-item').each(function(i) {
 if (pathname.includes(pages[i])) this.addClass('active');
 else if (this.className.includes('active')) this.removeClass('active');
});


text:
Q: Проблема с Object.prototype Я создаю 2 функции для прототипа объекта, а в консоль сыпятся ошибки:

jquery-2.2.3.min.js:2 Uncaught TypeError: W[g].exec is not a function

Возможно конфликтует что то с jquery, подскажите как решить вопрос?
Вот пример функций:
Object.prototype.getFirstKey = function () {
        for (var i in this) {
            return i;
            break;
        }
    }

    Object.prototype.getFirstValue = function () {
        for (var i in this) {
            return this[i];
            break;
        }
    }

A: Изменять встроенные объекты - очень плохая практика, не используйте её.
Это не jQuery 2.2.3:

Object.prototype.getFirstKey = function() {
  for (var i in this) {
    return i;
    break;
  }
}

Object.prototype.getFirstValue = function() {
  for (var i in this) {
    return this[i];
    break;
  }
}

let test = {
  hello: 'world',
  some: 'value'
};

console.info(test.getFirstKey(), ' | ', test.getFirstValue());
console.info('Всё работает без ошибок, версия jQuery: %s', $().jquery);
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>

UPDATE:

let arr = JSON.parse`[ { "hash1": { "color": "blue", "size": "1", "count": 1 } }, { "hash2": { "color": "red", "size": "22", "count": 22 }},{ "hash3": { "color": "red", "size": "22", "count": 22 }}]`;

// Перебираем объекты объектов
arr.forEach(e => {
  // Перебираем сами объекты
  Object.keys(e).forEach(hash => {
    console.info(hash, e[hash]);
  });
});


text:
Q: Create a Docker container without internet access What's the simplest way to create an isolated Docker container that doesn't have any internet access whatsoever?

A: Use the none network: "The none network adds a container to a container-specific network stack. That container lacks a network interface"
For example, you can run a container without network interfaces attached to it specifying none as the network:
docker run --net none -it alpine  /bin/sh

See that only the loopback interface is attached:
/ # ifconfig -a
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)


text:
Q: How can I connect an NVIDIA GeForce GT 330 to multiple monitors? My video card has displayport & DVI-I. I used this picture. I have:

*

*DVI-I to VGA (Currently use this to connect Acer monitor)

*Bizlink (Active Display Port to DVI-D) Cable. View

*DL-DVI-D to VGA adapter

*First display: Acer G225 HQ (VGA & DVI-D port)

*Second display: Dell 19 inch monitor (VGA port)

I want to use dual monitor. But I'm connecting video card to bizlink, DVI to DVI, and Dell monitor.
My video card can support multimonitor. Geforce GT 330 Review
How can I connect a second monitor?

A: The way you describe it is confusing, but it sounds like you're trying to connect the Dell monitor via VGA, through a DVI-D adapter, through a DisplayPort adapter, to the DisplayPort connector on the card.  This will not work because DVI-D is digital only.  You need an active digital-to-analog converter somewhere along the line, that's what an adapter like that is intended to be used in conjunction with.  I'd just buy a DisplayPort to VGA converter (which generally don't need external power beyond what the DisplayPort provides itself, which is a nice bonus).


text:
Q: Why is this application stucked on loading json content? I'm trying to use this Github example to learn how to GET and POST data from a PHP/MySQL server using json requests.
I've been able to run the pendaftaran database perfectly on my browser using XAMPP.
However, when the following application class is trying to fetch data from the MySQL db, it becomes stucked displaying the ProgressDialog.
package id.creatorb.bukutamu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SemuaBukuTamu extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // buat json object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> bukutamuList;

    // url untuk get semua buku tamu
    private static String url_semua_bukutamu = "http://192.168.1.22/lab-tutor/pendaftaran/get_all_pendaftaran.php";

    // JSON Node
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PENDAFTARAN = "pendaftaran";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // pendaftaran JSONArray
    JSONArray pendaftaran = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.semua_bukutamu);

        // Hashmap untuk ListView
        bukutamuList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadSemuaBukuTamu().execute();

        // Get listview
        ListView lv = getListView();

        // select single bukutamu
        // Jalankan tampilan edit buku tamu
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // dapatkan nilai dari list pendaftaran
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

                // Memulai aktifitas baru
                Intent in = new Intent(getApplicationContext(),
                        EditBukuTamu.class);
                // kirimkan pid ke activity selanjutnya
                in.putExtra(TAG_PID, pid);

                // memulai activity baru dengan mnghrap bbrapa kembalian response

                startActivityForResult(in, 100);
            }
        });

    }

    // response dari edit bukutamu
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // jika kode hasil sama dengan 100
        if (resultCode == 100) {
            // maka diterima
            // ketika user ngedit atau menghapus data
            // reload screen
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task untuk menampilkan semua daftar bukutamu menggunakan http request
     * */
    class LoadSemuaBukuTamu extends AsyncTask<String, String, String> {

        /**
         * sebelum melakukan thread di background maka jalankan progres dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(SemuaBukuTamu.this);
            pDialog.setMessage("Mohon tunggu, Loading Data...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * dapetkan semua produk dari get url di background
         * */
        protected String doInBackground(String... args) {
            // Buat Parameter
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // ambil json dari url
            JSONObject json = jParser.makeHttpRequest(url_semua_bukutamu, "GET", params);

            // cek logcat untuk response dari json
            Log.d("Semua Buku Tamu: ", json.toString());

            try {
                // cek jika tag success
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // data ditemukan
                    // ambil array dari bukutamu
                    pendaftaran = json.getJSONArray(TAG_PENDAFTARAN);

                    // tampilkan perulangan semua produk
                    for (int i = 0; i < pendaftaran.length(); i++) {
                        JSONObject c = pendaftaran.getJSONObject(i);

                        // simpan pada variabel
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

                        // buat new hashmap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // masukan HashList ke ArrayList
                        bukutamuList.add(map);
                    }
                } else {
                    // jika tidak ada data
                    // maka jalankan tambahkan buku tamu
                    Intent i = new Intent(getApplicationContext(),
                            TambahBukuTamu.class);
                    // tutup semua proses sebelumnya
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * jika pekerjaan di belakang layar selesai maka hentikan progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // hentikan progress ketika semua data didapat
            pDialog.dismiss();
            // perbarui screen
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * perbarui json ke arraylist
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            SemuaBukuTamu.this, bukutamuList,
                            R.layout.list_pendaftaran, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // perbarui list pendaftaran
                    setListAdapter(adapter);
                }
            });

        }

    }
}

EDIT
I've found out after some debugging that if I switch the local IP to localhost it will throw an Exception on the JSONParser.class at
HttpResponse httpResponse = httpClient.execute(httpGet);

What could possibly be going on?


text:
Q: different execution time between loclal variable and static structure I write a program on AVR's microcontrolers. It should check actual temperature and show it on 7-segment display. And this the problem which I have: I made a structure with all variables referd to temperature (temperature, pointer position, sign and unit) and saw that the execution time of e.g. dividing by 10 or mod 10 is much more longer then when i use normal local variable. I dont know why. I use Atmel Studio 6.2.
struct dane
{
    int32_t temperature;
    int8_t pointer;
    int8_t sign;
    int8_t unit;
};
//************************************
//inside function of timer interrupt
static struct dane present;

//*****************************
//tested operations:
present.temperature % 10;    //execution time: ~380 processor's cycles, on normal local variable ~4 cycles.
present.temperature /= 10;    //execution time: ~611 cycles

I give you this function where I use it and a little bit of assembly code.
ISR(TIMER0_OVF_vect)
{
    static int8_t i = 4;
    static struct dane present;

    if(i == 4 && (TCCR0 & (1 << CS01)))
    {
        i = 0;
        present = current;
        if(present.temperature < 0)
            present.temperature = -present.temperature;
    }

    if((TCCR0 & ((1 << CS00) | (1 << CS02))) && i != 0)
    {
        i = 0;
    }
    if(present.unit == current.unit) //time between here and fist instruction in function print equals about 300 cycles.
    {
        print((i * present.sign == 3 && present_temperature % 10 == 0) ? 16 : present_temperature % 10, displays[i], i == present.pointer);
    }
    else
    {
        print(current.unit, displays[i],0);
        if(i == 4)
        {
            i = 3;
            TCCR0 = (1 << CS01);
            present.unit = current.unit;
        }
    }

    present.temperature /= 10;
    i++;
}

And assembly code for the one before last instruction:
present.temperature /= 10;
0000021F  LDI R28,0x7D      Load immediate
00000220  LDI R29,0x00      Load immediate
00000221  LDD R22,Y+0       Load indirect with displacement
00000222  LDD R23,Y+1       Load indirect with displacement
00000223  LDD R24,Y+2       Load indirect with displacement
00000224  LDD R25,Y+3       Load indirect with displacement
00000225  LDI R18,0x0A      Load immediate
00000226  LDI R19,0x00      Load immediate
00000227  LDI R20,0x00      Load immediate
00000228  LDI R21,0x00      Load immediate
00000229  RCALL PC+0x01AC       Relative call subroutine
0000022A  STD Y+0,R18       Store indirect with displacement
0000022B  STD Y+1,R19       Store indirect with displacement
0000022C  STD Y+2,R20       Store indirect with displacement
0000022D  STD Y+3,R21       Store indirect with displacement

I can't use int16_t for temperature because I use the same structure inside function which coverts the temperature from the sensor and it is easier to operate on number with decimal part when I multiply it by 10 powered by suitable number.

A: There must be something wrong with your timings:
present.temperature % 10;    //execution time: ~380 processor's cycles, on normal local variable ~4 cycles.
present.temperature /= 10;    //execution time: ~611 cycles

A modulo-10 operation for a 32-bit value is never going to happen in 4 clock cycles with an AVR. The 380 cycles sounds a lot, but it is more realistic for a 32:32 division operation. I am afraid even an integer division on an AVR will take a lot of time with long integers.
It is quite natural that operations on module static variables take a bit longer, because they have to be fetched and stored in the RAM. This takes maybe 10 extra clock cycles per byte when compared to register variables (local variables are often in a register. The variable being in a struct should not change the timings at all in a case like this (with pointers to structs it may have an effect).
The only real way to get to know what is happening is to look at the assembly code produced by the compiler in each case.
And, please, include a minimal but complete example of both cases in your question. Then it is easier to see if there is something clearly wrong.

If you are interested in making your code faster, I suggest you try to use int16_t for the temperature. Your dynamic range in temperature measurement is hardly more than 12 bits (that would be, e.g., 0.1 °C for temperatures between -100°C..+300°C.) so that 16-bit ints should be sufficient.


text:
Q: Use of data available in async function on node request to update data of the application This is a simplification of a module in nodejs I'm working.
I know that the function sent as second parameter of request is async. But I cannot understand how I can access that data.
Basically, I need to fetch some external json file, hopefully only once, when the server start (and I call the function requestJson), and use this data to update the global for the module json_data. This json_data will be the data consulted by the api exposed (apicall1 and apicall2, corresponding to getSomeJSONData1 and getSomeJSONData2)
var json_data = []; // <-- here I want to put the json data

var requestJson = function() {
  request({
    url: "example.com/somejson.json",
    json: true
  }, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      //here I have access to the json content
      // how I can do to use the body content
      // and put it on json_data
    }
  });
}

var getSomeJSONData1 = function() {
  return json_data[0];
};

var getSomeJSONData2 = function() {
  return json_data[1];
};

exports.apicall1 = getSomeJSONData1;
exports.apicall2 = getSomeJSONData2;

how I could do that?

A: Try this. Install q module.
var json_data = []; // <-- here I want to put the json data

var requestJson = function() {
  var dfd = q.defer();
  request({
    url: "example.com/somejson.json",
    json: true
  }, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      //assign json_data
      dfd.resolve({});
    } else {
      dfd.reject({});
    }
  });
  return dfd.promise;
}

var getSomeJSONData1 = function() {
  var dfd = q.defer();
  if(json_data.length){
    dfd.resolve(json_data[0]);
  } else {
    requestJson()
      .then(function(res) {
        dfd.resolve(json_data[0]);
      })
      .catch(function(err) {
        dfd.reject('error');
      });
  }
  return dfd.promise;
};

var getSomeJSONData2 = function() {
  var dfd = q.defer();
  if(json_data.length){
    dfd.resolve(json_data[1]);
  } else {
    requestJson()
      .then(function(res) {
        dfd.resolve(json_data[1]);
      })
      .catch(function(err) {
        dfd.reject('error');
      });
  }
  return dfd.promise;
};

exports.apicall1 = getSomeJSONData1;
exports.apicall2 = getSomeJSONData2;


text:
Q: Find all homomorphisms of $(\mathbb{Z}, +, \cdot)$ How to find all homomorphisms for ring $ (\mathbb{Z}, +, \cdot) $ ? Operations $+$ and $\cdot$ are usual operations of addition and multiplication in $\mathbb{Z}$. If you can, please provide a general approach to finding all homomorphisms in a ring.
It would also be great if you could do the same for groups. I also had another question for which I have the answer, to find all automorphisms of group $(\mathbb{Q}, +)$. However I do not understand it. I will write it out, it would be helpful if you could explain it since I really don't know the approach to these kind of problems.
Solution: Homomorphisms $f \colon \mathbb{Q}\to \mathbb{Q}$ need to satisfy: $$ f(x+y) = f(x) +f(y)\\ f(x \cdot y) = f(x) \cdot f(y), \forall x \in \mathbb{Q}$$
$$f(0+0) = f(0)+f(0) \implies f(0) = 0 \\$$ Let $$f(1)=a \in \mathbb{Q}$$ then $$f(2) = f(1+1) = f(1) + f(1) = 2a \\f(3) = f(1+1+1) =f(1+1)+f(1) =f(1)+f(1)+f(1)=3a \\ \dots \\f(n) =  n \cdot a $$ Next, $$f(n)+f(-n) = f(n+(-n)) = f(0) = 0\\ f(-n) = -f(n) = (-n)a$$
Similarly, for $\hspace{0,5cm}r= \frac{p}{q}, p \in \mathbb{Z}, q \in \mathbb{N}\hspace{0,5cm} f(r)= \frac{p}{q} \cdot a = ra. \hspace{1cm}$ So, $\forall x \in \mathbb{Q} \hspace{0,5cm} f(x)=xa.\\$ We got: $$f(x+y)=(x+y)a \\f(x)+f(y)=xa+ya = (x+y)a$$


text:
Q: ffmpeg output video size limits to 4GB I have a video file of .mp4 format. I want to convert it into .mpeg.
But when the output file size reaches 4GB, the conversion stops with a message something like "av_interleaved_write_frame() file too large"
My file system is ext4.
The commands I used are as below :
ffmpeg -i "input_file.mp4" -q:v 0 -q:a 0 -c:v mpeg2video "output_file.mpeg"
ffmpeg -i "input_file.mp4" -q:v 0 -q:a 0 -c:v mpeg2video -fs 8G "output_file.mpeg"
I understand that the conversion target defaults to DVD, so, the 4GB is the upper limit. can I tweak the target ?
Or, is it possible to dump the output to a subsequent file2Out.mpeg once file1Out.mpeg reaches 4GB

A: Yes, the reason is the filesystem format. FAT32 doesnt allow an mpeg file to exceed 4GB.
thank you

A: For instance, if your input lasts for 2 hours, you can convert the first hour to one file, and the second hour to another file by using -to option to stop at a certain position and -ss (placed before -i) option to start from a certain position:
ffmpeg -i "input_file.mp4" -to 1:00:00 -q:v 0 -q:a 0 -c:v mpeg2video "output_file_h1.mpeg" && \
ffmpeg -ss 1:00:00 -i "input_file.mp4" -q:v 0 -q:a 0 -c:v mpeg2video "output_file_h2.mpeg"


text:
Q: Kernel module to implement neighbour discovery I have a requirement to implement a kernel module to perform a neighbour descovery and output the discovered details using PRINTK. I know that there are already existent modules to implement this feature such as ARP and SEND - Secure Neighbor Discovery. Also in Linux one can use ip -6 neigh show or ip -4 neigh show to perform this.
My requirement is to locate the code segment of the kernel-module which implements the ip -6 neigh show or ip -4 neigh show feature so that I could alter it to my requirements OR utilize these modules and develop my own kernel module to display the discovered neighbor the information on the console when I type the command dmesg | tail.
My research always lead to the already defined modules within the kernel and not on self implementing tutorials or examples. (https://www.google.com/search?client=ubuntu&channel=fs&q=lldp+kernel+module&ie=utf-8&oe=utf-8#channel=fs&q=linux+neighbor+discovery+kernel+module+)
I would be really grateful if you experts would provide some assistance in this matter. MY project's success depend on this matter.
Thank you :)


text:
Q: What is the relation between UART and the tty? When I write programs for my own FPGA, I must select UART to emulate a terminal and for my FPGA design but I don't know exactly what that means.
I believe that UART is a basic serial transmission protocol, isn't it? And is that the protocol between the program and the terminal and therefore I must choose UART from my programming environment?

A: A UART (Universal Asynchronous Receiver Transmitter) is not a protocol, it's a piece of hardware capable of receiving and transmitting data over a serial interface. I presume you are selecting some design block for your FPGA design implementing an UART.


text:
Q: Python, mock that was imported with relative path Have you faced the problem, how to mock that was imported by a relative path? Python.
I don't want to use an absolute path, because all my modules are in the same folder.
More precisely:
The tested file:
from ..some_module import something   # <- the relative path

The test:
@patch('test_libs.some_path.some_module.something.method')
def test_something()
. . . .

Such a patch accepts an absolute path only, and doesn't mock the class, imported relatively.
I've googled, but unsuccessfully.

A: I worked out that the reason was not in the relative path. Sorry for the disturbance, you can close the topic.


text:
Q: Creating a Random javascript array from an HTML input field I have basic HTML form that asks for a number between 1 and 10. Based on that number I want to create a new array. For now the code shows an alert box of the new created array, but eventually it will be a table that displays the results. The current array has 10 values and I want it generate a new array randomly. I think I have it and just missing one thing or maybe a few.
function createRandomArray () {

var numOfGamesElement = document.getElementById("numOfGames");
var numOfGames = numOfGamesElement.value;

var gamesPicked [];

  const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];

let gamesPicked = boardGames[Math.floor(Math.random() * boardGames.length)];

for(let i = 0; i < numOfGames; i++){
  gamesPicked.push(i);
}
  alert(gamesPicked.join("\n"));
//createTable(gamesPicked)
}

A: One issue is you might get duplicates in your randomized gamespicked array. It might be better to shuffle the array (randomize it) and then just get the slice of X items, like this. Notice that I change the numOfGames value from a string to a number by prepending it with +
/* Randomize array in-place using Durstenfeld shuffle algorithm */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];
function createRandomArray () {
   let numOfGames = +document.getElementById("numOfGames").value || 0;
   let gamesPicked = shuffleArray(boardGames).slice(0, numOfGames)
   alert(gamesPicked.join("\n"));
}

A: You can do it using vanilla JS like this
function samples(array, length) {
    var samplesSet = new Set();
    if (array.length < length) {
        throw Error("requested length is greater than given array");
    }
    while(samplesSet.size < length) {
        samplesSet.add(array[Math.floor(Math.random() * array.length)]);
    }
    return [...samplesSet];
}
function createRandomArray () {

var numOfGamesElement = document.getElementById("numOfGames");
var numOfGames = numOfGamesElement.value;

  const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];

let gamesPicked = samples(boardGames, numOfGames);
  alert(gamesPicked.join("\n"));
//createTable(gamesPicked)
}

Or using lodash sampleSize like this
let _ = require('lodash');

function createRandomArray () {

var numOfGamesElement = document.getElementById("numOfGames");
var numOfGames = numOfGamesElement.value;

  const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];

let gamesPicked = _.sampleSize(boardGames, numOfGames);
  alert(gamesPicked.join("\n"));
//createTable(gamesPicked)
}

A: This works but does not address that the random function can pick duplicates.
<!DOCTYPE html>
<head>
<script>
function createRandomArray () {
    var numOfGamesElement = document.getElementById("numOfGames");
    var numOfGames = numOfGamesElement.value;

    const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];

    var gamePicked;
    var gamesPicked = {};
    for(let i = 0; i < numOfGames; i++){
      gamePicked = boardGames[Math.floor(Math.random() * boardGames.length)];
      gamesPicked[i] = gamePicked;
      alert(gamesPicked[i]);
    }
    // could build table here
}
</script>
</head>

<body>
<label>Number of games (1 to 10):
<input id="numOfGames">
</label>
<button onclick="createRandomArray()">Click Me</button>
</body>


text:
Q: problem with Creating textures in DirectX 12 As in the title I have problem with a simple texture in DirectX 12. It's hard for me to describe the whole thing so looking at the code will explain the situation that I'm stuck with.It gives  me a black color.
Texture:
    auto commandqueue = D3D12Core::Get().GetCommandQueue(D3D12_COMMAND_LIST_TYPE_DIRECT);
auto commandlist = commandqueue->GetCommandList();

stbi_uc* data = stbi_load(filePath.c_str(), &m_Width, &m_Height, &m_BytesPerPixel, 0);
m_TextureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
m_TextureDesc.Alignment = 0;
m_TextureDesc.Width = m_Width;
m_TextureDesc.Height = m_Height;
m_TextureDesc.DepthOrArraySize = 1;
m_TextureDesc.MipLevels = 1;
m_TextureDesc.Format = DXGI_FORMAT_R16G16B16A16_UNORM;
m_TextureDesc.SampleDesc.Count = 1;
m_TextureDesc.SampleDesc.Quality = 0;
m_TextureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
m_TextureDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

auto device = D3D12Core::Get().GetDevice();

device->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &m_TextureDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&texture));

UINT64 textureUploadBufferSize;

device->GetCopyableFootprints(&m_TextureDesc, 0, 1, 0, nullptr, nullptr, nullptr, &textureUploadBufferSize);

device->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(textureUploadBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&UplodeTexture));

subresource.pData = data;
subresource.RowPitch = m_Height * m_BytesPerPixel;
subresource.SlicePitch = subresource.RowPitch * m_Width;

UpdateSubresources(commandlist.Get(), texture, UplodeTexture,0,0,1, &subresource);

commandlist->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE));

Shader Resource View:
    auto device = D3D12Core::Get().GetDevice();

    D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
    srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
    srvDesc.Format = m_TextureDesc.Format;
    srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
    srvDesc.Texture2D.MipLevels = 1;
    device->CreateShaderResourceView(texture,&srvDesc, m_SRVHeap->GetCPUDescriptorHandleForHeapStart());

Descriptor table parameter in root signature :
 D3D12_DESCRIPTOR_RANGE  descriptorTableRanges;
descriptorTableRanges.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
descriptorTableRanges.NumDescriptors = 1;
descriptorTableRanges.BaseShaderRegister = 0;
descriptorTableRanges.RegisterSpace = 0;
descriptorTableRanges.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;

D3D12_ROOT_DESCRIPTOR_TABLE descriptorTable = {};
descriptorTable.NumDescriptorRanges = 1;
descriptorTable.pDescriptorRanges = &descriptorTableRanges;

m_RootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
m_RootParameters[1].DescriptorTable = descriptorTable;
m_RootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;

The static sampler that I gave it to root signature:
D3D12_STATIC_SAMPLER_DESC sampler = {};
sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
sampler.MipLODBias = 0;
sampler.MaxAnisotropy = 0;
sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
sampler.MinLOD = 0.0f;
sampler.MaxLOD = D3D12_FLOAT32_MAX;
sampler.ShaderRegister = 0;
sampler.RegisterSpace = 0;
sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;

And I set the descriptor table through command list:
m_SRV = m_SRVHeap->GetGPUDescriptorHandleForHeapStart();
ID3D12DescriptorHeap* heap = m_SRVHeap.Get();
commandList->SetDescriptorHeaps(1, &heap);
commandList->SetGraphicsRootDescriptorTable(1, m_SRV);

Pixel shader:
struct PixelShaderInput
{
float2 TexCoord : TEXCOORD;
float4 Color    : COLOR;
};
Texture2D tex : register(t0);
SamplerState s1 : register(s0);
float4 main(PixelShaderInput IN) : SV_TARGET
{
return tex.Sample(s1, IN.TexCoord);
}

EDIT:
I haven't enabled the GPUBasedValidation debug layer and after I enabled it it gives the following error:
D3D12 ERROR: GPU-BASED VALIDATION: Draw, Incompatible resource state: Resource: 0x0D1FFFF8:'TextureResource', Subresource Index: [0], Descriptor heap index to DescriptorTableStart: [0], Descriptor heap index FromTableStart: [0], Binding Type In Descriptor: SRV, Resource State: D3D12_RESOURCE_STATE_COPY_DEST(0x400), Index of Descriptor Range: 0, Shader Stage: PIXEL, Root Parameter Index: [1], Draw Index: [0], Shader Code: C:\DevPractice\D3D12Test\D3D12Test\src\Shaders\Pixel.hlsl(10,2-40), Asm Instruction Range: [0x60-0x8b], Asm Operand Index: [3], Command List: 0x0D385EE0:'Unnamed ID3D12GraphicsCommandList Object', SRV/UAV/CBV Descriptor Heap: 0x03F2AEC0:'Unnamed ID3D12DescriptorHeap Object', Sampler Descriptor Heap: , Pipeline State: 0x0D4A9788:'Unnamed ID3D12PipelineState Object',  [ EXECUTION ERROR #942: GPU_BASED_VALIDATION_INCOMPATIBLE_RESOURCE_STATE]


text:
Q: How to convert string into aggregated quantiles? I have a dataframe that is nested by groups. I want to convert variable 'x' from its raw value to quantile position (20%, 40%, 60%, 80%, 100% or 1, 2, 3, 4, 5).
Here is an example of the data I'm using:
df <- data.frame(x=c(1, 5, 21, 24, 43, 47, 56, 59, 68, 69, 11, 15, 25, 27, 48, 49, 51, 55, 61, 67),
                 y=c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B"))

This is what I have tried:
df$z <- aggregate(df$x, by = list(df$y), FUN = function(x) quantile(x, probs = c(0.2, 0.4, 0.6, 0.8, 1), na.rm = T))

In essence, I would like to create a new variable that looks like this:
df$z <- c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5)

A: On a grouped data.frame you can use dplyr::ntile():
library(dplyr)

df %>%
  group_by(y) %>%
  mutate(z = ntile(x, 5))

# A tibble: 20 x 3
# Groups:   y [2]
       x y         z
   <dbl> <fct> <int>
 1     1 A         1
 2     5 A         1
 3    21 A         2
 4    24 A         2
 5    43 A         3
 6    47 A         3
 7    56 A         4
 8    59 A         4
 9    68 A         5
10    69 A         5
11    11 B         1
12    15 B         1
13    25 B         2
14    27 B         2
15    48 B         3
16    49 B         3
17    51 B         4
18    55 B         4
19    61 B         5
20    67 B         5

A: We can use cut with breaks as the quantile
library(dplyr)
df %>%
   group_by(y) %>%
   mutate(z = as.integer(cut(x, breaks = c(-Inf,
       quantile(x, probs = c(0.2, 0.4, 0.6, 0.8, 1), na.rm = TRUE)))))
# A tibble: 20 x 3
# Groups:   y [2]
#       x y         z
#   <dbl> <fct> <int>
# 1     1 A         1
# 2     5 A         1
# 3    21 A         2
# 4    24 A         2
# 5    43 A         3
# 6    47 A         3
# 7    56 A         4
# 8    59 A         4
# 9    68 A         5
#10    69 A         5
#11    11 B         1
#12    15 B         1
#13    25 B         2
#14    27 B         2
#15    48 B         3
#16    49 B         3
#17    51 B         4
#18    55 B         4
#19    61 B         5
#20    67 B         5

Or using base R with ave
with(df, ave(x, y, FUN = function(u) as.integer(cut(u, breaks = c(-Inf,
          quantile(u, probs = c(0.2, 0.4, 0.6, 0.8, 1), na.rm = TRUE))))))
#[1] 1 1 2 2 3 3 4 4 5 5 1 1 2 2 3 3 4 4 5 5

NOTE: Answering based on the quantile question OP asked


text:
Q: Why does SIGTSTP exist when there is already SIGSTOP? I always thought that Ctrl-Z in a terminal (while in canonical mode) generates SIGSTOP, but according to man 3 tcsetattr, it generates SIGTSTP instead. However, in both cases, SIGCONT is used to resume the stopped processes.
What is the reason that Ctrl-Z does not just generate SIGSTOP? Is there a case in which it is useful for a program to handle SIGTSTP differently than SIGSTOP?

A: Like KILL, STOP can't be caught, blocked, or ignored: it always stops the receiving process. TSTP on the other hand can be ignored or handled in a different way; for example, shells, and Emacs, set up TSTP handlers to deal with CtrlZ themselves. This behaviour in shells ensures that pressing CtrlZ is always safe, and won't get you stuck in a terminal with a stopped process and no way of resuming it.


text:
Q: the tab is not loaded primefaces I have a tabview that contains two tabs, the first tab contains a datable and the second one contains google map. The problem is that once I moved from the first tab to the second, the content is not loaded (the map is not displayed). Im working with primefaces 4.
Here is my code:
this the first tab that contains the datatable
<h:form>

        <h:form id="a" >
            <h:panelGrid columns="1" cellpadding="5">

            </h:panelGrid>

            <p:dataTable var="property" value="#{propertybean.propertyList}" id="AjoutTab" rows="10"
                         paginator="true"
                         paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                         rowsPerPageTemplate="5,10,15"
                         widgetVar="propsTable"
                         emptyMessage="No property found with given criteria"
                         editable="true">
                <f:facet name="header">

                        <h:outputText value="Search all fields:" />

                </f:facet>

                        <f:facet name="output"><h:outputText value="#{property.propId}" /></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"><h:outputText value="#{property.propName}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"> <h:outputText value="#{property.propValidfromDate}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"> <h:outputText value="#{property.propValidtoDate}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"><h:outputText value="#{property.propCountry}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"><h:outputText value="#{property.propStreetname}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"> <h:outputText value="#{property.propStreetnb}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"> <h:outputText value="#{property.propPostcode}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"> <h:outputText value="#{property.propLength}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"><h:outputText value="#{property.propWidth}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"> <h:outputText value="#{property.propStatus}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"> <h:outputText value="#{property.propArea}"/></f:facet>
                        <f:facet name="input">
</f:facet>

                        <f:facet name="output"> <h:outputText value="#{property.propComment}"/></f:facet>
                        <f:facet name="input">
</f:facet>

        </h:form>

this is the second tab that contains a google map:

Map

                            <h:form prependId="false" id="idformshow">

                            </h:form>

Layer Selection

                                            <button class="btn btn-box-tool" data-widget="collapse"></button>

        </h:form>

The method onTabChanged contains a message:
public void onTabChanged(TabChangeEvent e){
    System.out.println("Success,tab changed");
    FacesContext.getCurrentInstance().addMessage("Message5", new FacesMessage("Tab With Index :: "+e.getTab().getTitle()+" Is Changed"));
}

I'd be grateful if anyone can help me


text:
Q: How to memoize custom React hook const useSomeHook = ({number}) => {
  const [newNumber, setNewNumber] = useState(0)

  useEffect(() => {
    setNewNumber(number + 1)
  }, [number])
}

const SomeComponent = ({number, value, ...restProps}) => {

  useSomeHook({number})

  return <div>{number}</div>
}

Let's imagine I have this case. Each time when in SomeComponent come some new prop, it will call my useSomeHook hook, but I want to prevent it. I want to call it only when the number is changed (memoize it). In other cases, don't touch it. But I haven't found any solving with this case. Could you help me solve this issue?

A: You can not prevent calling hook, this will lead to invariant violation error. Every hook in component should be executed on each render. You should rely on useEffect dependencies argument to run conditional code only if value changes.


text:
Q: Angular 5 - Get current time of video I have HTML5 video in my component and want to get the current video time, while it is playing.
Here is what I've tried and it only gets the time once initially.
Component TS:
export class RegisterComponent implements OnInit, OnChanges {

  @ViewChild('videoPlayer')
  private videoPlayer: ElementRef;

  constructor() { }

  ngOnInit() {
    // only logs once
    console.log(this.videoPlayer.nativeElement.currentTime);
  }

  ngOnChanges() {
    // only logs once
    console.log(this.videoPlayer.nativeElement.currentTime);
  }
}

Component HTML:
<video #videoPlayer [autoplay]="true" class="video">
    <source src="assets/videos/temp.mp4" type="video/mp4"/>
      Browser not supported
</video>

A: You can bind to the timeupdate event on the video tag set a variable to the value of the currentTime property of the video element.
Component TS:
export class RegisterComponent  {

  currentTime: number;

  setCurrentTime(data) {
     this.currentTime = data.target.currentTime;
  }
}

Component HTML:
<video [autoplay]="true" (timeupdate)="setCurrentTime($event)" class="video">
    <source src="assets/videos/temp.mp4" type="video/mp4"/>
      Browser not supported
</video>

A: HTML
<video [autoplay]="true" (timeupdate)="onTimeUpdate($event)" class="video">
    <source src="assets/videos/temp.mp4" type="video/mp4"/>
      Browser not supported
</video>

TS
public onTimeUpdate(value){
    console.log(value.target.currentTime);
}


text:
Q: Why universal elements is special case of universal arrow? I'm reading Mac Lane's Categories for the working mathematician, and it says "The notion 'universal element' is a special case of the notion 'universal arrow'. Indeed, if * is the set with only one point, then any element $e \in Hr$ can be regarded as an arrow $e \colon * \rightarrow Hr$ in Ens."
My questions are,
why $e$ can be regarded that way?
What is Ens?
In the book, it says that Ens is the category of all sets and functions within a set $V$, but I can't get it. Can you give a more precise description of such a category?


text:
Q: How to change the value of a div dynamically on each click I have got a task to create a game. For that I need some help...
How can I change the value of a div by clicking on it?

Two

js code :
 $( ".block1" ).click(function() {
          $( "#one" ).css('display','block');
          $( "#two" ).css('display','none');
          $( "#three" ).css('display','none');
          $( "#four" ).css('display','none');
           });

DEMO

A: Use .text to change the text
$('#one').text('New value')

You can use the this context inside the click event to change the text of currently clicked div.
 $(".block1").click(function () {
      $(this).text("New value")
  });

Check Fiddle

A: $( ".block1" ).click(function() {
$(this).html("Div Content")
}

A: Approach - 1
$("#one")[0].textContent = "test";

Approach - 2
$("#one").prop('textContent', "test");

A: Assuming you are using jQuery
You can use .text() to change or get the text inside the div
$("#one").text('Some new text');

You can use .html() to change or get the html inside the div
$("#one").html('
Some new html
');

For form elements such as  you can use .val()
$("#one").val('1');


text:
Q: redirect() Not Actually Redirecting (Routes for Pylons) I am constructing a table of routes in my Pylons app.  I can't get redirect() to work the way that it should work.  I'm not sure what I'm doing wrong.
Here is an example of redirect() usage from the Routes documentation:
map.redirect("/home/index", "/", _redirect_code="301 Moved Permanently")

Here is what appears in my routing.py file:
map.redirect("/view", "/", _redirect_code="301 Moved Permanently")

Here is a route using redirect() that appears at the end of my routing.py file:
map.redirect('/*(url)/', '/{url}', _redirect_code="301 Moved Permanently")

This route works just fine, so I know that redirect() is present and functional.  Therefore, I am doing something wrong in the /view redirect.  I know this because when I point my browser at /view, I get the 404 page instead of getting redirected.  Going to / works just fine, so I don't think that the problem is there, either.  I think that redirect() in Routes is a great idea and I would like to be able to use it as intended, but I'm not sure what I'm doing wrong here.
ETA @jasonjs: I believe that no other route matches.  When I try to access /view and then look at Paster's output, here's what I get:
21:22:26,276 DEBUG [routes.middleware] No route matched for GET /view

which seems pretty conclusive to me.  I should mention that there is a route that matches POST requests to /view:
map.connect('/view', controller='view', action='search', conditions=dict(method=['POST'])

That route also works correctly, and I have it listed earlier in routing.py so that it tries to match that before it tries to match the /view[GET] route.

A: That syntax works, so there must be something else going on.
Routes is sensitive to order. Is there another route above the redirect that would match /view to a controller that would return a 404?
Routes is also sensitive to trailing slashes. Did you accidentally type a trailing slash in the browser but not in the route, or vice versa?
Finally, in development.ini, if you set level = DEBUG under [logger_routes], you can then check the log messages after visiting /view to see what was matched.
ETA: I just tried putting a POST-matching rule before a redirect for the same path, and it worked as expected. Are you on the latest Routes version (1.11)? Otherwise I don't have anything else for you, not being able to see code. It may just be a matter of starting with a barebones test case and building up until it breaks, or taking things away until it works...


text:
Q: Perl - Is there a way to display notifications with some textbox? Here is my problem : I'm trying to make skype more interactive with my gnome desktop environment. So I want to use Perl to do that. Is there a way, using libnotify, to display a textbox (a field I can fill or type in) ?

A: Gnome provides zenity to create dialogs from scripts:
zenity --entry --text "foo" --entry-text "bar"

KDE provides kdialog. Older Gnome provided gdialog. There is also xdialog.


text:
Q: Teams Popout chat through coding I want to open the teams chat as pop out chat instead of opening in the chat window. When I used the below code through SPFx, I am able to open the chat window
window.open('MSTeams:/l/chat/0/0?users=' + userID, 'popup', 'width=600,height=600,resizable=yes,fullscreen=no');
return false;

but I want to open the chat window as pop out chat.
I tried
MSTeams:/l/chat/pop/1/0?users=useremail

and
MSTeams:/l/chat/1/1?users=useremail

but its not working please help me on this.

A: Teams has inbuilt pop out chat feature, there is no official sample code or support available for custom apps. I've raised a Feature request in backlog item.


text:
Q: Fetch rectangle (line segments)co ordinates from pdf using itextpdf I want to get the line segments co ordinates total & line segments should come. I want to read the pdf table co ordinates so that I can fetch the text inside the co ordinates? I am getting only 6 line segments. What about the 7 line segment?
I am using this program to read the line segments from tables(rectangle)
iText : image on PDF only if the position is blank
output is :

 50 50  150 50
150 50  150 150
150 150 50  150
150 50  200 50
200 50  200 150
200 150 150 150

A: The cause of this problem is that iText reports a rectangle drawing instruction as subpath containing three explicit lines (bottom, right, top) and sets its Closed property implying the fourth line (left):
public void rectangle(float x, float y, float w, float h) {
    moveTo(x, y);
    lineTo(x + w, y);
    lineTo(x + w, y + h);
    lineTo(x, y + h);
    closeSubpath();
}

(com.itextpdf.kernel.geom.Path.rectangle(float, float, float, float))
The FreeSpaceFinder in the referenced answer, though, only considers the explicit subpath segments, not the implied one. Thus, for your two rectangles you only get 6 lines instead of the expected 8 lines.
To also get implied closing lines for each Subpath subpath, you have to check whether subpath.isClosed(), and if it is, you have to determine the end point of the last IShape segment in subpath.getSegments() and the start point of the first IShape segment and add a line connecting those points.


text:
Q: RecyclerView.ViewHolder communicating with Fragment I need to find a way for a recyclerview to tell a fragment when a certain type of post is shown on the screen. I'm having trouble developing a generalized method for determining if and how many video posts are shown on the screen at any given point in time. What I want is for the fragment to at least know when a video post (along with their state) is on the screen so that the activity can become unlocked from portrait mode so that on rotation the VideoView takes up the entire screen instead of a small part of it (assuming the video is playing). Given the situation where there is more than one video post shown, when one is started while the other is playing, I want the one playing to stop and the other video post to start playing. The logic for controlling video playback is in the viewholder class. How would I go about setting up this functionality?

A: Using a interface was the way to go. I also looked up EventBus, but apparently those types of mechanisms are used for when you have one component sending messages to multiple recipients (as opposed to when you implement a listener, which is for a one to one connection).


text:
Q: Why doesn't the LED turn off? I have a program (copied below) that has an alarm that starts in 10 seconds, which starts a LED that blinks every two seconds. I would like to push a button that turns off the alarm / LED. The LED blinks as intended but does not turn off when I push the button. Any idea why? Code below:
#include <Time.h>
#include <TimeAlarms.h>
#define buttonPin 2 // assigns pin 2 as buttonPin
#define ledPin 13 // assigns pin 13 as ledPin

int buttonState; // variable for reading the pushbutton status
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers

void setup() {
  Serial.begin(9600); // start Serial Monitor
  setTime(0, 0, 0, 1, 1, 2018); // set time to 00:00:00 Jan 1 2018
  Alarm.alarmRepeat(0, 0, 10, DailyAlarm); // Alarm triggered in 10 sec
  pinMode(ledPin, OUTPUT); // assigns ledPin as led output pin.
  pinMode(buttonPin, INPUT); // assigns buttonPin as input pin
  // digitalWrite(ledPin, ledState); // LED is off initially
}

void loop() {
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = HIGH;
      Serial.print(buttonState);
    }
  }
}

void DailyAlarm() {
  Serial.println("Alarm");
  while (buttonState == LOW) {
    blink(2000); // blink every 2s
  }
}

void blink(int period) {
  digitalWrite(ledPin, HIGH);
  delay(period / 2);
  digitalWrite(ledPin, LOW);
  delay(period / 2);
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

A: int buttonState; // variable for reading the pushbutton status

You haven't initialized the button state
Try
boolean buttonState = LOW

And Don't mix integers and booleans
use this
boolean lastButtonState = LOW;

instead of
int lastButtonState = LOW;


text:
Q: Change the appearance of Android Search Dialog I am trying to implement search functionality into an android app using the Search Dialog. After following the documentation, I got this search dialog when pressing the search button in my app.

As you can see, the search dialog is too small( the app bar can be seen below it), it is not centered, and contains the app icon near the back button.
The Search Dialog showed in the guide is centered vertically in the app bar and doesn't have the app icon near the back button, which is what I want to do for my search dialog as well. But I can't seem to find any resource on how to do it. Can anyone help me out?
Thanks in advance!
Edit: Here is the code that enables the Search Dialog
MainActivity.kt
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val root = binding.root
        setContentView(root)
        //Setup the app bar
        setSupportActionBar(binding.toolbar);

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val inflater = menuInflater;
        inflater.inflate(R.menu.app_bar_menu, menu)
        return true;
    }

    override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
        R.id.action_search -> {
            onSearchRequested()
            true
        }
        else -> {
            super.onOptionsItemSelected(item)
        }
    }
}

searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="@string/search_hint"
    android:label="@string/app_name">

</searchable>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:title="@string/app_name" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: Using the method that you want for create a search dialog, this is the most similar aspect that it can achieve:
https://i.stack.imgur.com/hwTlF.png
This is the code that I implemented:
MainActivity.class code:
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@SuppressLint("ResourceType")
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(true);
    searchView.setIconified(false);

    //Here you can set the parameters of the search view

    return true;
}

I created a menu resource file called options_menu.xml and that's the code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/search"
    android:title="title"
    android:icon="@drawable/search_icon"
    app:showAsAction="collapseActionView|ifRoom"
    app:actionViewClass="android.widget.SearchView" />

</menu>

And the searchable xml file called search.xml
<?xml version="1.0" encoding="utf-8"?>
<Searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="Your hint"
    android:label="Label text">
</Searchable>

I created the icon of the menu in the drawable folder but you can change to other icon if you want.
Also I leave several links to all the customizations that you can add to the searchView:
https://developer.android.com/guide/topics/search/searchable-config
https://developer.android.com/reference/android/widget/SearchView
I hope this is the right solution for you.

A: I made a different search method, I used the Android Studio search view,
that's the main activity code:
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    MenuItem item = menu.findItem(R.id.mySearchButton);
    SearchView searchView = (SearchView)item.getActionView();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

    return super.onCreateOptionsMenu(menu);
}

You have to create an Android Resource File, select resource type "menu", and call it as you want, after that, add this item:
    <item android:id="@+id/mySearchButton"
    android:title="Button"
    android:icon="@drawable/search_icon"
    app:actionViewClass="android.widget.SearchView"
    app:showAsAction="always"/>

This code worked for me, images here:
https://i.stack.imgur.com/XNRZy.png
https://i.stack.imgur.com/hUt4x.png
I hope it works for you aswell.


text:
Q: chmod throws missing operand on 764, OK on 664 Having set everything in my project to 777 (rwxrwxrwx) for debugging purposes, I wanted to dial down the openness and set the directories (not the files) in the root folder to 664 (rw-rw-r--).
To do this I used (from How to list folders using bash commands?):
chmod 664 -- */

This worked as expected. Then I realized I needed the execution bit on directories to enter them. So I tried:
chmod 764 -- */

But that threw a missing operand after "764" error.
I can change the permissions by hand (chmod 764 <dir-name>) and there aren't that many directories so it's not a big problem, but I'd like to understand.
Why can't I use chmod 764 */ to set the directories in my current path to rwxrw-r--?

A: This would make sense if you have set shell glob options so that

*

** includes names beginning with ., and

*a wildcard that doesn't match anything just disappears, rather than persisting as itself.
(E.g., if you don't have any files whose names begin with foo,
the command echo foo* prints a blank line rather than printing foo* literally.)

If the above are true, then the first command set . to mode 664,
which means that you didn't have permission to read . when you issued the second command.
So the */ couldn't be expanded, and chmod 764 -- */ became chmod 764 --.


text:
Q: Pyspark Py4JJavaError enter image description here
Getting this error on - > sc = pyspark.SparkContext(appName="Pi") line
import findspark
findspark.init()
import pyspark
import random
pyspark.SparkContext(appName="Pi")


text:
Q: How to hide default 'X' close button inside magnific popup? I have used Magnific-popup in my jsp to display few messages to the user.
The code I have used to open magnific popup is as below:
$.magnificPopup.open({
  items: {
    type: 'inline',
    src: '#idOfSomeDivInPage'
  },
  focus: '#someButtonId',
  closeOnBgClick: false,
  enableEscapeKey: false
}, 0);

Is there a way to delete/hide the 'X' button present on top right top corner of magnific popup by using jquery and css?

A: You could use showCloseBtn config as mentioned here in doc.
showCloseBtn

Controls whether the close button will be displayed or not.

$.magnificPopup.open({
  items: {
    type: 'inline',
    src: '#idOfSomeDivInPage'
  },
  focus: '#someButtonId',
  closeOnBgClick: false,
  enableEscapeKey: false,
  showCloseBtn:false
}, 0);

Please check here with working codepen

A: As a workaround.
Please add following line in your code where you create your popup.
$('.mfp-close').css('display','none');

Hope this solution works.


text:
Q: one thread takes 2 sec , 10 threads take 16-18 secs. why? Each of my threads sleep for 2000 ms , and i have 10 such threads , so i expected the total sleep time to be atleast 20 secs , but its only coming up in between 16-18 secs. Sorry if i'm asking something that has already been asked . Here's what i have so far :
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MyThreadPoolApp {
    public static void main(String[] args) {
        long execTime = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(1);
        ExecutorService executor = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {
            executor.submit(new Task());
        }
        System.out.println("threads submitted and waiting execution");

        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
        }
        execTime = System.currentTimeMillis() - execTime;
        System.out.format("%d threads finished execution \n",Task.getCount());
        System.out.println("thread time : " + Task.getTime());
        System.out.println("main time : " + execTime);

    }
}

Where Task is :
public class Task implements Runnable {

    private static long totalTime;
    private static int count;
    public static long getTime(){ return totalTime; }
    public static int getCount(){ return count; }

    public void run() {
        count++;
        long startTime = System.currentTimeMillis();
        try {
            Thread.sleep(2000);
            totalTime += System.currentTimeMillis() - startTime;
        } catch (InterruptedException e) {}
    }
}

My output :
threads submitted and waiting execution
10 threads finished execution
thread time : 18001
main time : 2020

A: Because you are messing with concurrent update of totalTime by various threads.
Try this:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MyThreadPoolApp {
    public static void main(String[] args) {
        long execTime = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(1);
        ExecutorService executor = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {
            executor.submit(new Task());
        }
        System.out.println("threads submitted and waiting execution");

        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
        }
        execTime = System.currentTimeMillis() - execTime;
        System.out.format("%d threads finished execution \n",Task.getCount());
        System.out.println("thread time : " + Task.getTime());
        System.out.println("main time : " + execTime);
    }
}

class Task implements Runnable {

    private static long totalTime;
    private static int count;
    public static long getTime(){
        synchronized(Task.class){
            return totalTime;
        }
    }
    private static void addTime(long time){
        synchronized(Task.class){
            totalTime = totalTime + time;
        }
    }
    public static int getCount(){ return count; }

    public void run() {
        count++;
        long startTime = System.currentTimeMillis();
        try {
            Thread.sleep(2000);
            addTime(System.currentTimeMillis() - startTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

EDIT
As you wish, synchronize inside run() method:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MyThreadPoolApp {
    public static void main(String[] args) {
        long execTime = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(1);
        ExecutorService executor = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {
            executor.submit(new Task());
        }
        System.out.println("threads submitted and waiting execution");

        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
        }
        execTime = System.currentTimeMillis() - execTime;
        System.out.format("%d threads finished execution \n",Task.getCount());
        System.out.println("thread time : " + Task.getTime());
        System.out.println("main time : " + execTime);
    }
}

class Task implements Runnable {

    private static long totalTime;
    private static int count;
    public static long getTime(){
        synchronized(Task.class){
            return totalTime;
        }
    }
    public static int getCount(){ return count; }

    public void run() {
        count++;
        long startTime = System.currentTimeMillis();
        try {
            Thread.sleep(2000);
            synchronized(Task.class){
                totalTime += System.currentTimeMillis() - startTime;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
Q: Wrong result using arraycopy I'm trying to copy two Byte arrays into another. The problem is that the first element of the result Byte is strange, I get 0xFFFFFF80 instead of 0x80.
the code I'm using is:
    this.IC_SUBMIT_APDU = new byte[13];
    byte[] prefix = {
        (byte) 0x80,
        (byte) 0x20,
        (byte) 0x07,
        (byte) 0x00,
        (byte) 0x08
    };
    System.arraycopy(prefix , 0, this.IC_SUBMIT_APDU, 0, prefix.length);

    for(int i=0; i<this.IC_SUBMIT_APDU.length ; i++)
        System.out.println("" + Integer.toHexString(this.IC_SUBMIT_APDU[i]));

when I give it this argument:
{
    (byte) 0x41,
    (byte) 0x43,
    (byte) 0x4F,
    (byte) 0x53,
    (byte) 0x54,
    (byte) 0x45,
    (byte) 0x53,
    (byte) 0x54
}

it produces the following result:
ffffff80
20
7
0
8
0
0
0
0
0
0
0
0

WHy do I get that  0xFFFFFF80 ? am I not supposed to get 0x80 ??

A: 0xFFFFFF80 is more than one byte. The 0xFFFFFF portion is probably from  a different print statement that you have not shown.

A: Nothing to do with System.arrayCopy.
In fact, System.out.println(Integer.toHexString((byte) 0x80)); will also print ffffff80.
You have an arithmetic overflow when casting hex 0x80 as byte, since its decimal value is 128, i.e. 1 more than byte's capacity (Byte.MAX_VALUE, or 127) and overflows to -128.
Note that in turn, Integer.toHexString returns the representation of an unsigned integer, hence the additional overflow.

A: your are copying correctly the only 5 elements present in ic_submit_apdu_prefix ...
hint: 0x80 with 8 bits is -128 (2 complement)

0xffffff80 = -128
0x20 = 32
7
0
8
0

the rest is zero. (default initial primitive value)


text:
Q: Event for resize stopped Is there an event that tells me when the user has stopped resizing by letting go of the mouse button?  I'm looking at $(window).resize, and it's firing for every pixel movement.  I just need to know when they've stopped.

A: No, but you can defer the event handler if you want:
function onResize(){ ... }

var timer;

$(window).bind('resize', function(){
    if (timer) {
        clearTimeout(timer);
    }

    timer = setTimeout(onResize, 100);
});

This will make it fire 100ms after the user has stopped resizing.

A: You can try this :
function rsizeItems()
{ }

var tOut = false;
var milSec = 500;
$(window).resize(function(){
 if(tOut !== false)
    clearTimeout(tOut);
 tOut = setTimeout(rsizeItems, milSec);
});