text:
Q: requests python lib adding in Accept header so I have made a request to a server with pythons request library. The code looks like this (it uses an adapter so it needs to match a certain pattern)
def getRequest(self, url, header):
    """
    implementation of a get request
    """

    conn = requests.get(url,  headers=header)
    newBody = conn.content
    newHeader = conn.headers
    newHeader['status'] = conn.status_code

    response  = {"Headers" : newHeader, "Body" : newBody.decode('utf-8')}

    self._huddleErrors.handleResponseError(response)
    return response

the header parameter I am parsing in is this
{'Authorization': 'OAuth2 handsOffMyToken', 'Accept': 'application/vnd.huddle.data+json'}

however I am getting an xml response back from the server. After checking fiddler I see the request being sent is:
Accept-Encoding: identity
Accept: */*
Host: api.huddle.dev
Authorization: OAuth2 HandsOffMyToken
Accept: application/vnd.huddle.data+json
Accept-Encoding: gzip, deflate, compress
User-Agent: python-requests/1.2.3 CPython/3.3.2 Windows/2008ServerR2

As we can see there are 2 Accept Headers! The requests library is adding in this Accept:* / * header which is throwing off the server. Does anyone know how I can stop this?

A: As stated in comments it seems this is a problem with the requests library in 3.3. In requests there are default headers (which can be found in the utils folder). When you don't specify your own headers these default headers are used. However if you specify your own headers instead requests tries to merge the headers together to make sure you have all the headers you need.
The problem shows its self in  def request() method in sessions.py. Instead of merging all the headers it puts in its headers and then chucks in yours. For now I have just done the dirty hack of removing the accept header from the default headers found in util


text:
Q: Issues adding IP config to Existing vm's NIC I have a VM NIC that has an IP(Primary) added to it. I am trying to find a way how I can add more IP's to the NIC.I am using a piece of code and it throws an error saying.
The final solution should actually give me to add 4 ip additonal to the NIC and update the first Ip which is primary and also update dns ip to the NIC.
Error Thrown:
nic1-test-ipConfig cannot be deleted. Deletion and renaming of primary IP Configuration is not supported StatusCode: 400 ReasonPhrase: Bad Request ErrorCode: IpConfigDeleteNotSupported ErrorMessage: IP Configuration ProdNuma1-nic1-test-ipConfig cannot be deleted.
$vnet = Get-AzVirtualNetwork -Name "vnet" -ResourceGroupName "rg"
$subnet1 = Get-AzVirtualNetworkSubnetConfig -Name "sn" -VirtualNetwork $vnet
$location="westcentralus"
$vm="test"

#Adding IP's to ->NIC1
$ipc11 = New-AzNetworkInterfaceIpConfig -Name "ipconfig1" -PrivateIpAddress "10.64.13.10" -Primary -Subnet $subnet1
$ipc12 = New-AzNetworkInterfaceIpConfig -Name "ipconfig2" -PrivateIpAddress "10.64.13.11" -Subnet $subnet1
$ipc13 = New-AzNetworkInterfaceIpConfig -Name "ipconfig3" -PrivateIpAddress "10.64.13.12" -Subnet $subnet1
$ipc14 = New-AzNetworkInterfaceIpConfig -Name "ipconfig4" -PrivateIpAddress "10.64.13.13" -Subnet $subnet1
$ipc15 = New-AzNetworkInterfaceIpConfig -Name "ipconfig5" -PrivateIpAddress "10.64.13.14" -Subnet $subnet1

$NIC1 = New-AzNetworkInterface -Name "nic1-test" -ResourceGroupName "rg" -force -Location $location -IpConfiguration $ipc12,$ipc13,$ipc14,$ipc15 -DnsServer "10.64.2.00","10.64.0.01"

A: Since the NIC already exists, you should be updating ipconfig1 with Set-AzNetworkInterfaceIpConfig, then adding the others with Add-AzNetworkInterfaceIpConfig. Then you can update the NIC with Set-AzNetworkInterface.
$vnet = Get-AzVirtualNetwork -Name "vnet" -ResourceGroupName "rg"
$subnet1 = Get-AzVirtualNetworkSubnetConfig -Name "sn" -VirtualNetwork $vnet

$vm = Get-AzVM -Name "vm" -ResourceGroupName "rg"

$nicName = $vm.NetworkProfile.NetworkInterfaces[0].Id.Split("/")[-1]

$nic = Get-AzNetworkInterface -Name $nicName -ResourceGroupName "rg"

$nic | Set-AzNetworkInterfaceIpConfig -Name "ipconfig1" -PrivateIpAddress "10.64.13.10" -Primary -Subnet $subnet1
$nic | Add-AzNetworkInterfaceIpConfig -Name "ipconfig2" -PrivateIpAddress "10.64.13.11" -Subnet $subnet1
$nic | Add-AzNetworkInterfaceIpConfig -Name "ipconfig3" -PrivateIpAddress "10.64.13.12" -Subnet $subnet1
$nic | Add-AzNetworkInterfaceIpConfig -Name "ipconfig4" -PrivateIpAddress "10.64.13.13" -Subnet $subnet1
$nic | Add-AzNetworkInterfaceIpConfig -Name "ipconfig5" -PrivateIpAddress "10.64.13.14" -Subnet $subnet1

$nic | Set-AzNetworkInterface

If you have many NIC IP configurations to add, you could use an array of hashtables and make use of splatting. See about_Splatting for more information.
$secondaryIpConfigs = @(
    @{
        Name             = "ipconfig1"
        PrivateIpAddress = "10.64.13.10"
        Subnet           = $subnet1
        Primary          = $true
    },
    @{
        Name             = "ipconfig2"
        PrivateIpAddress = "10.64.13.11"
        Subnet           = $subnet1
    },
    @{
        Name             = "ipconfig3"
        PrivateIpAddress = "10.64.13.12"
        Subnet           = $subnet1
    },
    @{
        Name             = "ipconfig4"
        PrivateIpAddress = "10.64.13.13"
        Subnet           = $subnet1
    },
    @{
        Name             = "ipconfig5"
        PrivateIpAddress = "10.64.13.14"
        Subnet           = $subnet1
    }
)

foreach ($ipconfig in $secondaryIpConfigs) {
    $nic | Add-AzNetworkInterfaceIpConfig @ipconfig
}

$nic | Set-AzNetworkInterface

However, Add-AzNetworkInterfaceIpConfig will throw an error if the ipconfig already exists. You can use Get-AzNetworkInterfaceIpConfig to first check if the ipconfig exists, and add/update accordingly. To make sure the program doesn't throw an error immediately if an ipconfig is not found, we can use -ErrorAction SilentlyContinue.
foreach ($ipconfig in $secondaryIpConfigs) {

    if ($null -eq (Get-AzNetworkInterfaceIpConfig `
                -Name $ipconfig.Name `
                -NetworkInterface $nic `
                -ErrorAction SilentlyContinue)) {

        $nic | Add-AzNetworkInterfaceIpConfig @ipconfig
    }
    else {
        $nic | Set-AzNetworkInterfaceIpConfig @ipconfig
    }
}

$nic | Set-AzNetworkInterface

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I fix this ParseException error with NOT IN clause subquery? I am running this query through beeline
select * from sales.inventory

where customer not in
(select id
from sales.local);

This query gives me the next error:
Error: Error while compiling statement: FAILED: ParseException line 4:1 cannot recognize input near '(' 'select' 'id' in expression specification
Could anyone help me? Thanks!!


text:
Q: How can I Setup overloaded method invocations in Moq? I'm trying to mock a mapping interface IMapper:
public interface IMapper<TFoo, TBar> {
    TBar Map(TFoo foo);
    TFoo Map(TBar bar);
}

In my test, I'm setting the mock mapper up to expect an invocation of each (around an NHibernate update operation):
//...
_mapperMock.Setup(m => m.Map(fooMock.Object)).Returns(barMock.Object);
_mapperMock.Setup(m => m.Map(barMock.Object)).Returns(fooMock.Object);
//...

However, when the second Map invocation is made, the mapper mock throws because it is only expecting a single invocation.
Watching the mapper mock during setup at runtime, I can look see the Map(TFoo foo) overload get registered, and then see it get replaced when the Map(TBar bar) overload is set up.
Is this a problem with the way Moq handles setup, or is there a different syntax I need to use in this case?
EDIT
Here is the actual instantiation code from the test constructor:
public class TestClass {
    private readonly MockRepository _repository = new MockRepository(MockBehavior.Strict);

    public TestClass() {
        //...
        _mapperMock = _repository.Create
            <IMapper<RequestData.Foo, ResponseData.Bar>>();
        //...
     }
}

EDIT 2
Here is a complete failing test case:
public interface IMapper<TFoo, TBar> {
    TFoo Map(TBar bar);
    TBar Map(TFoo foo);
}

public class Foo {
    public override int GetHashCode() {
        // return base.GetHashCode();
        return 1;
    }
}

public class Bar {
    public override int GetHashCode() {
        // return base.GetHashCode();
        return 2;
    }
}

[Test]
public void TestIt()
{
    // Arrange
    var _mapperMock = new Mock<IMapper<Foo, Bar>>(MockBehavior.Strict);
    var fooMock = new Mock<Foo>();
    var barMock = new Mock<Bar>();

    _mapperMock.Setup(m => m.Map(fooMock.Object)).Returns(barMock.Object);
    _mapperMock.Setup(m => m.Map(barMock.Object)).Returns(fooMock.Object);

    // Act - breaks on first line below this comment
    var bar = _mapperMock.Object.Map(fooMock.Object);
    var foo = _mapperMock.Object.Map(barMock.Object);

    // Assert
    _mapperMock.Verify(x => x.Map(fooMock.Object), Times.Once());
    _mapperMock.Verify(x => x.Map(barMock.Object), Times.Once());
}

If I comment out the GetHashCode() override on either Foo or Bar, or on both, the test case passes.  Or, if I don't use Mocks of Foo and Bar, the test case passes.
EDIT 3
I opened Moq Issue 347 against this problem, with more detailed test cases.

A: Not sure what your Foo and Bar classes look like, but this test passes for me (Moq 4.0.10827.0, which is the newest one in NuGet)
using Moq;
using NUnit.Framework;

namespace ConsoleApplication1
{
    [TestFixture]
    public class Tests
    {
        [Test]
        public void TestIt()
        {
            // Arrange
            var _mapperMock = new Mock<IMapper<Foo, Bar>>();
            var fooMock = new Mock<Foo>();
            var barMock = new Mock<Bar>();

            _mapperMock.Setup(m => m.Map(fooMock.Object)).Returns(barMock.Object);
            _mapperMock.Setup(m => m.Map(barMock.Object)).Returns(fooMock.Object);

            // Act
            var bar = _mapperMock.Object.Map(fooMock.Object);
            var foo = _mapperMock.Object.Map(barMock.Object);

            // Assert
            Assert.AreSame(bar, barMock.Object);
            Assert.AreSame(foo, fooMock.Object);

            _mapperMock.Verify(x => x.Map(fooMock.Object), Times.Once());
            _mapperMock.Verify(x => x.Map(barMock.Object), Times.Once());
        }
    }

    public class Bar
    {
    }

    public class Foo
    {
    }
}


text:
Q: Chat Bot, last part Just one last part remaining in the ChatBot. I need to figure out a way to modify the chatbot class so
that it occasionally (say, 30% of the time) returns a randomly-‐generated standard reply to user input one  of at least five  possible replies,  like "LOL", "OMG", "You  don't say", "Really?", or "I see".
Edit: Applied recommended changes:
import java.util.Random;
import java.util.Scanner;
public class ChatBot
{
private int responseCount = 0;
public String getResponse(String value)
{
    String X = longestWord(value);
    this.responseCount++;
    if (responseCount == 10)
    {
        return "Sorry, but our time is up. I can't talk with you any longer.";
    }
    if (value.contains("you"))
    {
        return "I'm not important. Let's talk about you instead.";
    }

    else if (X.length() <= 3)
    {
        return "Maybe we should move on. Is there anything else you would like to talk about?";
    }
    else if (X.length() == 4)
    {
        return "Tell me more about " + X;
    }

    else if (X.length() == 5)
    {
        return "Why do you think " + X + " is important?";
    }
    else if (X.length() <=9)
    {
    return "Now we are getting somewhere. How does " + X + " affect you the most?";
    }

    return getRandomResponse();
}

public String longestWord(String value){
    Scanner input = new Scanner (value);
    String longest = new String();
    longest = "";

    while (input.hasNext())
    {
        String temp = input.next();
        if(temp.length() > longest.length())
        {
            longest = temp;
        }
    }
    return longest;
}

private String getRandomResponse()
{

String [] responses = {"OMG", "LOL", "You don't say", "Really?", "I See"};

return responses [(int)(Math.random() * responses.length)];
}
}

The problem is, it keeps returning the same response, instead of one of the five responses given. Any help would me much appreciated, thank you!
Edit:It's now giving only the random responses, and overriding every other response in the getResponse() method.

A: Given your logic, your getRandomResponse method should always return "OMG". This is because on the first run of the loop in that method, counter = 1. Thus the first if statement will run and will return "OMG" exitting the method. A nicer equivalent might putting all teh responses into an array and returning a random value from it, rather than doing somehting strange with iteration:
String[] responses = {"OMG", "LOL", "You don't say", "Really?", "I See"};
return responses[(int)(Math.random() * responses.length)];

A: In getRandomResponse, you make a random number generator using Random(), but you never use it.  Then in your for loop, you execute your decision-making tree but use a variable counter that always begins at 0.  Then on the first time through your loop, the first if statement will execute because 0 < 5, so "OMG" is returned.
Edit: I just noticed something else that is not going to work in your code:
Random randomNumber = new Random();
for (int counter =0; counter<10; counter++)
{
    counter = randomNumber.nextInt();

You're trying to use counter to do two different things: you are trying to run this loop 10 times, but you're also using it to store random values.


text:
Q: unable to open file:/// link in sharepoint2013 While working on a demo
I wanted to have some file links to a share.
This might sound odd, as normally data is placed inside SharePoint and not in share. But it makes some sense in this case (content of share is managed by another application).
So i copied the the file url from explorer, post it in my web browser.
Which translates all the spaces in the url to %20, to gain a valid url
I then took a List added url column, and posted that url into it.
The strange thing is while i can browse to that share using syntax file:/// url using firefox and Iexplorer once placed in the list it doesnt work anymore
Any ideas why ?.

A: My suggestion would to be to create a Content source and Result Source for the file share location and have it surface in Search Results.
If you want a custom view of the documents, you can use a Content Search Web Part to display the contents of the result source. Display Templates would help you in modifying the content view as needed.


text:
Q: GitPython list all files affected by a certain commit I am using this for loop to loop through all commits:
repo = Repo("C:/Users/shiro/Desktop/lucene-solr/")
for commit in list(repo.iter_commits()):
    print commit.files_list  # how to do that ?

How can I get a list with the files affected from this specific commit ?

A: Try it
for commit in list(repo.iter_commits()):
    commit.stats.files

A: from git import Repo
repo = Repo('/home/worldmind/test.git/')
prev = repo.commit('30c55d43d143189698bebb759143ed72e766aaa9')
curr = repo.commit('5f5eb0a3446628ef0872170bd989f4e2fa760277')
diff_index = prev.diff(curr)
for diff in diff_index:
    print(diff.change_type)
    print(f"{diff.a_path} -> {diff.b_path}")

A: I solved this problem for SCM Workbench. The important file is:
https://github.com/barry-scott/scm-workbench/blob/master/Source/Git/wb_git_project.py
Look at cmdCommitLogForFile() and its helper __addCommitChangeInformation().
The trick is to diff the tree objects.


text:
Q: Unable to start Logstash server and throwing error I want to pass  log file as an input to a Logstash input. I have added /bin to the environment variable path so that I can access it from anywhere.
Below is my conf file:
logstash.conf
input{
 path => "D:\nest\es-logging-example\log\info\info.log"
 start_position => beginning
}
output{
 elasticsearch{
    hosts => ["localhost:9200"]
    index => "indexforlogstash"
 }
}

After running this using logstash -f "D:\nest\es-logging-example\logstash.conf" its showing below  error in terminal.
 `
[2022-03-15T16:14:49,851][ERROR][logstash.agent           ] Failed to
execute action
{:action=>LogStash::PipelineAction::Create/pipeline_id:main,
:exception=>"LogStash::ConfigurationError", :message=>"Expected one of [
\\t\\r\\n], \"#\", \"{\" at line 2, column 11 (byte 19) after input{\r\n
path ", :backtrace=>["C:/logstash-8.1.0/logstash-
core/lib/logstash/compiler.rb:32:in `compile_imperative'",
"org/logstash/execution/AbstractPipelineExt.java:189:in `initialize'",
"org/logstash/execution/JavaBasePipelineExt.java:72:in `initialize'",
"C:/logstash-8.1.0/logstash-core/lib/logstash/java_pipeline.rb:47:in
`initialize'", "C:/logstash-8.1.0/logstash-
core/lib/logstash/pipeline_action/create.rb:50:in `execute'",
"C:/logstash-8.1.0/logstash-core/lib/logstash/agent.rb:376:in `block in
converge_state'"]}`

What is this error about?

A: There's no configuration found in C:\logstash-8.1.0\logstash.conf
Specify the absolute path where your logstash.cong file is located instead:
logstash -f "D:\\nest\\es-logging-example\\logstash.conf"

You also need to modify your config file as follows
path => "D:\\nest\\es-logging-example\\log\\info\\info.log"

A: I think your problem is that the \ is an escape character in the quoted string in your config file.
Can you change
 path => "D:\nest\es-logging-example\log\info\info.log"

to
 path => "D:\\nest\\es-logging-example\\log\\info\\info.log"

So the \ characters in the path are escaped.

A: Your configuration is wrong, you need to specify which input plugin you are using, which based on what you shared is the file input plugin.
Also, you need to use forward slashes.
Try the following:
input {
  file {
    path => "D:/nest/es-logging-example/log/info/info.log"
    start_position => beginning
  }
}


text:
Q: Explain if (++value % 2 == 0 && ++count < limit) in java public class AndOperator {

    public static void main(String[] arg) {
        int value = 8;
        int count = 10;
        int limit = 11;

        if (++value % 2 == 0 && ++count < limit) {
            System.out.println("here");
            System.out.println(value);
            System.out.println(count);
        } else{
            System.out.println("there");
            System.out.println(value);
            System.out.println(count);
        }
    }
}

i am getting output as
there
9
10

explain how count is 10....?

A: ++value = 9 so ++value % 2 == 0 is false so ++count < limit is not evaluated.
This is called Short circuit evaluation. See the wikipedia page : http://en.wikipedia.org/wiki/Short-circuit_evaluation

A: Since you are using &&(logical and) operator.

logical and evaluate second condition only if first condition is evaluated to true

Here in your code first condition ++value % 2 == 0 is evaluated to false,so second condition ++count < limit won't be evaluated.
If you want to execute ++count < limit also use &.
more information read Difference between & and &&

A: Because ++value % 2 == 0 is false, thus it won't return the first statement. The reason ++value % 2 is false is because value is incremented by one before the mod operator is evaluated. So ++value % 2 is 9 % 2 which != 0.

A: && is short-circuit operator. It will only evaluate the 2nd expression if the 1st expression evaluates to true.
Since ++value % 2 == 0 is false, hence it doesn't evaluate the 2nd expression, and thus doesn't increment count.


text:
Q: how overload operator<< for an array in C++? I'm trying to do it this way:
template <typename T>
ostream &operator<<(ostream &os, T &arr)
{ /*...*/ }

But can T represent an array? Is it correct to overload the << operator for an array?

EDIT:
According to Kerrek SB's advice, here is my implementation for <<:
template <typename T, unsigned int N>
ostream &operator<<(ostream &os, const T (&arr)[N])
{
    int i;
    for(i = 0; i < N; i++)
        os << arr[i] << " ";
    os << endl;
    return os;
}

Is my implementation right? I got a compilation error.

A: You could do this:
template <typename T, unsigned int N>
std::ostream & operator<<(std::ostream & os, const T (&arr)[N])
{
  // ..
  return os;
}

This works only for compile-time arrays, of course. Note that you are not allowed to instantiate this template when T is a built-in type or a type in the std namespace!
Probably best to make this inline if possible, since you'll cause a separate instantiation for every N. (The pretty printer has an example of this.)
You will notice, though, that the blanket template introduces an ambiguity, because os << "Hello" now has two possible overloads: the template matching const char (&)[6], and the (non-template) overload for the decay-to-pointer const char *, which both have identical conversion sequences. We can resolve this by disabling our overload for char arrays:
#include <ostream>
#include <type_traits>

template <typename T, unsigned int N>
typename std::enable_if<!std::is_same<T, char>::value, std::ostream &>::type
operator<<(std::ostream & os, const T (&arr)[N])
{
  // ..
  return os;
}

In fact, to be even more general you can also make the basic_ostream parameters template parameters:
template <typename T, unsigned int N, typename CTy, typename CTr>
typename std::enable_if<!std::is_same<T, char>::value,
                        std::basic_ostream<CTy, CTr> &>::type
operator<<(std::basic_ostream<CTy, CTr> & os, const T (&arr)[N])
{
  // ..
  return os;
}

In view of the fact that T must be a user-defined type, you could even replace is_same<T, char> with is_fundamental<T> to get a bit more checking (but users still must not use this for arrays of standard library types).

A: Another way you could do this would be something like the following:
template<typename T>
ostream& operator<<(ostream &out, const std::pair<T, int>& array)
{
    //...code
    return out;
}

Where T will take a pointer to an array (i.e., it will be the pointer-type that the array will decay into), and the int portion of the pair would be the size of the array.  You could then use it like the following:
int array[10];
//...some code that initializes array, etc.

cout << make_pair(array, 10);

One plus with this method is it will also work for dynamic arrays (i.e., arrays you allocate on the heap, etc.)


text:
Q: I want to implement TabBarController and add Navigation Controller View but in vain Iknow how to add a TabBar with two TabBar buttons on it by Interface Builder. And I link each button to a Navigation Controller.
Now I want to learn how to do everything programmatically. Now I can see a TabBar in simulator but with no buttons on it. Can someone please help me with this. Thanks!
Here's the TabBarAppDelegate.h.
#import <UIKit/UIKit.h>
@interface TabBarAppDelegate : NSObject <UIApplicationDelegate>
{
    UIWindow *window;
    UITabBarController *tabBarController;
    IBOutlet UINavigationController *navigationController1;
    IBOutlet UINavigationController *navigationController2;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) UITabBarController *tabBarController;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController1;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController2;
@end

Here's TabBarAppDelegate.m.
#import "TabBarAppDelegate.h"
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation TabBarAppDelegate
@synthesize window=window;
@synthesize tabBarController;
@synthesize navigationController1;
@synthesize navigationController2;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    tabBarController = [[UITabBarController alloc]init];
    FirstViewController *firstViewController = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
    firstViewController.title = @"First";
    [self.navigationController1 pushViewController:firstViewController animated:NO];

    SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
    secondViewController.title = @"NavCal";
    [self.navigationController2 pushViewController:secondViewController animated:NO];

    tabBarController.viewControllers = [NSArray arrayWithObjects:navigationController1, navigationController2, nil];

    [window addSubview:tabBarController.view];
    [self.window makeKeyAndVisible];
    [firstViewController release];
    [secondViewController release];
    return YES;
}

- (void)dealloc
{
    [tabBarController release];
    [window release];
    [super dealloc];
}

A: It looks like you are not initializing the navigation view controllers. See if this would work:
TabBarAppDelegate.h

*

*Remove the properties navigationController1 and navigationController2

TabBarAppDelegate.m

*

*Replace
[self.navigationController1 pushViewController:firstViewController animated:NO];

with
UINavigationController *navigationController1 = [[UINavigationController alloc] initWithRootViewController:firstViewController];

*

*Replace
[self.navigationController2 pushViewController:secondViewController animated:NO];

with
UINavigationController *navigationController2 = [[UINavigationController alloc] initWithRootViewController:secondViewController];

*

*Release navigationController1 and navigationController2 after adding them to the tabBarController


text:
Q: Is it possible to create immutable field in sequelizejs? Is there a way to make a field not modifiable in sequelize.js ?
var Employee = sequelize.define('Employee', {
  name:  {
    type     : Sequelize.STRING,
    allowNull: false,
    immutable:true// <-- something like that
  },
 ...
});

I cant't find any documentation on the subject.
Thanks


text:
Q: setOrientationHint rotates video counterclockwise on some phones' front facing cameras (HTC) The Problem: Certain Android devices (listed at the bottom of the question) exhibit unexpected behavior when utilizing the setOrientationHint(int degrees) function for videos taken with the front facing camera. The expected behavior is for the video to be rotated clockwise, but these devices rotate the video counterclockwise.
My Goal: To identify a variable within either the camera settings or hardware orientations that allows me to predictably know when this will occur. Specifically, I would like to avoid special casing these phones in my code!
Further Explanation: I am recording video using the standard MediaRecorder object, and in preparing for recording, I set the orientation of the video using setOrientationHint(). In the documentation for setOrientationHint(), the following is specified for the degrees parameter:

degrees  –– the angle to be rotated clockwise in degrees. The supported angles are
  0, 90, 180, and 270.

The function is intended to add a composition matrix containing the rotation angle so that a video player can display the video as intended. So, what I do is that I get the camera hardware's orientation using the CameraInfo class and use that as the degrees parameter in the setOrientationHint fn. (I have tried variation on this code using the AOSP as a guide, but I had the exact same result.)
A Real Example: The Samsung Galaxy S3 front-facing camera (and most others, in fact) will have a hardware orientation of 270, so I use this when recording, and the resulting video is displayed correctly. An HTC Vivid will similarly return a hardware orientation of 270 for the same camera, but will only be displayed correctly if I use 90 as the degrees parameter in the setOrientationHint fn. If I use the 270 of the hardware orientation like any other phone, the video will be upside down.
NB: The setOrientationHint() function includes a warning:

Note that some video players may choose to ignore the compostion
  matrix in a video during playback.

However, this is not what is happening, because I can easily fix this issue on these phones if I fake it and put in 90 instead of 270.
Phones that I have seen specifically exhibit this issue: HTC Vivid (PH39100) running Android 4.0.3, HTC EVO 4G (PG86100) running Android 4.0.3, HTC Thunderbolt (ADR6400L) running Android 2.3.4. Notice that they are all HTC phones. Perhaps someone at HTC mistook clockwise for counterclockwise.

A: Yes, the HTC phones rotate in the wrong direction for the front facing cameras.  Instead of trying to guess, I ended up adding a settings screen that would take two pictures with the second one rotating 90 degrees.  Then the user could keep hitting next as I cycled through the different rotation direction and angle combinations until both pictures appeared oriented the same way.


text:
Q: Break long formula R documentation I have a long formula that I need to break in the R documentation of a package or it trails off the right hand side of the page.  HEre's the formula in roxygen2 style:
#' \deqn{Cov(r_{ist}, r_{iuv})= [.5\rho_{ist}\rho_{iuv}(\rho_{isu}^2 +
#' \rho_{isv}^2 + \rho_{itu}^2 + \rho_{itv}^2) + \rho_{isu}\rho_{itv}+ \newline
#' \indent \rho_{isv}\rho_{itu}-(\rho_{ist}\rho_{isu}\rho_{isv} +
#' \rho_{its}\rho_{itu}\rho_{itv}) + \rho_{ius}\rho_{iut}\rho_{iuv} +
#' \rho_{ivs}\rho_{ivt}\rho_{ivu}]/n_i}

Notice I tried to use \new line and indent but this didn't work it still trails off the edge.
How can I break the formula and indent it?  Maybe indenting isn't appropriate (not sure on that).

A: Here's a link about this question:
http://yihui.name/en/2007/12/line-breaks-for-latex-code-in-r-documentation-files/


text:
Q: random woocommerce categories are not showing when count enabled? First I would like to apologize if this is off topic as it's based on Woocommerce and specific to a theme (Natural using wpOpal Themer), but the issue is a wordpress coding issue.
My theme has a "widget" so to speak that displays Woocommerce product categories based on custom criteria. The biggest problem with this is that it only shows the same categories and has no parameters to choose categories. I would like to change the behavior so that I get random categories. Searching around I found that I had to edit the woo_shop_category.php (through a child theme). I have found the snippet I need to change and using instructions and logic from - Categories and products in random order I have been able to get close to what I want.
Here is the problem.
When I don't have the count as per the code below, it shows all categories in random order - the correct result.
  $product_cat = get_term_by( 'slug', $product_cat_slug, 'product_cat' );
$product_category_parent = $product_cat->term_id;

extract( $atts );

$_id = rand();
$_count = 0;

$args = array(
    'child_of'  => $product_category_parent,
'hide_empty'    => 1,
'hierarchical'  => 1,
'taxonomy'      => 'product_cat',
'pad_counts'    => 1,

);

$all_categories = get_categories( $args );
$_totals = count($all_categories);
shuffle($all_categories);

As soon as I include 'number' => $number_cats in the args(a number of categories that is selected in the front end using King Composer as per the theme) it only shows the same categories as per the $number_cats value . For example, if I want 10 categories, it would shuffle the first 10 categories and does not display 10 random categories of all categories which is the desired action.
I doubt the following code is relevant but it basically tells to display each of the $all_categories as a carousel as per the woocommerce global variables.
if($all_categories):

?>
<div class="opal-category-shop woocommerce <?php echo (($el_class!='')?' '.esc_attr( $el_class ):''); ?>">

<?php echo trim($title);?>

        <div class="products-collection owl-carousel-play woocommerce carousel-products" id="postcarousel-<?php echo esc_attr($_id); ?>" data-ride="carousel">
            <?php if( $_totals > $columns ): ?>

                    <a href="#postcarousel-<?php echo esc_attr($_id); ?>" data-slide="prev" class="left carousel-control carousel-md">

                    <a href="#postcarousel-<?php echo esc_attr($_id); ?>" data-slide="next" class="right carousel-control carousel-md">

            <?php endif; ?>
            <div class="owl-carousel" data-slide="<?php echo esc_attr($columns);?>"  data-singleItem="true" data-navigation="false" data-pagination="false">
                <?php foreach($all_categories as $_category): ?>

                            <a href="<?php echo esc_url( get_term_link( $_category->slug, 'product_cat' ) ); ?>">
                                 <?php
                                    $thumbnail_id = get_woocommerce_term_meta( $_category->term_id, 'thumbnail_id', true );
                                    $image = wp_get_attachment_url( $thumbnail_id );
                                    if ( $image ) {
                                        echo 'name.'" />';
                                    }else{
                                        echo 'name.'" />';
                                    }
                                ?>

<a href="<?php echo esc_url( get_term_link( $_category->slug, 'product_cat' ) ); ?>"><?php echo trim($_category->name); ?>

                <?php endforeach; ?>

What I believe the issue is:
The shuffle($all_categories); is doing its job and shuffling all the categories. But the shuffle is based on the count of categories and not on all categories. So basically I need to know how I can set my array to get all categories and shuffle them and then only display the number selected in $number_cats. So basically Array gets created and results shuffled. Then create another array from the results of the first array to the count of $number_cats.
Can I create two arrays that will first shuffle all categories and then choose the count from the shuffled categories? If that is the case, what is the syntax to create multiple arrays. I tried to list one array then create a variable from get_categories($args) and then create another array from that variable by calling it in the array as 'child_of' but that through a php error saying that it was illegal (I reverted after seeing this message. If need be I can recreate it if its required to troubleshoot)

A: While researching for this I came across Categories and products in random order which had a similar but different issue but was able to derive the required information to cut the array.
I modified his $categories = array_slice( $categories, 0, 5 ); to suit my needs. Final answer was just to add an array_slice based on $cat_number
so I modified $all_categories and called it just $categories (as I will later reference $all_categories) and changed the code to following
$categories = get_categories( $args );
$_totals = count($categories);
    shuffle($categories);
$all_categories = array_slice( $categories, 0, $number_cats );


text:
Q: Can't delete file after calling FontFactory.getFont() method I am using iTextPdf 5.5.3 to create PDF/A documents, I want the user to select custom fonts by uploading the .ttf file of the font, and becuase FontFactory.getFont() method only takes the font name as a string I have to write the uploaded file to the user's drive (I KNOW, I ASKED MY CUSTOMER FOR PERMISSION TO WRITE TO THE DRIVE) and then pass the path of the uploaded file to the getFont() method, after everything is finished I want to delete the uploaded files from the drive. Here is my code:
File fontFile = new File("d:/temp/testFont.ttf");
try {
    FileOutputStream outStream = new FileOutputStream(fontFile);
    outStream.write(the bytes of the uploaded font file);

    outStream.flush();
    outStream.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Font font = FontFactory.getFont(fontFile.getAbsolutePath(), BaseFont.CP1250 , BaseFont.EMBEDDED);

fontFile.delete();

This code is not working, somehow the getFont() method is locking the font file and therefore the file is not being deleted. I tried lots of ways to do this, like: fontFile.deleteOnExit(); or FileDeleteStrategy.FORCE.delete("file path"); but nothing is working for me. Please advise. Thanks

A: I am not going to answer the question mentioned in the title of your post (because it is a secondary). Instead I am going to answer the question in the body (which is the essential question).
You claim that FontFactory.getFont() requires a font file on the file system. That is not incorrect. However, that doesn't mean you can't create a font from a byte[].
You are trying to solve your problem by saving a ttf on disk (which is forbidden by your customer), but that isn't necessary. In a way, your customer is right: it's not a good idea to save the TTF as a temporary file on disk (which is why I'm ignoring your secondary question).
Take a look at the following createFont() method:
public static BaseFont createFont(String name,
        String encoding,
        boolean embedded,
        boolean cached,
        byte[] ttfAfm,
        byte[] pfb)
    throws DocumentException,
        IOException

This is how you should interpret the parameters in your case:

*

*name - the name of the font (not the location)

*encoding - the encoding to be applied to this font

*embedded - true if the font is to be embedded in the PDF

*cached - probably false in your case, as you won't be reusing the font in the JVM

*ttfAfm - the bytes of the .ttf file

*pfb - in your case, this value will benull (it only makes sense in the context of Type1 fonts).

Now you can meet the requirements of your customer and you do not need to introduce a suboptimal workaround.
Note: you are using iText 5.5.3 which is available under the AGPL. Please be aware that your customer will need to purchase a commercial license with iText Software as soon as he starts using iText in a web service, in a product,...


text:
Q: RuntimeException in Android when using BroadcastReceiver and My Application stop working
Unable to start receiver br.exemploalarmmanagerbn.BroadcastReceiverAux: java.lang.NullPointerException
previously my app worked properly.but after adding

new getNewMessages().execute(new ApiConnector());

code part it was giving a above run time error.
logcat

09: W/dalvikvm(17914): threadid=1: thread exiting with uncaught exception (group=0x40af49f0)
08-07 17:53:30.609: E/AndroidRuntime(17914): FATAL EXCEPTION: main
08-07 17:53:30.609: E/AndroidRuntime(17914): java.lang.RuntimeException: Unable to start receiver br.exemploalarmmanagerbn.BroadcastReceiverAux: java.lang.NullPointerException
08-07 17:53:30.609: E/AndroidRuntime(17914):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2126)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at android.app.ActivityThread.access$1500(ActivityThread.java:123)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1197)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at android.os.Looper.loop(Looper.java:137)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at android.app.ActivityThread.main(ActivityThread.java:4424)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at java.lang.reflect.Method.invokeNative(Native Method)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at java.lang.reflect.Method.invoke(Method.java:511)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at dalvik.system.NativeStart.main(Native Method)
08-07 17:53:30.609: E/AndroidRuntime(17914): Caused by: java.lang.NullPointerException
08-07 17:53:30.609: E/AndroidRuntime(17914):    at br.exemploalarmmanagerbn.BroadcastReceiverAux.onReceive(BroadcastReceiverAux.java:46)
08-07 17:53:30.609: E/AndroidRuntime(17914):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2119)
08-07 17:53:30.609: E/AndroidRuntime(17914):    ... 10 more
08-07 17:53:31.249: W/System.err(17914): java.net.UnknownHostException: Unable to resolve host "crowdeye.crowderia.com": No address associated with hostname
08-07 17:53:31.269: W/System.err(17914):    at java.net.InetAddress.lookupHostByName(InetAddress.java:467)
08-07 17:53:31.269: W/System.err(17914):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:258)
08-07 17:53:31.269: W/System.err(17914):    at java.net.InetAddress.getAllByName(InetAddress.java:236)
08-07 17:53:31.269: W/System.err(17914):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-07 17:53:31.269: W/System.err(17914):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-07 17:53:31.279: W/System.err(17914):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-07 17:53:31.279: W/System.err(17914):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-07 17:53:31.279: W/System.err(17914):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-07 17:53:31.279: W/System.err(17914):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-07 17:53:31.279: W/System.err(17914):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-07 17:53:31.279: W/System.err(17914):    at br.exemploalarmmanagerbn.ApiConnector.getMessage(ApiConnector.java:31)
08-07 17:53:31.279: W/System.err(17914):    at br.exemploalarmmanagerbn.getNewMessages.doInBackground(getNewMessages.java:14)
08-07 17:53:31.279: W/System.err(17914):    at br.exemploalarmmanagerbn.getNewMessages.doInBackground(getNewMessages.java:1)
08-07 17:53:31.279: W/System.err(17914):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-07 17:53:31.289: W/System.err(17914):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-07 17:53:31.289: W/System.err(17914):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-07 17:53:31.289: W/System.err(17914):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-07 17:53:31.289: W/System.err(17914):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-07 17:53:31.289: W/System.err(17914):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-07 17:53:31.299: W/System.err(17914):    at java.lang.Thread.run(Thread.java:856)
08-07 17:53:31.299: W/System.err(17914): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
08-07 17:53:31.349: W/System.err(17914):    at libcore.io.Posix.getaddrinfo(Native Method)
08-07 17:53:31.349: W/System.err(17914):    at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
08-07 17:53:31.359: W/System.err(17914):    at java.net.InetAddress.lookupHostByName(InetAddress.java:452)
08-07 17:53:31.359: W/System.err(17914):    ... 19 more

A: There may be other issues, but you need to add a period (.) to your receiver name android:name="BroadcastReceiverAux" should be receiver android:name=".BroadcastReceiverAux". The reason is you're specifying a class name (and it is appended to your package name declared at the beginning of your manifest)
Take a look at the name part of this documentation


text:
Q: Not able to run system command through perl script Hi i am inserting image location into particular line of file using Perl one-liner code as below
 my $image="/home/users/images/image1.tar";
 system(q(perl -pi -e 'print "\n$image" if ($. == 5 && $_=~ /^\s*$/ )' myfile.txt));

i am not able to insert a image location into the file .
please can anyone help me out?

A: I'm not sure why you're shelling out to a second Perl process to do this. Why not just do the processing within the original Perl program?
But your problem seems to be that the string you're passing to system is in single quotes (using q(...)) which means that the $image variable won't be expanded. You probably want to change that to a double-quoted string (using qq(...)).
Update:
This is why shelling out to an external process is fraught with difficulty. You have one variable ($image) which needs to be passed though and another variable ($_) which needs to be internal to the second process. You also have an escape sequence (\s) which the shell is trying (but failing) to interpret.
Liberal application of backslashes to escape special characters gives this:
#!/usr/bin/perl

use strict;
use warnings;

my $image='/home/users/images/image1.tar';
system(qq(perl -pi -e 'print "\n$image" if (\$. == 5 && /^\\s*\$/ )' myfile.txt));

Which seems to work. But I still think you'd be far better off doing this all in one Perl program.

A: As was pointed out, using single quotes q{} did not allow your $image variable to interpolate.
To fix, just concatenate that variable into your string:
#!/usr/bin/perl

use strict;
use warnings;

my $image = '/home/users/images/image1.tar';
system(q{perl -pi -e 'print "\n} . $image . q{" if ($. == 5 && $_=~ /^\s*$/ )' myfile.txt});

However, a much better solution is just to do this processing local to your perl script.
The following does the exact same processing without the secondary call to perl by using $INPLACE_EDIT:
my $image = "/home/users/images/image1.tar";

local @ARGV = 'myfile.txt';
local $^I = '';
while (<>) {
    print "\n$image" if $. == 5 && $_ =~ /^\s*$/;
    print;
}

For additional methods for editing a file, just read perlfaq5 - How do I change, delete, or insert a line in a file, or append to the beginning of a file?


text:
Q: Default ordered dictionaries in Python 2.7.x Besides the answers from ~3 years ago in this question:
Can I do an ordered, default dict in Python?
Have any implementations been adopted into recent versions of Python?
If not, why not?

A: No, for default options, you will only have the built-in dictionary which is not ordered. If you do want an ordered dictionary, you will have to import the module OrderedDict.
from collections import OrderedDict
>>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])

You do, however, have the option of creating a list of tuples which will maintain its order.
Instead of:
a = {'a': 1, 'b': 2, 'c':3}
you would do it as:
a = [('a', 1), ('b', 2), ('c', 3)]

A: I'm afraid I'm not on 2.7, so cannot test, but this should reimplement a defaultdict subclassed from OrderedDict:
from collections import OrderedDict

class DefaultOrderedDict(OrderedDict):
    def __init__(self, default):
        self.default = default
    def __getitem__(self, x):
        try:
            return OrderedDict.__getitem__(self, x)
        except KeyError:
            self[x] = self.default()
            return self[x]


text:
Q: Ruby : Convert XML to JSON putting the values of Name as keys and the values of Contents as values I have an android XML file in the following format
<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <!-- I AM A COMMENT -->

  <!-- General -->
  <string name="foo">foo</string>
  <string name="bar">bar</string>
 </resources>

I want my JSON output to look like this:
 {
    "resources": {
        "foo": "foo",
        "bar": "bar"
    }
 }

That is, I want the values of the node names to be the Keys, and the Values of the contents of the nodes to be the values in the JSON KV pairs.
is this doable with nokogiri attributes?  or crack?
or must i perform pre-processing on the XML beforehand?

A: You can use XSLT to transform the XML and then use nokogiri to transform it:
The XSLT I used:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="resources">
{
    "resources": {
        <xsl:for-each select="string">
            "<xsl:value-of select="./@name"/>":
            "<xsl:value-of select="."/>"
            <xsl:choose>
                <xsl:when test="position() != last()">,</xsl:when>
            </xsl:choose>
        </xsl:for-each>
    }
}
</xsl:template>
</xsl:stylesheet>

Apply the XSLT with nokogiri:
require 'nokogiri'
document = Nokogiri::XML(File.read('input.xml'))
template = Nokogiri::XSLT(File.read('template.xslt'))
transformed_document = template.transform(document)


text:
Q: Проверку, лежит ли точка внутри окружности Задана окружность (x-a)2 + (y-b)2 = R2 и точки Р(р1, р2), F(f1, f1), L(l1,l2). Выяснить и вывести на экран, сколько точек лежит внутри окружности. Проверку, лежит ли точка внутри окружности, оформить в виде процедуры.
  def task(a,b,r,c):
            return len(list(filter(lambda x : (x[0]-a)**2+(x[1]-b)**2 < r**2, c )))

        print(task(int(input('Введите точку a: ')),
    int(input('Введите точку b: ')),
    int(input('Введите радиус: ')),
    [[int(i) for i in input('Введите точки р1, р2: ').split()],
    [int(i) for i in input('Введите точки f1, f2: ').split()],
    [int(i) for i in input('Введите точки l1,l2: ').split()]]))

1)Правильно ли?
2)Как написать проверку, лежит ли точка внутри окружности, в виде процедуры

A:
Правильно ли?

Результат - правильный. Попытка пропихать всё в одну строчку - не правильная :)

Как написать проверку в виде процедуры

Процедурой называют программу / функцию, которая последовательно выполняет какие-то инструкции. Иногда это слово используют как синоним для "функции". В контексте задачи, имеется в виду функция, которая получит координаты точки, центра окружности и выдаст True / False.
def int_input(msg = ''):
    x = input(msg).strip().split()

    return int(x) if len(x) <= 1 else map(int, x)

###
cx, cy, r = int_input('Введите коор-ты центра окружности и радиус (через пробелы): ')
# ↖________________________   (числа сразу сохраняются в виде значений параметров
#                          ↓          по умолчанию, в момент создания функции)
def includes(px, py, cx = cx, cy = cy, r = r):
    return (px - cx) ** 2 + (py - cy) ** 2 < r ** 2

###
included_points = 0

for p in ('P', 'F', 'L'):
    px, py = int_input(f'Введите коор-ты точки {p}: ')   # Справка: «f-string»
    included_points += includes(px, py)

print(included_points)

* cx = cx — названия могут отличаться, они совпали случайно)
** += includes(px, py) в мат-операциях True → 1, False → 0


text:
Q: Iterated $\Pi^1_1$-reflection and non-Gandiness underrepresented in ordinal analyses? The admissible ordinals $\alpha$ s.t. the supremum of $\alpha$-recursive well-orderings is less than the next admissible $>\alpha$ are called non-Gandy, and according to Madore's "A Zoo of Ordinals" the least non-Gandy ordinal is between the least $(^+)$-stable and the least inaccessibly-stable in size. Another phenomenon that begins happening with admissible ordinals at a similar size is iterated $\Pi^1_1$-reflection, which according to Taranovsky's "Ordinal Notation" page can be informally iterated further than first-order reflection.
On the same page in §4.2, Taranovsky conjectures that even with an arbitrary recursive base notation O, the system "Degrees of Reflection" only just suffices to capture the structure below the least non-Gandy ordinal, in which case the structure of admissible ordinals below the least non-Gandy is quite rich. Also, from the same site's §5.2, an informal statement about how rich the structure of non-Gandy ordinals is even below the least $\alpha$ that's $(\alpha^++1)$-stable, sharpening the "inaccessibly-stable" bound from A Zoo of Ordinals, and that said structure is rich to the point of stratifying into multiple "levels" the same way the $(\alpha^++n)$-stable ordinals would for $n<\omega$. And not only that, but §4.2 also says each $(\alpha^++1)$-stable $\alpha$ is non-Gandy, implying the non-Gandy ordinals are unbounded in the least inaccessibly-stable. All things considered, iterated $\Pi^1_1$-reflection and non-Gandy ordinals seem to contribute very heavily to the structure of countable admissibles past the least $(^+)$-stable!
However, in strong ordinal notations going past the level of the least $(^+)$-stable, such as the ones in Arai's recent analysis of $\textrm{KP}+\Pi_1$-collection and Rathjen's analysis of $\Pi_2^1$-CA+BI, I haven't noticed a treatment of iterated $\Pi^1_1$-reflection or non-Gandy ordinals. I'm far from an expert on ordinal analysis, so it's possible I've missed their appearance if they do appear. In the case they don't show up, how is analysis done without dealing with these phenomena, assuming they really do contribute so much to the structure of the admissible ordinals in that range?


text:
Q: How to get multiple first matches from regex? I'm using regular expressions to extract all class names from a CSS file. The regex works well if there is only one class, for example .test {margin: 0}, but if there is a set of classes, for example .test.second.third {margin:0}, I need only the first class als result: .test.
My current regex gives me .test, .second, .third. This is fine, but not what I need in this case. Where is the error in my regular expression?
I'm using it with JavaScript:
code = code.match(/(?:[\.]{1})([a-zA-Z_]+[\w-_]*)(?:[\s\.\,\{\>#\:]{0})/igm);

Or here as regex101 sheet: https://regex101.com/r/sgjrHt/1

A: In your pattern:

*

*This part (?:[\.]{1}) is the same as writing \.

*Using \w also matches _ so you don't have to add them both to a character class like this [\w-_]

*Note that in that format you would have to escape the hyphen or put it at the start or the end of the character class

If a lookbehind assertion is supported:
(?<!\S)\.\w+(?:[:-]+\w+)*(?=[^{}]*\{[^{}]*})

Explanation

*

*(?<!\S) Assert a whitespace boundary to the left

*\.\w+ Match . and 1+ word chars

*(?:[:-]+\w+)* Optionally repeat matching : or - and 1+ word chars

*(?= Positive lookahead, assert to the right

*

*[^{}]* Match optional chars other than { and }

*\{[^{}]*} Match {...}

*) Close the lookahead

Regex demo
Without a lookbehind you can use a capture group:
(?:\s|^)(\.\w+(?:[:-]+\w+)*)[^{}]*\{[^{}]*}

Regex demo


text:
Q: Youtube Autoplay on mobile not working but in browser it works i just embed regular youtube video into my html file.
and i use autoplay=1  ,and it works regulary on browsers.
but the autoplay doesn't work with any mobile.
can you help ?
Thanks

A: `

var player;

function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
        playerVars: {
            'autoplay': 1,
            'controls': 0,
            'autohide': 1,
            'wmode': 'opaque',
            'showinfo': 0,
            'loop': 1,
     'playlist': 'aF5HAF0fg6M',
     'fs':1
        },
        videoId: 'aF5HAF0fg6M',
        events: {
            'onReady': function(){
      player.pauseVideo();
      player.playVideo();
     }
        }
    });

}

window.onload=function() {
};
.video-background {
  background: #000;
  position: fixed;
  top: 0; right: 0; bottom: 0; left: 0;
  z-index: -99;
}
.video-foreground,.video-background iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

@media (min-aspect-ratio: 16/9) {
  .video-foreground { height: 300%; top: -100%; }
}

test

Working sample on the following link
http://demo.jawadsolutions.com/researchs/youtube/


text:
Q: Problem with Web View Height I have some problem with webView
I want know height web view   i use this
-(void)webViewDidFinishLoad:(UIWebView *)webViews
{
    NSLog(@"hight %@",[webViews stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"]);
}

or
document.body.offsetHeight;

but for iPad and iPhone i get different height for 1 html?
Who can help or give some advice  about this problem?Tnx


text:
Q: Why should I use a ContentProvider with exported=false? I can't figure out why I should use a ContentProvider with the setting "android:exported=false" in the AndroidManifest.xml. Aren't ContentProviders created to share data between multiple applications? In this way, I am restricting data sharing only to my application and not to external applications. But at this point I can simply use a database in SQLite (maybe with SQLiteOpenHelper).
In the case where I need to create a pre-populated database by loading data from a Rest API, but at the same time I do not need to share my data to other applications, should I create a ContentProvider with the setting "android:exported=false" using the ContentProviderOperation and ContentProviderOperation.Builder Classes (I have seen that these two Classes are used for massive data insertion) ? Or should I create a database in SQLite and insert the data using the INSERT command ?
Thank you!


text:
Q: When using Microsoft Access DSNs do I simply replace the database connection string with the path of the DSN? I have inherited a web application with an Access backend (yes I know).
I need to get this thing deployed asap to a shared hosting provider. Unfortunately, it's not as easy as I imagined as hosts tend to lock down access to Access databases (AFAICT).
I have a shared account with GoDaddy - I have enabled Access database use, and created a DSN.
The application has references to the database connection string littered throughout it. Is using DSNs simply a matter of changing the connection string to be the path of the DSNs?
Any help much appreciated.

A: Been a while since I did this, but you should just be able to change the connection string to DSN=MYDSNNAme
I would try it locally first though.
Obviously if you are going to go to this trouble, replace each occurance with a variable, so if you need to do it again it will be easier :)


text:
Q: Add liked posts to user account I'm working on a setlist website where the users can view all the setlists from a band. I would like to have the functionality that users can add their attended setlists to their profile.
So when they go to their profile page, they'll see all the gigs attended.
My guess is to install Buddypress and start from there. But maybe there is another solution for this?

*

*users should be able to create a profile

*a user should be able to like or favourite (in this case "attend") the gig (= custom post type 'gig').

*they should be able to view all their gigs attended.

Thanks in advance.

A: I have utilized this plugin for a similar situation:
https://de.wordpress.org/plugins/ultimate-member/
Your users can register and create a profile. As the plugin comes with a lot of add-ons I'm not sure if there maybe is an add-on that solves your "attend" issue. If yes, problem solved. If not you could simply add a function which saves an array of gigs to the users profile.
I believe, that you'll probably be better off using this than buddypress. Hope that helps.


text:
Q: Could someone expound why Spliterators::trySplit uses an arithmetic progression to calculate the size of the returned Spliterator? Summary
The motivation for the arithmetic progression does not seem entirely clear from the implementation, and I would like to understand the details of its conception.
Specific Questions

*

*Are there cases where this is superior to equal partitions of the elements?

*Are there JIT effects to consider that make subsequent partitions more efficient than their predecessors?

My thoughts so far
Given: progression P(i) = 1024*1 + 1024*2 + 1024*3 ... 1024*i

*

*It seems that this design is less efficient when P(cores) > number of elements

*It seems that this design is substantially less efficient when each element has a very high cost to process, and P(cores) >> number of elements (e.g. 8 very complex items)

*It seems that if the size of a collection were available before it is processed into a spliterable the size could be used to hint at a more optimal partitioning scheme. Is this incorrect? If it is correct, why do we not do this?

Thank you.


text:
Q: libcurl error, curl_easy_perform() failed: c++ I have written this code for downloading a file using libcurl:
#ifndef CHECK_RESOURCES_H
#define CHECK_RESOURCES_H

#include <string>
#include <stdio.h>
#include <curl/curl.h>
// #include <bzlib.h>

void progress_bar (void* ptr, double TotalToDownload, double NowDownloaded, \
    double TotalToUpload, double NowUploaded) {

    printf("%f : %f \n", TotalToDownload, NowDownloaded);
}

void download_file () {
    CURL *curl;
    CURLcode res;
    char outFileName[FILENAME_MAX] = "shape_predictor_68_face_landmarks.dat.bz2";
    std::string url = "http://ufpr.dl.sourceforge.net/project/dclib/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2";
    FILE *fp;

    curl = curl_easy_init ();
    if (curl) {
        fp = fopen (outFileName, "wb");

        curl_easy_setopt (curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        // Internal CURL progressmeter must be disabled if we provide our own callback
        curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
        // Install the callback function
        curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_bar);

        res = curl_easy_perform (curl);

        if (res != CURLE_OK) {
            fprintf(stderr, "%s%s\n", "curl_easy_perform() failed : ", curl_easy_strerror(res));
        }

        curl_easy_cleanup (curl);
        fclose (fp);
    }
}

void extract_bz2 () {

}

void check_dlib_landmark_weights (const std::string& name) {
    if (FILE *file = fopen(name.c_str(), "r")) {
        fclose(file);
    } else {
        download_file ();
    }
}

#endif  // CHECK_RESOURCES_H

The problem is that when I run the code it gives this output:
0.000000 : 0.000000
0.000000 : 0.000000
curl_easy_perform() failed : Operation was aborted by an application callback

I dont understand why this is failing. I have checked the link I am using and it's a working link (downloaded the file without any prob). How do I correct this?

A: The CURLOPT_PROGRESSFUNCTION expects that the callback function will return a value of 0, currently your function returns void. If you modify your progress_bar function to return int instead of void and add return 0; to the end of it that should resolve the issue.


text:
Q: Como criar um usuario com AbstractBaseUser ou AbstractUser. (Erros de login) Estou tentando utilizar minha classe Pessoa como usuario no models.py.
Entretanto tentei usar AbstractUser e AbstractBaseUser. Ambos me retornam erros na parte onde tento efetuar login, testei diversas maneiras até perceber que necessito de ajuda de alguém com mais experiencia e conhecimento que eu.
Meu models.py:
    from django.contrib.auth.models import AbstractUser
from django.db import models

class Pessoa(AbstractUser):
    id_pessoa = models.AutoField(primary_key=True)
    cnpj = models.CharField(max_length=14, unique=True)
    nome = models.CharField(max_length=70)
    email = models.CharField(max_length=100, blank=True, null=True)
    senha = models.CharField(max_length=40, null=False)
    ativo = models.BooleanField(blank=True, null=True)
    datacadastro = models.DateField(blank=True, null=True)
    cidade = models.CharField(max_length=50, blank=True, null=True)
    uf = models.CharField(max_length=2, blank=True, null=True)
    USERNAME_FIELD = 'cnpj'

    class Meta:
        managed = False
        db_table = 'pessoa'

Detalhe: estou impossbilitado de remover ou adicionar campos em
  qualquer modelo que estou utilizando, porque eu usei inespectdb para
  criar os modelos baseados no banco de dados que estou utilizando(O
  mesmo que já esta cheio de dados). Qualquer alteração, com exceções
  de alterações básicas, está fora de cogitação.

Abaixo meu views.py com a def que valida o login e redireciona para o dashboard.
def dash_login(request):
    form = LoginForm(request.POST, None)
    if request.method == 'POST':
        #if form.is_valid():
        username = form.data['cnpj']
        password = form.data['senha']
        user = authenticate(username=username)
        print(username)
        #p = Pessoa.objects.filter(cnpj=form.data['cnpj']).values('id_pessoa')[0]['id_pessoa']
        #login(request, user)
        print(request.user.is_authenticated)
        #return render(request, 'dashboard.html')
    return render(request, 'login.html', {'form': form})

Eu utilizo print() para testar os comandos antes de sair executando, no momento quando ele chega na linha:

user = authenticate(username=username)

Ele dispara este erro:

File "C:\Users\Pichau\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py",
  line 85, in _execute
      return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column pessoa.password does not
  exist LINE 1: SELECT "pessoa"."password", "pessoa"."last_login",
  "pessoa"....
Independente que eu ponha senha dentro do authenticate o erro é
  disparado.

Essa foi a segunda opção:
def dash_login(request):
    form = LoginForm(request.POST, None)
    if request.method == 'POST':
        print(form.is_valid())
        if form.is_valid():
            cnpj = form.data['cnpj']
            print('Valido')
            print(cnpj)
            p = Pessoa.objects.filter(cnpj=cnpj).values('id_pessoa')[0]['id_pessoa']
            #print(p)
            #return redirect('dashboard', p)
    return render(request, 'login.html', {'form': form})

Onde eu caio no mesmo erro, caso eu retire o p e use return render(request, 'dashboard.html') Eu estou redirecionamento sem o id do usuário, o que me gera problemas para pegar os dados dele dentro do dashboard.
Contudo ainda tenho o problema principal, essa tabela está logando no login do Django e não no login que eu criei dentro do models.py|forms.py
Erro:

Edit1: models.py que estou tentando integrar.
from django.contrib.auth.models import AbstractUser, User
from django.db import models
from django.conf import settings

class Pessoa(AbstractUser):
    id_pessoa = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True)
    cnpj = models.CharField(max_length=14, unique=True)
    nome = models.CharField(max_length=70)
    email = models.CharField(max_length=100, blank=True, null=True)
    senha = models.CharField(max_length=40, null=False)
    ativo = models.BooleanField(blank=True, null=True)
    datacadastro = models.DateField(blank=True, null=True)
    cidade = models.CharField(max_length=50, blank=True, null=True)
    uf = models.CharField(max_length=2, blank=True, null=True)

    USERNAME_FIELD = 'cnpj'
    REQUIRED_FIELDS = []

    class Meta:
        managed = False
        db_table = 'pessoa'

    def __str__(self):
        return self.nome

Mensagem de erro ao dar migrate:
 File "C:\Users\Pichau\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY"
LINE 6:                     FROM unnest(c.conkey) WITH ORDINALITY co...

Erro completo https://i.stack.imgur.com/vV54h.png
O fato de eu não conseguir dar migrate explica o erro anterior que explica que o componente não existe na table do model.

Edit: O erro foi gerado quando executei inspectdb e o banco estava
  com uma versão desatualizada(PostgreSQL), era necessário atualizar
  para uma versão mais nova e executar o  código novamente, para poder
  inspecionar seu banco e criar modelos a partir dele.
Outro possível erro é que ele te impede de dar migrate por esse
  mesmo erro, e isso pode causar erros de faltas de campos no banco por
  não poder dar migrate

A: Ola,
Tente fazer makemigrations e migrate colocancando o nome do APP
python manage.py makemigrations NOMEDOAPLICATIVO
python manage.py migrate NOMEDOAPLICATIVO

Pode ser esse o ERRO, ele não esta migrando corretamente.
Estava vendo seus códigos e não consigo o que você esta importando (quais bibliotecas) import
Um Exemplo que estou usando no meu sistema model.py:
from __future__ import unicode_literals
import re

from django.db import models
from django.core import validators
from django.utils import timezone
from django.core.mail import send_mail
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.conf import settings

class UserManager(BaseUserManager):
  #codigo omitido para dimimuir o exemplo, ele será chamado no meio do User para gerenciar o User

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    username = models.CharField(_('username'), max_length=15,
    help_text=_(É obrigatório. 15 caracters ou menos. Letras,numeros e@/./+/-/_ caracters'),
    validators=[validators.RegexValidator(re.compile('^[\w.@+-]+$'),
     _('Use um nome Valido.'), _('invalid'))])
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    birth_date = models.CharField(_('birth date'),max_length=10,null=True, blank=True)
    is_staff = models.BooleanField(_('staff status'), default=False,
      help_text=_('Designates whether the user can log into this admin site.'))
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    avatar = models.ImageField(default='accounts/defaults/default1.jpg', upload_to=upload_location1) #, blank=True) # null=True)
    picresume = models.ImageField( default='accounts/defaults/default1.jpg', upload_to=upload_location2 ) #, blank=True , null=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username','birth_date']

    class Meta:
    #explica para o django se usa o plural
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        #Returna nome e sobrenome juntos
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        #Returna nome curto.
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        #envia email , vai precisar no futuro , para resetar a senha.
        send_mail(subject, message, from_email, [self.email], **kwargs)

DICA:
Se usar no settings.py
LANGUAGE_CODE = 'pt-BR'

QUASE toda as palavras padrões como email,user estão na interface (site) mensagem de erro , texto de ajuda (help text) estarão em Português.
link de métodos de login 1: https://medium.com/@gabrielfgularte/custom-user-model-no-django-d9bdf2838bd8
link de 4 métodos de login 2:(esta em ingles) https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
Espero que tenha ajudado. Abraço.


text:
Q: Why Styled- components doesn´t work in react I try to use styled-component in react but I am always getting error
Failed to compile.

./src/Components/Header/style.js
Module not found: Can't resolve 'styled-components' in 'C:\Users\Dell\Desktop\luna\src\Components\Header'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\pagefile.sys'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\swapfile.sys'

My Header.js
import React from 'react';
import {HeaderStyle} from './style';

const Header =()=>{
    return(
        <HeaderStyle>

Luna

        </HeaderStyle>
    )
}

export default Header ;

style.js
import styled from "styled-components";

export const HeaderStyle = styled.section`
    background-color:black;
`

Do you have any ideas why It doesn´t work?


text:
Q: Asynchronous confusion with ItemFileReadStore query I want to save the results from a query using itemFileReadStore into an array called boxes, but the return value is empty (presumably because fetch is run asynchronously).
The gotItems function builds the array as I want it to, but I can't return that back to myself for any use! I could build the rest of my functionality into the gotItems part, but that would make my code unpretty.
How do I return an array for general use in my JavaScript from the gotItems function?
function getContentFile() {
  contentStore = new dojo.data.ItemFileReadStore({
    url: '../config/content.json',
preventCache : true
  });

  var boxes = new Array();
  contentStore.fetch({query: {partner : 'enabled'}, onItem: gotItems });
  return boxes;
}

function gotItems(item ) {
  boxes.push( contentStore.getValue(item,'title') );
  console.log( boxes );
  return boxes;
}

dojo.addOnLoad( function() {
  boxes = getContentFile();
  console.log(boxes);
  fadeIn('header', 500, 0);
});

A: Welcome to the world of asynchronous operations.
You'll need to do it with the "continuation-style" programming.  ItemFileReadStore's fetch operations is asynchronous -- as you already know by passing the gotItems continuation to it.
contentStore.fetch({query: {partner : 'enabled'}, onItem: gotItems }) will return immediately.  Your boxes will be empty at that point (because JavaScript is single-threaded).  gotItems is executed after data arrived and subsequent to the function passed to dojo.addOnLoad returning.
You have to put your handling code:
  console.log(boxes);
  fadeIn('header', 500, 0);

inside the continuation gotItems itself.  For example, something like:
function gotItems(item ) {
  var boxes = [];
  dojo.forEach(item, function(box) {
    boxes.push( contentStore.getValue(box,'title') );
  });
  console.log(boxes);    // You probably need to store "boxes" somewhere instead of just logging it
  fadeIn('header', 500, 0);
}

Also, the data passed to onItems is an array, so you need to iterate it.

A: You don't have access to the results when the function returns because as you guessed, the fetch operation executes asynchronously.
You can either put the code that uses the results in your gotItems() function (as answered by Stephen), or you can use Deferreds and Promises. IMHO, that's a better alternative since it lets you organize your code better (once you get used to the idioms of dealing with promises, the code reads more naturally) and it allows you to transparently execute both synchronous and asynchronous operations.
See these two Dojo tutorials on the subject.
In your case, a possible solution involving deferreds would read like:
function getContentFile() {
  contentStore = new dojo.data.ItemFileReadStore({
    url: '../config/content.json',
    preventCache: true
  });

  var dfd = new dojo.Deferred();
  var boxes = new Array();
  contentStore.fetch({
    query: { partner : 'enabled' },
    onItem: function(item) {
      boxes.push( contentStore.getValue(item,'title') );
    },
    onComplete: function() {
      // resolve the promise and execute the function in then()
      dfd.callback(boxes);
    }
  });
  return dfd;
}

dojo.addOnLoad( function() {
  getContentFile().then(function(boxes) {
    console.log(boxes);
    fadeIn('header', 500, 0);
  });
});


text:
Q: vidyo.io: Moving and resizing a video using VidyoConnector API I downloaded the latest iOS package from vidyo.io and have successfully built my application integrated with the Vidyo libraries and using the VidyoConnector API.
When my app first comes up, I was very happy to see that a preview video appears on the screen just where I'd expect it to be! However, when moving the view to a different location, the video did not render quite how I intended.
The video did move to the x/y position on screen that I'd hoped but the size did not adjust to my new view dimensions. Then I found the VidyoConnectorShowViewAt API call and that did indeed resize my view but the positioning of the video then was off.
Is this the correct call to make when moving and resizing a view? Does anybody have any ideas what I could be doing wrong? Any help would be appreciated.

A: Sounds like you are pretty close. If you are just moving your view to different coordinates without resizing, then no API call is necessary. But if also resizing, then indeed use VidyoConnectorShowViewAt. My hunch is that your coordinates that you are passing are off, as x and y should be relative to the view itself and not to the main view. So try passing 0 and 0 as x and y and see if that helps.


text:
Q: How can I dynamically import in a NextJs page data (array) not entire component Hi all I followed the next tutorial
https://nextjs.org/docs/advanced-features/dynamic-import
and works great for components
But I need to fetch data dynamically.
Situation:
I have one simple component named MyItems that receives as props items which is a list of elements title, category.
I want to dynamically import these lists from typescript files stored in page-data/myitems/de|en.ts and so on
So these ts files export array  after doing some calculations that is why i don't import json dynamically or search for other solution. I need them to have code and export an array
export default [{name: 'somename', title: somemagic()]
I have this page in pages/page
const Page = async ({ t, ...props }: Props) => {
    const locale = props._nextI18Next.initialLocale;

    const items = (await import(`../page-data/myitems/${locale}`)).default;
    console.log(items); // HERE I SEE OUTPUT FINE

    return (
        <>
            <Head>
                <title>dynamic test</title>
            </Head>
            {/*@ts-ignore*/}
            <MyPage items={items} />
        </>
    );
};

The error I get is that cannot return promise to react
So my understanding is that I cannot export async component.
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

That is all fine, so my question is howcan I solve this situation then ?
The goal is still the same (items are fetched fine now but the component is returned as promise due to async and rest of react magic fails)

A: I have solved this issue myself and am posting the solution for anyone facing the same issue.
So summarized
You still import dynamically one react component, but the "localized" react component relies on the common page. For example page-en.tsx imports page.tsx (see below)
This will be your NextJs main page:
import React from 'react';

import dynamic from 'next/dynamic';

const Page = ({ t, ...props }: Props) => {
    const locale = props._nextI18Next.initialLocale;
    const nt = scopedT(t, T_NAMESPACE);

    const DynamicComponent = dynamic(() => import(`../page-data/mypage/${locale}`));

    return (
        <>
            <Head>
                <title>{nt('pageTitle')}</title>
            </Head>
            {/*@ts-ignore*/}
            <DynamicComponent />
        </>
    );
};

and this will be your page-data/mypage/en|de|whateverlang.tsx
const En: React.FC = () => {
    return <MyPage items={getItemsForLocale('en')} />;
};


text:
Q: Fired a event when scroll to down for dropdown I want to fired a event when dropdown is scrolled to down.
My .ts look like this
@HostListener('window:scroll', ['$event'])
     onWindowScroll(): void {
            let position = (document.documentElement.scrollTop || document.body.scrollTop) + document.documentElement.offsetHeight;
            let maximum = document.documentElement.scrollHeight;
            if(position >= maximum )   {
                console.log(document.body.className);
            }
      }

but it works for whole page not for dropdown
 My html looks like this
<ng-select #postCodeDD [items]="postCodes" bindLabel="displayName"
                                                bindValue="id" class="width-percent-100 scroll-event-fordropdown" name="CodeCode"
                                                placeholder="select postcode" appendTo="body"
                                                (change)="CodeChange($event)" [virtualScroll]="true"
                                                [selectOnTab]="true" [(ngModel)]="patientEntry.postCodeId">
                                            </ng-select>

A: You can use (scrollToEnd) event provided by the ng-select. For use that needs to enable virtual scroll like this [virtualScroll] = 'true'.
Refer this: https://github.com/ng-select/ng-select


text:
Q: Cant reach mongo db container I trying to implement a dockerized mongo/node based app by this article.
docker-compose.yml
version: '3'
services:
  gecar_app:
    build:
      context: .
      dockerfile: Dockerfile.gecars
    restart: always
    ports:
      - 3000:3000
    depends_on:
      - mongo
    command: /usr/app/initAndStartService.sh
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"

Dockerfile.gercars
FROM node:latest
RUN mkdir -p /usr/app
WORKDIR /usr/app
COPY src/ /usr/app/src/
COPY package.json /usr/app/package.json
COPY webpack.config.js /usr/app/webpack.config.js
COPY tsconfig.json /usr/app/tsconfig.json
COPY initAndStartService.sh /usr/app/initAndStartService.sh
RUN yarn
RUN yarn build

RUN ["chmod", "+x", "/usr/app/initAndStartService.sh"]

initAndStartService.sh
#!/bin/sh
curl 127.0.0.1:27017

but when run docker-compose up get this:
mongo        | 2019-11-19T06:13:21.682+0000 I  NETWORK  [initandlisten] Listening on 0.0.0.0
mongo        | 2019-11-19T06:13:21.683+0000 I  NETWORK  [initandlisten] waiting for connections on port 27017

...................
gecar_app_1  |                                  Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (7) Failed to connect to 127.0.0.1 port 27017: Connection refused

If I recognize the situation correctly, gecar_app_1 container cant reachmongo` container.

A:
depends_on
Express dependency between services, Service dependencies cause the
  following behaviors:
docker-compose up starts services in dependency order. In the following example, db and redis are started before web.

docker-compose up SERVICE automatically includes SERVICE's dependencies. In the following example, docker-compose up web also

creates and starts db and redis.
docker-compose stop stops services in dependency order. In the following example, web is stopped before db and redis.

in other words, when you want to communicate with the mongo container, all you have to do is to call it as mongo based on your container service naming.
So curl mongo:27017 from the gecar_app container will do the trick

A: 127.0.0.1 is a loopback address, this mean, when you run curl 127.0.0.1:27017 on gecar_app container, you try to connect to itself, but gecar_app did not have any service running on 27017 port. What you need to connect is mongo service (I think so).
You use depends_on to wait until the mongo service started, then start the gecar_app container (good point), now mongo will be come to a hostname, and gecar_app can connect to mongo via mongo "domain".
But, gecar_app maybe started before mongodb service already, then you have make sure that when mongo service already. You can use healthcheck property to do that.
Finally,
docker-compose.yml
version: '3'
services:
  gecar_app:
    build:
      context: .
      dockerfile: Dockerfile.gecars
    restart: always
    ports:
      - 3000:3000
    depends_on:
      - mongo
    command: /usr/app/initAndStartService.sh
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
    healthcheck:
      test: echo 'db.runCommand("ping").ok' | mongo mongo:27017/test --quiet 1
      interval: 3s
      timeout: 5s
      retries: 5

and, initAndStartService.sh
#!/bin/sh
curl mongo:27017


text:
Q: javascript bigint conversion To represent balance as u128, we assume that the smallest decimal is 15. i.e the smallest unit is  1e-15. Now, I need the following functionalities:
(1) convert between float to big number integer e.g. 0.001$ is 0.001*1e15=1e12 as bignumber integer.
(2) convert the balance into byte array, either big endian or small endian, so that I can sign on it.
The library I used before is "bn.js". It supports (2), however, if I want to convert 1000$ as bigint by using:
let amt = new BN(1e18, 10)

I will get error, because bn.js requires the number to be less than 2^53, but 1e18>2^53. This is just against the point of big number! Here is the link to this restriction:
https://github.com/indutny/bn.js/blob/master/lib/bn.js#L128
There are some other libraries such as bignumber.js I check, but they doesn't support (2).

A: Check out this GitHub repo: https://github.com/peterolson/BigInteger.js/
let amt = bigInt("1e18");

or you can use a different base:
let largeHexValue = bigInt("FFFFF",16)


text:
Q: Can a fraction be simplified like this? Ridiculously embarrassing question, but can $\frac{x^2-x}{x^2-25}$ be simplified to simply $\frac{1-x}{1-25}$?
Full thought process here is that this is essentially $\frac{x*x-x}{x*x-25}$ so the $x$s should cancel.  The full problem is:$$\frac{x^2-x-30}{x^2-25}$$
sorry
I'm used to programming forums where a simplest-case example of an error is the way to ask about it.  I should have made the full problem clearer earlier as $-$ unfortunately $-$ this lead to someone who gave more information being wrong at the final problem and I can't mark both answers right.

A: If you are unsure, then one way to check whether things like this might be true is to plug in a value for $x$.  Let $x = 2$.  We get:
$$\frac{x^2-x}{x^2 - 25} = \frac{2}{-21} \neq \frac{1-x}{1-25} = \frac{-1}{-24} = \frac{1}{24}$$
So in this case, you made a mistake somewhere.
Of course, if you plug in a value and equality does hold, then that doesn't imply it always holds.  E.g. $2x \neq x^2$ in general even though it holds when $x = 2$.

A: No.  If you want to divide numerator and denominator by $x^2$, you will get $\dfrac{1-\frac1x}{1-\frac{25}{x^2}}$, which isn't really simpler.  If you really want to do something to simplify it, you can rewrite it as
$$\frac{x^2-25-x+25}{x^2-25}=\frac{x^2-25}{x^2-25}+\frac{-x+25}{x^2-25}=1+\frac{25-x}{x^2-25}$$

A: To simplify a fraction, you want to factor the numerator and denominator and see what cancels.  The denominator $x^2-25$ is a difference of squares:  $x^2-25=(x+5)(x-5)$, so see if either of those factors divides the numerator.  When you say $x$s should cancel you should understand that "cancel" means "divide by".  The $25$ term does not have a factor of $x$, so you can't cancel it.

A: $\displaystyle \frac{x^2-x-30}{x^2-25}=\frac{(x-6)(x+5)}{(x-5)(x+5)}=\frac{x-6}{x-5}$


text:
Q: jquery ajax form plugin submit multiple times to the server only when using IE6 I all.
I have the following form used to temporarily upload a photo on a j2ee server and then crop it with imageAreaSelect plugin :
<form name="formAvatarName" id="formAvatar" method="post"
action="../admin/admin-avatar-upload"
enctype="multipart/form-data">
Upload a Picture of Yourself
<input type="file" name="upload" id="upload" size="20" />
<input type="button" id="formAvatarSubmit" value="formAvatar" onclick="invia()"/>
</form>

I am using jquery form plugin to do ajax submission, this is my last :) attempt :
var options = {
    beforeSubmit:  showRequest,  // pre-submit callback
    success:       showResponse,  // post-submit callback
    dataType:  'text/html'
};

   $('#formAvatar').unbind('submit').bind('submit', function() {
     alert('aho');
        $(this).ajaxSubmit(options);
        return false;
   });

Here below the javascript functions used as submit event handlers:
    function showRequest(formData, jqForm, options) {
        var queryString = $.param(formData);
        log.debug('About to submit: \n\n' + queryString);
        return true;
    }

    function showResponse(responseText, statusText, xhr, $form)  {
        myRes=responseText;
        log.debug('status: ' + statusText + '\n\nresponseText: \n' + responseText);

        //box uploaded
        $('div#avatar-upl > img').replaceWith(myRes);
        var origWidth = $('div#avatar-upl > img').width();
        var origHeight = $('div#avatar-upl > img').height();
        log.debug('AjaxUpload onComplete(): orig size w,h : ' + origWidth + ', ' + origHeight);

        //scaling uploaded
        $('div#avatar-upl > img').jScale(
                {ls:'300px'},
        function(){
                var scaleWidth = $(this).width();
                var scaleHeight = $(this).height();
                log.debug('AjaxUpload onComplete(): scaled size w,h : ' + scaleWidth + ', ' + scaleHeight);
                //put scaled sizes on img custom attribute, to be retrieved from preview() method
            $('div#avatar-upl > img').attr('scaleWidth', scaleWidth);
                $('div#avatar-upl > img').attr('scaleHeight', scaleHeight);
            }
        );

        //box thumbnail
        $('div#avatar-thumb > img').replaceWith(myRes);
        $('div#avatar-thumb > img').css({
        width: 100,
        height: 100
    });

    //setup of imgAreaSelect
    $('div#avatar-upl > img').imgAreaSelect({
        handles: true,
        onSelectEnd: avatarPreview
    });
}

This is the html :

    <form name="formAvatarName" id="formAvatar" method="post" action="../admin/admin-avatar-upload" enctype="multipart/form-data">
        Upload a Picture of Yourself
        <input type="file" name="upload" id="upload" size="20" />
        <input type="button" id="formAvatarSubmit" value="formAvatar" onclick="invia()"/>
    </form>

Only when tested with IE6 I can see that the sumbission to the server is done multiple times (first time I got the uploaded file, the other times the sumbmission seems empty and I got error). With IE7, IE8, FFOX, CHROME is working fine.
Any Ideas?
Many thank in advance!

A: It seems very likely that you're not getting as far as return false -- thus IE goes ahead and submits the form in the "natural" way, as well as by ajaxSubmit(). Your options specify a success callback. What does showResponse() look like? Perhaps something in showResponse() is tripping up IE so that it fails to run return false. I'd start by trying your code without the success callback, and going from there.


text:
Q: in-amp for strain gauge I'm working on a project where I should send an overload signal if the strain is bigger than 40 ppm.
So far I found this answer:
Strategy to balance a Wheatstone bridge for strain measurement
The wheatstone bridge consists 2x 120 ohm, GF 2 strain gauge and two 120 ohm 0.1% resistor.
Using the answer above I'd make it so that at 40 ppm the in-amp's output would drive a JFET.
I think that a ina-128 would be a good choice, but the power source is x piece 1,5 V battery so I'd need 4.
Is it a good choice, can you recommend a better for this application?

A: Shopping questions area off-topic, but in general terms I would definitely go for one of the newer type of "zero drift" instrumentation amplifier that has a maximum supply voltage of ~5V or less.
Go to either a manufacturer (TI, AD, etc.) or to a distributor such as Digikey and do a parametric search, then compare datasheets.
A quick search yields, for example, the AD8237 which sports a 115uA current drain at 1.8 to 5.5V and 75uV maximum Vos.


text:
Q: How can I make my code in compliance with MISRA 2012 RULE10.4     if(fn1())   //Line 1
     {
     a++;
     }

Here the return type of function fn1 is uint8_t. The function returns only values 0 or 1.
PC Lint throws error for line 1 says "Mismatched essential type categories for binary operator" [RULE 10.4 required]
Rule 10.4 says "Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category"

A: MISRA-C doesn't allow implicit checks against zero - all inputs to conditional statements must be "essentially boolean", which is what you get if you explicitly use logical operators like ==.
In addition, MISRA-C has various rules blocking you from mixing "essenitally signed" and "essentially unsigned" in the same expression, and thereby relying on implicit type promotions. So you can't write if (fn1() == 1) for that reason, since 1 is a signed type and there's also a rule requiring all integer constants to have u suffix.
So one possible fix is if (fn1() == 1u). However, since the function only returns 0 or 1, you can also cast its result to boolean type and that would be fine too: if ((bool)fn()). The best solution is however to rewrite the function to return bool, after which you can use if(fn1()).


text:
Q: Changing indentation of pseudocode including line numbers with algorithm and algorithmic If I have pseudocode as shown below using the algorithm and algorithmic packages, is it possible to indent the pseudocode, including the line numbers, so that it lines up with the indentation of the first line of the paragraph above, i.e. so that the line numbers of the pseudocode are indented as much as the first line of the paragraph above.

A: This is one possible solution via adjustwidth environment from changepage package. It takes two arguments.
As to the par indention value, please check HERE
\begin{adjustwidth}{left indent}{right indent}
\begin{algorithmic}[1]
content
\end{algorithmic}
\end{adjustwidth}

Code
\documentclass[12,a4paper]{article}
\usepackage[showframe,papersize={\paperwidth,8cm}]{geometry}
\pagestyle{empty}
\usepackage{algorithmic}
\usepackage[plain]{algorithm}
%\usepackage{algpseudocode}
\usepackage{changepage}    %adjustwidth environment from changepage package

\begin{document}

Paragraph text, Paragraph text, Paragraph text, Paragraph text, Paragraph text, Paragraph text, Paragraph text, Paragraph text,

\begin{algorithm}
\begin{adjustwidth}{1em}{}
\begin{algorithmic}[1]
\STATE{\textit{pollingDateTime $\leftarrow$ now $-$ 1 hour}}
\FOR {\textbf{each} rssFeed}
\STATE {\textit{pollingDateTime $\leftarrow$ now $-$ 1 hour}}
\ENDFOR
\IF {\textit{pollingDateTime is even}}
\STATE {\textit{pollingDateTime $\leftarrow$ now $-$ 1 hour}}
\ENDIF
\end{algorithmic}
\caption{Algorithm 1}\label{alg1}
\end{adjustwidth}
\end{algorithm}
\end{document}


text:
Q: net::ERR_CONTENT_LENGTH_MISMATCH on angular 2 on docker cloud I am getting a net::ERR_CONTENT_LENGTH_MISMATCH  main.bundle.js  while running angular 2 on docker cloud ,the same however works on my local docker instance
The below is the docker file
FROM node

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

COPY . /usr/src/app

RUN npm install

and the docker compose
version: '2'
services:
app:
 build: .
 volumes:
   - ./:/usr/src/app
 ports:
   - 4200:4200
   - 49153:49153
 command: npm start

Any clue as to why this is happening will be of much help

A: Happened to me after I updated one of the packages in node_modules. Probably integrity/checksum-related issue. The cure was to flush node_modules and run
$ npm install
again.