text:
Q: How to automatically add many variables in a loop-for-count in CLIPS? I want to use a loop-for-count to loop many different variables to let user input and let CLIPS read the variables.
For example:
Question: "How many dependent you wish to add?"
Answer: 5.
Then the CLIPS should create the variables like:
name1
name2
name3
name4
name5
Here is my code:
(printout t "How many dependent you wish to add? (Must have atleast 1): ")
    (bind ?DepNo (read))
    (assert (DepNo ?DepNo))
    (loop-for-count (?DepNo 1 ?DepNo) do
        (printout t "Name: ")
        (bind $?DepName (explode$ (readline)))
        (assert (DepName $?DepName))

    )

A: Create a multifield value to hold all of the dependent names:
         CLIPS (6.31 6/12/19)
CLIPS>
(defrule get-dependents
   =>
   (printout t "How many dependent you wish to add? (Must have at least 1): ")
   (bind ?DepNo (read))
   (bind ?depNames (create$))
   (loop-for-count ?DepNo
      (printout t "Name: ")
      (bind ?depNames (create$ ?depNames (readline))))
   (assert (DepNames ?depNames)))
CLIPS>
(defrule print-names
   (DepNames $?depNames)
   =>
   (printout t "Dependents are: ")
   (foreach ?d ?depNames
      (printout t "   " ?d crlf)))
CLIPS> (reset)
CLIPS> (run)
How many dependent you wish to add? (Must have at least 1): 3
Name: Sally Jones
Name: Fred Jones
Name: David Jones
Dependents are:
   Sally Jones
   Fred Jones
   David Jones
CLIPS> (facts)
f-0     (initial-fact)
f-1     (DepNames "Sally Jones" "Fred Jones" "David Jones")
For a total of 2 facts.
CLIPS>


text:
Q: Identifying absolute phrase In an exercise I had to find how the participle was used in sentences.
One of the sentence was--

The traveller, being weary, sat by the wood side to rest.

Its answer was

being - present participle, Absolute phrase.

Why it is an absolute phrase I don't understand.

A: An absolute phrase is a phrase that modifies/describes a noun within the sentence but is not connected to the rest of the sentence by a conjunction.
In your example, being wary describes the traveler and does not use a conjunction (because, and, so, but, yet . . .).
There are two verbs in your sentence. The main verb is sat (to sit, past tense). The second verb is being (to be, present tense) and it is part of the phrase that describes the traveler, not saying what the traveler is doing.
Contrast this with:

The traveler was weary.
The traveler sat by the wood side to rest because she was weary.

In these examples, the verb to be is functioning as the main verb or is more strongly joined to the rest of the sentence through the conjunction because.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you set the tab width using images for each tab and ActionBarSherlock I can create five tabs using ActionBarSherlock that will not scroll and all fit on the screen.  After I set one of the tabs to use an image, all the tabs become as wide as that tab, which itself becomes larger than the image I am using.  How can I show five tabs, each with an image?  I do not want them to scroll, but all be visible at once.  Here is how I am setting the tab with the image:
tab1.setIcon(R.drawable.tab_home_unselect);

A: I guess you ll have to play with padding, marging, layout, and the size of your image...
Here is an example of tab layout with image and text :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/tab_item"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="2dip" >

    <ImageView
        android:id="@+id/tab_icon"
        android:layout_width="28dip"
        android:layout_height="28dip"
        android:layout_marginBottom="1dip" />

    <TextView
        android:id="@+id/tab_title"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_marginBottom="2dp"
        android:layout_weight="1"
        android:gravity="center"
        android:textColor="@android:color/white"
        android:textSize="12sp" />

</LinearLayout>

and the method to add them
private View getTabIndicator(String text, int drawable) {

    View indicator = _inflater.inflate(R.layout.abs_tab, null);
    ((TextView) indicator.findViewById(R.id.tab_title)).setText(text);
    ((ImageView) indicator.findViewById(R.id.tab_icon)).setImageResource(drawable);
    return indicator;
}


text:
Q: Unit testing Polymer listener that uses this.fire I have a Polymer element that is set up something like this:
Polymer({

  is: 'some-element',

  properties: {
    //properties
  },

  listeners: {
    'something-happened': '_onSomethingHappening'
  },
  someFunction: function() {},

  anotherFunction: function() { // something-happened listener is executed here},

  _onSomethingHappening: function(e) {
      this.fire('it-happened', {e.someInfo});
  }
})

I have unit tested all functions, but I need to test for the _onSomethingHappening event. I try to capture the return value of the this.fire event, but this doesn't work. The unit test I have in mind is something like this:
test('_onSomethingHappened', function() {

    var ev = some-element._onSomethingHappened();
    assert(typeof ev, 'object');

});

The thing is, when I do this, it says that no event was passed to the listener, so therefore the test fails. Is there a way I could structure this test to make it work? Is there a way to say "assert that a JS .fire event was executed"?

A: With Web Component Tester, you could use a SinonJS spy on your test fixture's fire method, and assert that it was called with specific parameters.
test.html:
<test-fixture id="basic">
  <template>
    <my-list></my-list>
  </template>
</test-fixture>

<script>
  describe('my-list', function() {
    var list;

    beforeEach(function() {
      list = fixture('basic');
    });

    it('fires "foo" event with {bar: xxx}', function() {
      sinon.spy(list, 'fire');

      var e = {someInfo: 100};
      list._onSomethingHappened(e);
      expect(list.fire).to.have.been.calledWith('foo', {bar: e.someInfo});
    });
  });
</script>

Alternatively, you could test that the element emitted the event.
describe('my-list', function() {
  ...
  it('emits "foo" event with {bar: xxx}', function() {
    list._onTestFoo = sinon.spy();
    list.listen(list, 'foo', '_onTestFoo');

    var e = {someInfo: 100};
    list._onSomethingHappened(e);
    expect(list._onTestFoo).to.have.been.called;
    expect(list._onTestFoo.args[0][0].detail).to.deep.equal({bar: e.someInfo});
  });
});

The Polymer Test Guide and Polymer Starter Kit's test/my-list-basic.html could be helpful as a starting point.


text:
Q: Endlessh "Failed to start Endlessh SSH Tarpit" I have just learned about Endlessh package, I have installed following steps described in this video https://www.youtube.com/watch?v=SKhKNUo6rJU
But when it comes to check if Endlessh is listenning port 22 nothing happens, Then, I checked the status to see if it's running but it doesn't, here the result I have :
xxxxxxxxx@localhost:~$ sudo systemctl status endlessh.service
● endlessh.service - Endlessh SSH Tarpit
     Loaded: loaded (/etc/systemd/system/endlessh.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Mon 2022-01-03 13:14:16 CET; 2min 32s ago
       Docs: man:endlessh(1)
    Process: 186607 ExecStart=/usr/local/bin/endlessh (code=exited, status=1/FAILURE)
   Main PID: 186607 (code=exited, status=1/FAILURE)

Jan 03 13:13:46 localhost systemd[1]: endlessh.service: Main process exited, code=exited, status=1/FAILURE
Jan 03 13:13:46 localhost systemd[1]: endlessh.service: Failed with result 'exit-code'.
Jan 03 13:14:16 localhost systemd[1]: endlessh.service: Scheduled restart job, restart counter is at 4.
Jan 03 13:14:16 localhost systemd[1]: Stopped Endlessh SSH Tarpit.
Jan 03 13:14:16 localhost systemd[1]: endlessh.service: Start request repeated too quickly.
Jan 03 13:14:16 localhost systemd[1]: endlessh.service: Failed with result 'exit-code'.
Jan 03 13:14:16 localhost systemd[1]: Failed to start Endlessh SSH Tarpit.
Jan 03 13:15:59 localhost systemd[1]: endlessh.service: Start request repeated too quickly.
Jan 03 13:15:59 localhost systemd[1]: endlessh.service: Failed with result 'exit-code'.
Jan 03 13:15:59 localhost systemd[1]: Failed to start Endlessh SSH Tarpit.

while looking further answers to my issue, I found on github of skeeto/endlessh, this :
https://github.com/skeeto/endlessh/issues/39#issuecomment-727283671
I tried but I still get the same Failure status when restarting endlessh.
I forgot to mention that I create a config file in endlessh folder /etc/endlessh/config:
# The port on which to listen for new SSH connections.
Port 22

# The endless banner is sent one line at a time. This is the delay
# in milliseconds between individual lines.
Delay 10000

# The length of each line is randomized. This controls the maximum
# length of each line. Shorter lines may keep clients on for longer if
# they give up after a certain number of bytes.
MaxLineLength 32

# Maximum number of connections to accept at a time. Connections beyond
# these are not immediately rejected but will wait in the queue.
MaxClients 4096

# Set the detail level for the log.
# 0 = Quiet
# 1 = Standard, useful log messages
# 2 = Very noisy debugging information
LogLevel 0

# Set the family of the listening socket
# 0 = Use IPv4 Mapped IPv6 (Both v4 and v6, default)
# 4 = Use IPv4 only
# 6 = Use IPv6 only
BindFamily 0

Do you have any ideas what is wrong ? should I restart the server ?
Thank :)


text:
Q: C# switching windows in .net Hi I'm trying to switch windows to other programs that are running (even if minimized) using C#.
I'm wondering why this won't work.
Error message:
Argument 1: cannot convert from 'System.Diagnostics.Process' to 'System.IntPtr'
By the time it hits the loop I would think that the proc variable would refer to the appropriate window handler.  Is this not true?
I really appreciate the help.
//declarations
using system.IO;
using System.Runtime.InteropServices;
//more

//namespace here

//class here

//initialize method

//related .dll import
[DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd);

String ProcWindow = "itunes";
//function which calls switchWindow() is here but not important

//now we have switch window.
private void switchWindow()
        {
            Process[] procs = Process.GetProcessesByName(ProcWindow);
            foreach (Process proc in procs)
            {
                //switch to process by name
                SwitchToThisWindow(proc);

            }
        }

For future readers:
I got to this point in my code from another question.
Correct way (in .NET) to switch the focus to another application

A: SwitchToThisWindow is expecting a handle to the window that you want to switch to in that process.
Try
SwitchToThisWindow(proc.MainWindowHandle);

A: I believe what you want is:
[DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool turnon);

String ProcWindow = "itunes";
//function which calls switchWindow() is here but not important

//now we have switch window.
private void switchWindow()
{
  Process[] procs = Process.GetProcessesByName(ProcWindow);
  foreach (Process proc in procs)
  {
     //switch to process by name
     SwitchToThisWindow(proc.MainWindowHandle, false);

  }
}

SwitchToThisWindow expects an IntPtr that is a handle to a window, not a process which is what you were trying to pass in.
Also note that your pinvoke signature for SwitchToThisWindow appeared to be incorrect, you were missing the bool parameter.


text:
Q: Is there a way to dynamically load a properties file in NAnt? I want to load a different properties file based upon one variable.
Basically, if doing a dev build use this properties file, if doing a test build use this other properties file, and if doing a production build use yet a third properties file.

A: You can use the include task to include another build file (containing your properties) within the main build file. The if attribute of the include task can test against a variable to determine whether the build file should be included:
<include buildfile="devPropertyFile.build" if="${buildEnvironment == 'DEV'}"/>
<include buildfile="testPropertyFile.build" if="${buildEnvironment == 'TEST'}"/>
<include buildfile="prodPropertyFile.build" if="${buildEnvironment == 'PROD'}"/>

A: I had a similar problem which the answer from scott.caligan partially solved, however I wanted people to be able to set the environment and load the appropriate properties file just by specifying a target like so:

*

*nant dev

*nant test

*nant stage

You can do this by adding a target that sets the environment variable. For instance:
<target name="dev">
  <property name="environment" value="dev"/>
  <call target="importProperties" cascade="false"/>
</target>

<target name="test">
  <property name="environment" value="test"/>
  <call target="importProperties" cascade="false"/>
</target>

<target name="stage">
  <property name="environment" value="stage"/>
  <call target="importProperties" cascade="false"/>
</target>

<target name="importProperties">
  <property name="propertiesFile" value="properties.${environment}.build"/>
  <if test="${file::exists(propertiesFile)}">
    <include buildfile="${propertiesFile}"/>
  </if>
  <if test="${not file::exists(propertiesFile)}">
    <fail message="Properties file ${propertiesFile} could not be found."/>
  </if>
</target>

A: Step 1: Define a property in your NAnt script to track the environment you're building for (local, test, production, etc.).
<property name="environment" value="local" />

Step 2: If you don't already have a configuration or initialization target that all targets depends on, then create a configuration target, and make sure your other targets depend on it.
<target name="config">
    <!-- configuration logic goes here -->
</target>

<target name="buildmyproject" depends="config">
    <!-- this target builds your project, but runs the config target first -->
</target>

Step 3: Update your configuration target to pull in an appropriate properties file based on the environment property.
<target name="config">
    <property name="configFile" value="${environment}.config.xml" />
    <if test="${file::exists(configFile)}">
        <echo message="Loading ${configFile}..." />
        <include buildfile="${configFile}" />
    </if>
    <if test="${not file::exists(configFile) and environment != 'local'}">
        <fail message="Configuration file '${configFile}' could not be found." />
    </if>
</target>

Note, I like to allow team members to define their own local.config.xml files that don't get committed to source control.  This provides a nice place to store local connection strings or other local environment settings.
Step 4: Set the environment property when you invoke NAnt, e.g.:

*

*nant -D:environment=dev

*nant -D:environment=test

*nant -D:environment=production

A: The way I've done this kind of thing is to include seperate build files depending on the type of build using the nant task. A possible alternative might be to use the iniread task in nantcontrib.


text:
Q: One launch per 10 seconds I'm creating a scroll down page auto load data. But when I scroll down the page getPosts function working more than one. When I alert() after function, there is no problem. How can I block multi launching when page scolling down?

var _primary = 0;
var _second = 15;
$(document).ready(function() {
  getPosts(_primary, _second);
});

function getPosts(x, y) {
  $.ajax({
    type: "POST",
    dataType: "json",
    data: {
      uidHash: "<?php echo md5($_SESSION['uid'].'pass_!_'); ?>",
      minVal: _primary,
      maxVal: _second
    },
    url: 'postloader.php',
    success: function(posts) {
      $('#postholder').append(posts);
      _primary += 15;
      _second += 15;
    }
  });
}

$(window).scroll(function goDown() {
  if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
    getPosts(_primary, _second);
  }
});

A: In jQuery, check whether you have hit the bottom of page using scroll function. Once you hit that, make an ajax call (you can show a loading image here till ajax response) and get the next set of data, append it to the div. This function gets executed as you scroll down the page again.
$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
           // ajax call get data from server and append to the div
    }
});

OR Try this lib
http://imakewebthings.com/waypoints/
Below is the simple way of calling a waypoints plugin and having the page load more Content once you reaches the bottom on scroll :
$(document).ready(function() {
    var $loading = $("

Loading more items…

"),
    $footer = $('footer'),
    opts = {
        offset: '100%'
    };

    $footer.waypoint(function(event, direction) {
        $footer.waypoint('remove');
        $('body').append($loading);
        $.get($('.more a').attr('href'), function(data) {
            var $data = $(data);
            $('#container').append($data.find('.article'));
            $loading.detach();
            $('.more').replaceWith($data.find('.more'));
            $footer.waypoint(opts);
        });
    }, opts);
});

OR
<!DOCTYPE html>

    <title>Demo: Lazy Loader</title>

            Contents will load here!!!.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

A: You could just add a flag postsAlreadyCalled like :
$(window).scroll(function goDown() {
  if ($(window).scrollTop() + $(window).height() > $(document).height() - 100 && !postsAlreadyCalled) {
    getPosts(_primary, _second);
    postsAlreadyCalled = true;
  }
});

So the function will be called just one time.
Hope this helps.

var _primary = 0;
var _second = 15;
var postsAlreadyCalled = false;

$(document).ready(function() {
  getPosts(_primary, _second);
});

function getPosts(x, y) {
  console.log('Get data');
}

$(window).scroll(function goDown() {
  if ($(window).scrollTop() + $(window).height() > $(document).height() - 100 && !postsAlreadyCalled) {
    getPosts(_primary, _second);
    postsAlreadyCalled = true;

    setTimeout(function(){
        postsAlreadyCalled = false;
    },10000);
  }
});
#test{
  height: 1000px;
}


text:
Q: Multiple C++ .lib projects to .dll projects, Lua crashes! Today I've tried to get Edit & Continue to work in my solution, which looks like this:
Game Engine .lib <- Game .lib <- Editor .exe
                        <- Server .exe

                        <- Client .exe

Which works nicely. But now I wanted to turn the engine and game .libs into .dlls, so I can use the Edit & Continue feature of visual studio C++.
So I got a bunch of "__declspec(dllexport)"s in there, etc. works just fine, it runs!
But in certain situations it crashes. Actually, it always crashes in a Lua function that is related to freeing memory.
The engine and the game both work with Lua, they both have their own static C++ interface functions.
I am not certain, but I suppose a .dll is a bit like an .exe without a main function, and each has its own memory somehow. So when for example Game.dll causes Lua to allocate some memory, and Engine.dll causes Lua to free it again, boom! Correct?
Any ideas on how to solve this? Of course Engine.dll should be in charge of Lua, but Game.dll should be able to extend the interface with new static functions.
EDIT: There were no more crashes after I turned Lua itself into a .dll. Before I tried this I also recompiled the statics with the same compiler as all other projects, and I double checked the run time libs, and they are all the same, and I am linking to the right debug/release libs. I am still curious what's going on here.
Have a nice day,
Antoon
P.S. Why don't I have control over returns at Stackoverflow?

A: You wrote:

The engine and the game both work with Lua, they both have their own static C++ interface functions.

That suggests to me the possibility that the engine and game are each individually statically linked to a copy of Lua.
If that were true, then this is exactly what you would expect to happen if a Lua state created by one copy were passed to the other. The typical result is to mess up the memory state and break the allocator. The root cause is that the implementation of the value nil depends on the address of something inside the Lua engine. A second copy of the engine linked into the same process will have a different address serving as its notion of nil. That way eventually leads to madness.
Of course, if the game and engine share a single copy of the Lua interpreter (say by both using LUA51.DLL) then I'm barking up the wrong tree.

A: Maybe it's just me, but I find the information you included a bit sparse. Since you mentioned that your problems are related to memory allocations across module boundaries though, I would recommend the following article to you:
http://blogs.msdn.com/b/oldnewthing/archive/2006/09/15/755966.aspx
Basically, memory has to be freed using the same allocator that was used to allocate it, i.e. don't mix new / free - but it also means that you should not allocate and free memory across module boundaries, since modules might be compiled with different settings, for example, the debug allocator could differ from the one used in the release version, or it could be different due to different versions of the runtime being used (different release, different vendor etc.)
Most of the time it is safest to just handle memory allocations in a single module by providing a consistent interface that is used by every other module in your project.

A: Why do you think you need a DLL edit and continue? It works perfectly well on executables as well, as far as I have used it. Was there some particular error you're getting that is preventing you from using it?
DLLs do not get their own memory segment, but they may use their own allocation mechanism which may be incompatible. Please ensure that all DLLs and the main program link against the same version of the C Runtime Library (Debug or release, multi-threaded or non-multi-threaded, and the same version number).

A: I guess one DLL/EXE allocated the memory, and another tries to deallocate it, and crashes.
The solution is to make sure all your binaries are compiled with either :

*

*Debug Multithread DLL (/MDd) for debug builds

*Release Multithread DLL (/MD) for release builds

And of course, make sure all your DLLs/EXEs were compiled with the same compiler and options...
This is the only way for binaries (EXE and DLL) in the same process to share their memory allocators.


text:
Q: Cipher AES/CBC/PKCS5Padding cant decrypt after application reinitialization I'm trying to encrypt and decrypt some texts using Cipher with the "AES/CBC/PKCS5Padding" algorithm but if I restart the application the text that was encrypt can't be decrypted.
I'm encrypting the text, transforming the encrypted bytes in base64 text, storing it and retrieving it when necessary, so transforming the base64 text in bytes and trying to decrypt to take the original text.
The code I'm using is:
private static SecretKey getKeyFromPassword(String password, String salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(UTF_8),
            65536, 256);
    SecretKey secret = new SecretKeySpec(factory.generateSecret(spec)
            .getEncoded(), "AES");
    return secret;
}

private static IvParameterSpec generateIv() {
    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);
    return new IvParameterSpec(iv);
}

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        // string for test
        String teste = "teste teste teste teste";

        //getting start with Cipher
        SecretKey secretKey = getKeyFromPassword("pass", "salt");
        IvParameterSpec ivParameterSpec = generateIv();
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        //encrypting
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] cipherText = new byte[0];
        cipherText = cipher.doFinal(teste.getBytes(UTF_8));

        // encrypt to base64 text
        String criptado = Base64.getEncoder().encodeToString(cipherText);

        //decripting
        byte[] plainText = new byte[0];
        byte[] rawText = Base64.getDecoder().decode(criptado);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        plainText = cipher.doFinal(rawText);
        String decriptado = new String(plainText);

The problem is something with the size of the bit key? Like in this topic: java AES/CBC/PKCS5PADDING in php (AES-256-CBC) resulting different result
I took this guide to the code: baeldung.com/java-aes-encryption-decryption


text:
Q: Flutter StreamSubscription not stopping or pausing In my Flutter app StreamSubscription is not pausing or cancelling. When I call cancel() if it started before, it will stop. If I call cancel() after starting, it will not stop. I am using Firestore snapshot listener. Below is my code.
I have tried different methods but it's still not working. The problem is that the Firestore listener is not stopping after loading data.
    StreamSubscription<QuerySnapshot> streamSubscription;

    @override
    void initState() {
    super.initState();

        print("Creating a streamSubscription...");
        streamSubscription =Firestore.collection("name").document("d1").collection("d1")
            .snapshots().listen((data){
                //It will display items
            }, onDone: () { // Not excecuting
                print("Task Done");
            }, onError: (error) {
                print("Some Error");
        });
         streamSubscription.cancel(); //It will work but cancel stream before loading
    }

    @override
    void dispose() {
     streamSubscription.cancel(); //Not working
    super.dispose();
    }

A: When you push a new page, the previous page is still rendered and therefore dispose() is not called.

*

*How to get current route path in Flutter?
Also sometimes it can happen that the widget is not rendered anymore but dispose was not yet called, which can lead to weird error messages. So adding such a check is probably a good idea as well if you use dispose.

*

*https://docs.flutter.io/flutter/widgets/State/mounted.html
Change
//It will display items

to
if(myIsCurrentRoute && mounted) {
  //It will display items
}

A: You are not assigning the subscription into the right variable.
StreamSubscription<QuerySnapshot> subscription;

@override
void initState() {
super.initState();

    print("Creating a streamSubscription...");
    subscription=Firestore.collection("name").document("d1").collection("d1")
        .snapshots().listen((data){
            //It will display items
        }, onDone: () { // Not excecuting
            print("Task Done");
        }, onError: (error) {
            print("Some Error");
    });

     subscription.cancel(); //It will work but cancel stream before loading

}

@override
void dispose() {
 subscription.cancel(); //Not working
super.dispose();
}

A: I was experiencing the same problem and it turns out that the stream seems to keep listening for events for a while before canceling, but if you debug you will see that after dispose is called it will stop listening at some point.
Therefore, Gunter's solution works fine, since you can prevent your callback function from being called if mount is false, which means your page is no longer there.


text:
Q: How to delay an observable subscription to finish method execution from first observable In my angular2 app i want to execute observable subscriptions in sequence but i get error because 1st subscription has a method which i think takes a lot of time. I have services for different components so that they cache my data and available to all components. I am new to Http Observables and dont know the sequence in which they execute.
PriceList.service.ts
export class PriceListService
{
    private priceLists : PriceList[];
    private observable : Observable<any>;
    public getAll()
    {
        if(this.priceLists)
        {
            return Observable.of(this.priceLists);
        }
        else if (this.observable)
        {
            return this.observable;
        }
        else
        {
            this.observable = this.authHttp.get(this.appService.getApiUrl() + "api/price-list/list")
                .map(response => {
                    this.observable = null;
                    if(response.status == 400)
                    {
                        return "Failure";
                    }
                    else if(response.status == 200)
                    {
                        let myJson = response.json();
                        this.priceLists = myJson.data.priceList;
                        return this.priceLists;
                    }
                })
                .share();
            return this.observable;
        }
    }
}

Product.service.ts
export class ProductService
{
    products : Product[];
    observable : Observable<any>;
    priceLists : any;
    priceListMap : Map<number, any> = new Map<number, any>();
    defaultPriceList : Map<number, any> = new Map<number, any>();
    productMap : Map<number , any> = new Map<number , any>();
    defaultPriceListId : number;
    public getActiveProducts()
    {
        if(this.products)
        {
            return Observable.of(this.products);
        }
        else if (this.observable)
        {
            return this.observable;
        }
        else
        {
            this.observable = this.authHttp.get(this.appService.getApiUrl() + "api/product/list/active")
                .map(response => {
                    this.observable = null;
                    if(response.status == 400)
                    {
                        return "Failure";
                    }
                    else if(response.status == 200)
                    {
                        let myJson = response.json();
                        this.products = myJson.data.products;
                        this.getPriceLists();
                        return this.products;
                    }
                })
                .share();
            return this.observable;
        }
    }
    getPriceLists()
    {
        this.priceListService.getAll().subscribe(
            success => { this.priceLists = success; },
            error => {},
            ()=> { this.populatePriceListMap(); }
        );
    }
    populatePriceListMap()
    {
        for(let priceList of this.priceLists)
        {
            for(let product of this.products)
            {
                for(let prices of product.prices)
                {
                    if(priceList.id == prices.priceList.id)
                    {
                        this.productMap.set(product.id , {price : prices.price , discount : prices.discount});
                    }
                }
            }
            if(priceList.isDefault == 1)
            {
                this.defaultPriceList.set(priceList.id , this.productMap);
                this.defaultPriceListId = priceList.id;
            }
            this.priceListMap.set(priceList.id , this.productMap);
            this.productMap = new Map<number , any>();
        }
    }
    getDefaultList()
    {
        if(this.defaultPriceList){
            return Observable.of(this.defaultPriceList.get(this.defaultPriceListId));
        }
    }
}

ListProduct.component.ts
export class ListProductsComponent implements OnInit
{
    products:any = null;
    pricesMap : Map<number, any> = new Map<number, any>();
    prices:any = [];
    discounts:any = [];
    ngOnInit()
    {
        this.productService.getActiveProducts().subscribe(
            success =>{
                this.products = success;
            },
            error =>{},
            () =>{
                this.populatePrices();
            }
        );
    }
    populatePrices()
    {
        this.productService.getDefaultList().subscribe(
            success =>
            {
                this.pricesMap = success;
            },
            error =>{},
            ()=>{
                for (let product of this.products)
                {
                    let myObject = this.pricesMap.get(product.id);
                    this.prices[product.id] = myObject.price;
                    this.discounts[product.id] = myObject.discount;
                }
            }
        );
    }
}

Error

What it should do
I want my component to execute functions in this order.

*

*I want to execute getActiveProducts() so that my productService fetches products from api and stores them.

*I want to execute getPriceLists() of productService to fetch data from other service and store that in productService.

*I want to execute populatePriceListMap() so that it populates different properties of service.

*I want to execute populatePrices() in my component and assign values to different properties.
Problem i am facing
I think it executes step 1 and 4 while step 1 is doing its work. I want to display the properties being set in step 4 but it does not assign them and gives error.

A: You're setting this pricesMap variable in the onNext callback in subscribe, and then accessing it in the onCompleted callback.
You're obviously setting it to an undefined value which comes in through as a value. That's the error.
As for best practices, you might want to look at how to do Rx, in an Rx-like way.

A: If you can make both get calls in parallel (one call does not depend on the other, just the results need to be synched), then I would recommend using the forkJoin operator. It's to handle parallel calls where it waits until they're all complete before it pumps the results for each.
For example:
EDIT: Had a mistake previously: I put take(2) for the second observable when it should have also been to take(1)
var obs1 = this.authHttp.get(firstUrl).take(1);
var obs2 = this.authHttp.get(secondUrl).take(1);
Observable.forkJoin(obs1, obs2)
          .subscribe(responseArray => {
               // Do something
               // where responseArray[0] is the response you receive from the first get call, obs1
               // responseArray[1] is the response you receive from the second get call, obs2
          });

You can read more about it here: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/forkjoin.md
But, if you want to run them sequentially (the second get call needs parameters from the first get's response), then you're looking for the switchMap operator. So using the same obs1 and obs2 above, you'd want to do:
obs1.do(resp1 => {
       // Anything you want to do with the first response before you fire off the second one
  }).switchMap(obs2)
    .subscribe(resp2 => {
               // Do something
    });


text:
Q: how to use the index with springboot or JPA Table A

ID
shortdescription
thumbnailimage
linkactions
Country_id

165
shortdescription
thumbnailimage
linkactions
E1796BA

Table B

ID
name
Country_id

1
India
E1796BA

Controller
public ResponseEntity<ContentManagePageVO> queryAllActionsWithPagination(
@RequestParam(defaultValue = "0") Integer pageNo,
@RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(required = false, defaultValue = "") String filter) {
return ResponseEntity.ok(contentManageService.queryAllActionsWithPagination(filter, pageNo, pageSize));
    }

Service
   public ContentManagePageVO queryAllActionsWithPagination(String filter, Integer pageNo, Integer pageSize) {
        Pageable paging = PageRequest.of(pageNo, pageSize,Sort.by("id"));
        Page<ContentCountryDto> contentManagePage;
       if(StringUtils.isBlank(filter)) {
           contentManagePage = contentManageRepository.findAllPaging(paging);
       }else {
           contentManagePage = contentManageRepository.findByTitlePaging(filter, paging);
       }
        if (contentManagePage.isEmpty()) {
            log.error("No record found!!! ", filter);
            throw new GenericSuccessException(StaffNotificationExceptionEnum.CONTENT_MANAGE_PAGE_SEARCH_NOT_FOUND_EXCEPTION);
        }
        ArrayList<ContentManageVO> ContentManageVOList = new ArrayList<>();
        for (ContentCountryDto contentManage : contentManagePage) {
            ContentManageVO contentManageVO = new ContentManageVO();
            BeanUtils.copyProperties(contentManage, contentManageVO);
            ContentManageVOList.add(contentManageVO);
        }
        return ContentManagePageVO.builder()
                .page(contentManagePage.getNumber())
                .pageSize(contentManagePage.getSize())
                .result(ContentManageVOList)
                .total(contentManagePage.getTotalElements())
                .build();
    }

Repository
    @Transactional(rollbackFor = Exception.class)
    @Query("select new com.model.entity.ContentCountryDto (A.id, A.position ,A.title,A.shortdescription,A.thumbnailimage, A.linkactions, A.last_updated_date, A.last_updated_by, A.country.countryId, A.country.countryName, A.date_published) " +
            "from ContentManage as A inner join A.country as B where lower(A.title) like lower(concat('%', :filter,'%') ) or lower(A.shortdescription) like lower(concat('%', :filter,'%') ) or lower(B.countryName) like lower(concat('%', :filter,'%')) or lower(A.linkactions) like lower(concat('%', :filter,'%'))")
    Page<ContentCountryDto> findByTitlePaging(String filter, Pageable pageable);

I would like to add index to retrieve data from the database more quickly.
I have no idea on index, please suggest me how to achieve index in spring boot or JPA

A: The use of an index by a database engine is almost 100% independent of JPA and Spring Data JPA.
It works simply like this:
You add an index to the table as desired. You do that using SQL for your database and execute it with whatever tool you use to provision your database. Hopefully something like Liquibase or Flyway, but maybe the command line SQL tool of your database.
When a SQL statement gets executed the database will determine (i.e. guess) if the index is helpful for that statement and use it if it deemed helpful. No change of the SQL is necessary.
The basic idea of that estimate is:

*

*the columns of the index need to be part of the filter criteria used in the table. For an exception for this rule read up on "index skip scan".

*the query needs to return only a small part of the table. Because a full table scan is in most cases faster than accessing 90% of all rows via index access.

Things get more complicated once you get into joins with the many different ways a join can get executed by the database and how these get affected by the presence of an index.


text:
Q: Granting access to google drive after signing up the user I recently visited a website which gave me a google drive link to access the content but when I tried to open the link it said permission denied. So I signed up at that website and now the drive link opened fine.
So what I observed is the website shared the drive content with users who had signed up.
So I am curious How do you implement this ? i.e How do you provide read access to
only those users that signed up at your website?

A: When you are the owner of a shared drive, you can easily manage the members of it - either adding and/or removing them and changing the permissions for each of them.
This can be done using the UI of Google Drive:

But it can also be done programmatically as well by making use of the Drive API and of the following request:
POST https://www.googleapis.com/drive/v3/files/fileId/permissions

Code snippet
var newMember = {
  type: 'user',
  role: 'reader',
  emailAddress: 'user@example.com'
};

driveService.permissions.create({
         resource: newOrganizerPermission,
         fileId: 'driveId',
         useDomainAdminAccess: true,
         supportsAllDrives: true,
         fields: 'id'
         }, callback);

So for example, whenever a new member is being registered, a script with the instructions above is run and the email address is added to the viewers of the shared drive.
Reference

*

*Drive API Permissions:create;

*Manage shared drive users and activity.


text:
Q: How to remove subdomain with express I have a website built on Node/Express4 with two subdomains, www.awesome.com and api.awesome.com.
This is working fine.
I also have a staging site, running a separate Node instance, running at staging.awesome.com. What I'd like to achieve is have foo.staging.awesome.com route to foo.awesome.com early in the request lifecycle, so my staging site distinguishes between www. and api. in exactly the same way as my production site.
I've tried adding the following early in my app.js:
app.use('/', function(req, res, next) {
  var hostname = req.hostname;
  var newHostname = hostname.replace(/staging\./g, "");
  req.hostname = newHostname;

  console.log(newHostname);
  console.log(req.hostname);

  next();
});

newHostname is set exactly how I want, but it seems I can't just set the hostname on the request like that. The log shows req.hostname hasn't been changed.
So, my question is. Either how to I overwrite the hostname in the request, or how do I conditionally remove the last subdomain. Either works :)


text:
Q: Cron expression to run azure function every day at 1 am I'm working on azure function time trigger using visual studio. I have set cron expression "TimerTrigger("0 1 * * *")" to run my azure function every day at 1 am. after running the function locally it is showing correct 'next 5 occurrences'

but after deploying the azure function on azure portal is showing 'invalid cron expression'

what can be the issue?

A: You're missing a "0", the correct one should be "0 0 1 * * * ".
A CRON expression includes six fields:
{second} {minute} {hour} {day} {month} {day-of-week}


text:
Q: how do I interpret the sentence structure
During my first months on the job, Salinger remained a comfortably abstract concept. Then, in June, he called, anxious to speak to Phyllis Westberg, the company's president. My stomach lurched a little when I realized that it was Salinger, for real, on the other end of the phone.

As to the bold sentence above, I first interpreted it by regarding " anxious to speak to Phyllis Westberg" as a parenthesis elaborating on the emotional state of "he," and the main sentence is " he called the company's president."
But then I feel as if "the company's president" is an appositive of "Phyllis Westberg." While still " anxious to speak to Phyllis Westberg" is a parenthesis, the main sentence becomes " he called."

A:
Then, in June, he called, [anxious to speak to Phyllis Westberg, the
company's president].

You are right that "the company's president" is a supplementary appositive.
The bracketed expression is an adjective phrase functioning as a predicative adjunct -- it is, more specifically, a supplement, detached by intonation or punctuation from the rest of the clause. It is nevertheless still predicative, in that it is related to a predicand, i.e. the referent of "he".
The meaning becomes clear if you compare it with the equivalent predicative complement in:
He was [anxious to speak to Phyllis Westberg, the company's president].


text:
Q: Differences between DartEditor and Dart plugin for Eclipse I developed a dart/polymer project with the DartEditor. Because the DartEditor has no support for Git I moved to Eclipse and installed the Dart plugin. Now suddenly I get new errors, I didn't get in the Dart Editor and I wonder what the difference could be.
The Dart-SDK and Dartium versions are exactly the same. I copied the corresponding folders from the DartEditor to the Eclipse folder.
The version of the Eclipse plugin is 1.6.0.dev_01_02, of the Dart Editor 1.6.0.dev_01_02, of the Dart-SDK 1.6.0-dev.1.2.
The error messages I get are:
Loading polymer transformers...
Serving mastermind web on http://localhost:8080
[Warning from polymer (Linter) on mastermind|web/mm-color-button.html]:
line 2, column 1 of web/mm-color-button.html: Missing definition for <polymer-element>, please add the following HTML import at the top of this file: <link rel="import" href="packages/polymer/polymer.html">.
[Warning from polymer (Linter) on mastermind|web/mm-game.html]:
line 2, column 1 of web/mm-game.html: Missing definition for <polymer-element>, please add the following HTML import at the top of this file: <link rel="import" href="packages/polymer/polymer.html">.
[Error from polymer (Linter) on mastermind|web/mm-game.html]:
line 3, column 1 of web/mm-game.html: Polymer.dart's implementation of HTML imports are not supported within polymer element definitions, yet. Please move the import out of this <polymer-element>.
Build error:
Transform ImportInliner on mastermind|web/mastermind.html threw error: Could not find asset mastermind|web/mm-game.html.

build failed with errors: {Transform polymer (Linter) on mastermind|web/mm-color-button-line.html threw error: Polymer.dart's implementation of HTML imports are not supported within polymer element definitions, yet. Please move the import out of this <polymer-element>., Transform polymer (Linter) on mastermind|web/mm-line.html threw error: Polymer.dart's implementation of HTML imports are not supported within polymer element definitions, yet. Please move the import out of this <polymer-element>., Transform polymer (Linter) on mastermind|web/mm-line.html threw error: Polymer.dart's implementation of HTML imports are not supported within polymer element definitions, yet. Please move the import out of this <polymer-element>., Transform polymer (Linter) on mastermind|web/mm-game.html threw error: Polymer.dart's implementation of HTML imports are not supported within polymer element definitions, yet. Please move the import out of this <polymer-element>.}

Probably it's because of the different Polymer versions. In the DartEditor I have 0.9.5+2 and in Eclipse 0.11.0+5. I thought that pub get would update the packages automatically to the newest version if the dependency is to any.
What did change in polymer? Why are this now errors?

A: These are normal messages, I don't think they are caused by the Eclipse plugin.
Can you please check, that you have the polymer.html import at the top of each Polymer element definition file
<link rel="import" href="packages/polymer/polymer.html">

<!-- other element imports -->

<polymer-element name='some-name>
  <!-- no elements imports in here or below -->
  <template>
    <!-- style imports are allowed here -->
  </template>
  <script ...>
</polymer-element>

A: This was not a difference between the eclipse plugin and the dart editor, but between the different versions of the polymer package. There were many changes in between the two versions and I had to adapt the code accordingly.


text:
Q: file sql.gz give error 1064 when import in phpmyadmin I tried to import a .sql.gz file that I exported before another server in phpmyadmin in this new phpmyadmin, the phpmyadmin version is the same, the sql is being imported the same way it was exported (GZIP), but the 1064 error and does not conclude
I was opening the .gz file in the text editor, it includes the delimiter - additional to see if it goes, but the result is the same
In the text editor, the .gzip file is not completely visible to the SQL text, after the thousand line is compressed, small sample text

q@WG°LSÔµ
  Ä]0Scˆc»†8¼ëaˆ#üp¢–GwuyqdW—ïX¤^ù¡†Çumqd×…±Ä±]mXcˆãº†8¦ëaˆã93†£É`óóe'e/œ8º·àHÙ\
  OìÛx¶2jò6o'ŸgÛü¼Œ£ÕñEšÍ±ëU¦>Ç…ò‡ †æ!

I need to import this database in phpmyadmin and I can not, I exported another one to see if I could import, no, does phpmyadmin have any configuration that prevents importing the gzip file itself?

A: extract and load sql:
gzip -d filename
or edit the phpmyadmin code to fix this permanently as shown here.

A: Use datatype BLOB or MEDIUMBLOB, not TEXT.
Or, as already pointed out, gunzip first.


text:
Q: Formula for Cohort Fertility Rate I understand the definition of Cohort Fertility Rate as the average number of live births that a woman born in a particular year has had by the end of her reproductive life. But is there a formula to calculate it? I tried googling but in vain. I have seen formula for many other fertility indicators like CBR, IMR etc. All of them have some formula for direct computation but I couldn't find any such idea for CFR. If there isn't any formula then please direct me to the mechanism of its calculation.

A: I'm not a demographer, but here's my stab at what it would be:

*

*Let $d_{a,t}$ be the mortality rate for women age $a$ in year $t$.

*Let $x_{a,b}$ be the fraction of women age $a$ that were born in year $b$ and still alive.

*Let $f_{a,t}$ be the fertility rate for women age $a$ in year $t$.
One hundred percent of women born are alive, hence: $x_{0,b} = 1$. Then we have:
$$ x_{a+1,b} = (1 - d_{a,a+b}) x_{a,b}$$
Let $l_{a,b}$ be live births for women age $a$ and born in year $b$. You might want to think about this more, but somewhere to start might be:

$$ l_{a,b} = f_{a,a+b} x_{a+1,b} \quad \text{<--- assumes all women that die don't give birth... probably not right}$$
Then lifetime cohort fertility would be:
$$c_b = \sum_a l_{a,b}$$


text:
Q: PYCURL get a json file with utf-8 encoding problems i'm facing a problem with my PYCURL request.
My json file on the server is encoded in utf-8 and look like this :
{
  "address" : "123 rue de Labège"
}

I use PYCURL to get this json and copy it into a new file on my computer.
I use Python 2.7 and here is my setup for PYCURL :
def setup(self, _url, _method, _login, _passwd, _path, *args, **kwargs):
    self.curl = pycurl.Curl()
    self.url = 'https://%s:%d/' % (self.ip, self.port) + _url
    self.method = _method
    self.userpwd = '%s:%s' % (_login, _passwd)
    self.path = _path

    self.curl.setopt(pycurl.URL, self.url)

    curl_method = {
        "GET": pycurl.HTTPGET,
        "POST": pycurl.POST
    }

    if self.method in curl_method:
        self.curl.setopt(curl_method[self.method], 1)
    else:
        self.curl.setopt(pycurl.CUSTOMREQUEST, self.method)

    self.curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    self.curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    self.curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
    self.curl.setopt(pycurl.USERPWD, self.userpwd)

    if _url == 'MY_FILE_JSON':
        filename = 'file.json'
        self.file = open(self.path + filename, 'wb')
        self.curl.setopt(pycurl.WRITEDATA, self.file)

The problem is in the file i'm getting :
{
  "address" : "123 rue de Lab\u00e8uge"
}

I don't understand why PYCURL encoding my "è" into \u00e8.
Is there any option with setopt with PYCURL to force it to print the good character ?

A: Actually this is totally correct, once you do a print of the variable property, you can see it prints out fine.
This is just how Python internally handles Unicode strings. Once PycURL receives the file it will be converted to whatever type is appropriate for the property. In your case this is a Unicode string.
Check this article out for more information.
So to recap, if you do:
>>> test = u'123 rue de Lab\u00e8uge'
>>> print(test)
123 rue de Labèuge

Here you can see I create a Unicode string (starting with the u).


text:
Q: Ruby and Rmagick. How to add ImageList to ImageList? Creating list of the lists I am using Rmagick and Ruby 2.1.0
I have the following code:
@ilg = Magick::ImageList.new
@il = Magick::ImageList.new

# in the loop
_______________
pic = Magick::Image.read("#{@dir}/#{e}").first
@il.push(pic)
_______________

@ilg.push(@il.append(false))
@ilg.write("#{@dir}/results/result#{@counter}.jpg")

I would like to replace 'pic' variable with Another ImageList.
I need something like this instead of @il.push(pic):
@il.push(@another_list.append(true))

How can I do it?

A: Like Малъ Скрылевъ said, ImageList is based on Enumerable.
That means that you can just use @il += @list_being_added.


text:
Q: Materialize CSS Equal Column/Card Height: Responsive card-content height I'm using Angular and Materialize CSS for it's responsive grid system, and while that works great, i'm having issues with cards with unequal heights within a row.
I believe rows will always have the same height with the Materialize grid system, but card height will adjust to fit content.
I have two cards within a row, each having their own separate column, and I would like for their heights to remain the same. The row's height will be defined by the largest card (I think).
I could set both cards to have a height of 100% (I think), so that the shorter card would increase in height to match the taller card, but there is a problem:
The shorter card is divided into three sections: a photo, a card-content section with words, and a card-action section that has a link and is separated by an underline. By increasing the cards height through CSS i'm increasing the card-height by increasing the card-action section's height, which looks awful. I would like the card-content section to grow to match the taller card's height.
I'm thinking I can accomplish this through javascript/typescript (i'm using angular), by increasing the css height of the shorter card's card-content section  by the difference of the two card's height.
The problem is, that I'm not sure when I should be calling the function to make this change. An adjustment needs to be made upon loading up the webpage, but also, whenever the browser is resized.
I tried using the Angular onInit life cycle hook to check the stylings of the two card elements, but I believe no styling takes place until after the onInit hook.
How can I call a function to readjust the card heights immediately after Materialize does it's work?
Am I overthinking this?


text:
Q: How to set different colors for shape's stroke (top/right/bottom/left)? Now I set one color for stroke, so it is used for 4 sides.
I'm trying to set different colors for each side of stroke.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#FFF" />

    <stroke
        android:width="1dp"
        android:color="#C7C7C7" />

</shape>

Here is how it can be achieved in css.
border-color:red green blue pink;
/*top border is red
right border is green
bottom border is blue
left border is pink*/

How to do the same in Android?

A: I think you can use layer list  for Implementing it
http://developer.android.com/guide/topics/resources/drawable-resource.html#LayerList


text:
Q: How to apply event.stopPropagation? Let me explain the problem first. I am using the following UL structure:

Navigation Item with long text do text wrap

Sub nav item

Sub nav item

Sub nav item

JS Function
function smenu_over(obj) {
  var a = obj.parentNode.childNodes[0];
  if(a!=null) {
   var top = $(".topnav_icons").length && !$(".logo_t").length ? "-45px" : "-34px";
   setBckPosition(a, top);
   a.style.color = "#fff";
  }
 }

I need to apply the event.stopPropagation inside this function which is called when mouseover event happen.
Please help me the code to apply event.stopPropagation?

A: You mean this:
$('ul.sub-menu a').mouseenter(function(event){
   event.stopPropagation();

   // your code....
});

A: You can remove your current handlers from being in-line, like this:

Then you can bind these functions in jQuery, like this:
$(function() { //run when DOM is ready
  $("ul.sub-menu").hover(smenu_over, smenu_out);
});

In your functions, instead of obj just use this, it'll refer to the element you're hovering, like this:
function smenu_over() {
  var a = this.parentNode.childNodes[0];
  if(a!=null) {
    var top = $(".topnav_icons").length && !$(".logo_t").length ? "-45px" : "-34px";
    setBckPosition(a, top);
    a.style.color = "#fff";
  }
}

The important difference here is .hover() maps to the mouseenter and mouseleave events (not mouseover/mouseout), which don't fire on the parent when entering/leaving a child, so no need to stop propagation, they already behave like you want.
You can probably optimize this much further, but without seeing your other code I don't want to give you any bad advice, this will fix the current issue though.


text:
Q: How to get the error message during a jquery post while using aps.net mvc? I'm using 2019 ASP.NET MVC with jquery 3.4.1. I'm trying to get the error message when I make a jquery ajax post. To simulate an error I mispelled the method in the controller being called by ajax. The best I could do was to display an alert box with some HTML code. It looks like the title tag contains the correct error message: "The resource cannot be found." But it's nested inside of a bunch of html code.
Is there a way to get that error message out of that html code and into a string?
Edit: I figured it out. I just added a span tag and set the html property of it.
Controller
using System.Web.Mvc;

namespace Test
{
    public class HomeController : Controller
    {

        [HttpGet]
        public ActionResult Index()
        {

            //view
            return View();

        }

        [HttpPost]
        public ActionResult DoSomething1111111111()
        {
            return Json("hello");

        }

    }

}

View
@{
    Layout = null;
}

<input type="button" id="test-button" value="test" />


text:
Q: PHP validation - input type"text" value must be one specific word I am very sorry if this seems like a "Sigh, another one of those~" questions, but I've looked far and wide, yet none of the things seemed to suit my needs. I've looked at games like hangman, but they did it letter for letter and I couldn't figure out what to do with the code. (incompetence on my side, I admit. My knowledge is quite limited)
I then decided to look at quizzes, but they seemed to only deal with radio buttons. I've tried to edit scripts so that they had input type text boxes, but that seemed to lead to a lot more problems, seeing as I turned the question from multiple choice to open answer.
All I really want, is a basic setup like this:
Question
Input box
Button (submit, I think?)
Nothing fancy aesthetically-wise, just those three things.
Summary: How do I get my code to check if the answer they've given to the question is, for example, banana? And how do I get the button to -only- work if the word is indeed banana?
I'm very lost after several days of searching now. Many thanks for any effort you guys put into this, it'd mean a lot to me.

A: basically you would change the submit button to a normal button, and run a javascript function to check if the value is correct before submitting the form. Something like:

<form id='myForm' method='POST' action='process.php'>
    <input type='text' id='check_value' />
    <input type='button' value='Submit' onclick='validate();' />
</form>

Hope that helps.

A: This is some basic client-side scripting using javascript.
Using the onkeyup event, we can test the value of what the user is typing in the text box, compare it to the "correct" value and enable/disable our submit button based on that evaluation.

How do you spell "banana"?

<form action="" method="post">
    <input type="text" name="answer" id="answer" />

    <input type="submit" id="submit" disabled="true" />
</form>

As others have pointed out, you'll want to verify the input on the server-side, just in case the user is a jerk and has disabled javascript.
<?php

    if ($_POST['answer'] == "banana") {
        // we're OK, do something
    } else {
        // return to the form and let the user know he's a cheater!
    }


text:
Q: Probability of $1 bill Suppose you have a wallet that contains either a 1 bill or a 10 bill (with equal probability). You add a 1 bill. Later you reach into your wallet and randomly remove a bill. It's a 1 bill. What's the probability that the bill remaining in the wallet is a 1 bill?
This is all I have so far:
A= event that $1 bill is chosen
B= event that $10 bill is chosen
P(A) = $\frac{2}{3}$
P(B)= $\frac{1}{3}$

A: Well, you have two possible configurations before the draw.  Enumerate those possibilities with the possible draws from each:

*

*1 & 1

*

*draw first 1

*draw second 1

*1 & 10

*

*draw 1

*draw 10

Consider the draws here where you took out a 1... you can count how many second draws will result in a 1 versus a 10.
Related: check out the famous Monty Hall problem


text:
Q: What happens when we issue read command from disk? Suppose there is a process which issues a read command for particular sectors to kernel.

*

*Now kernel issues this read command to disk and that process which requested those particular sectors sleeps ( get blocked ) and is it in the waiting queue.

*Now kernel issues this command to disk ( This is my understanding ) Read these sectors and after reading those sectors into your buffer , copy those bytes/data into this location ( and issues this command to DMA Controller )

*Now disk controller after reading those bytes/data into the buffer, with the help of DMA ( it asks DMA controller ) transfer those data to the memory region specified by the kernel.

*Now in the meanwhile ( the bus was busy ), so CPU was busy doing some calculations which does not needs the bus ( doubt ).
Now after data transfer from the disk is complete , disk issues a interrupt to the CPU.

*CPU acknowledges the interrupt and invokes the interrupt service routine and this ISR is responsible for waking the concerned Process which had been submitted into the queue.

*Now as i have read through some of the answers on stackoverflow , i comes to my knowledge that ISR knows which process to wake up exactly , which is confusing to me as at this moment , we dont know which process we need to wake up and even we don't know which request just got served via disk I/O.

My questions are :

*

*How does processor/ISR finds out which process to wake up

*When does the DMA controller comes into action ( is it processor asks DMA controller to take the action for transferring bytes from disk to memory or is it disk controller which is responsible for asking DMA controller for its service )

*How does DMA fields such as source address register and destination address registers gets filled ???


text:
Q: Getting Stock quotes from Yahoo Finance - Yahoo kicks me out, how can I avoid this? I grabbing stock quotes from the YAHOO finance API using CSV concept in Python. My problem is that yahoo is shutdown the connection at some stage. Sometimes after 100 polls, sometimes after 10000 polls. So I tried different thinks like waiting 1 hour between 1000 polls, try different concepts like :
                try:
                    name        = fetch.get_name(symbol + ex_code)
                    exchange    = fetch.get_stock_exchange(symbol + ex_code)

                except :
                    print 'going to sleep'
                    t.spleep(3600)
                    name        = fetch.get_name(symbol + ex_code)
                    exchange    = fetch.get_stock_exchange(symbol + ex_code)
                    print'Yahoo Fehler --- reconnect'

BUt I am not able to poll 3000 quotes from yahoo stable, yahoo kicks me out.
Any advice what works ?
regards
Adrian


text:
Q: Can I call a Lambda Expression with multiple params for a Html Helper? Can I create a Code line like this one in MVC 3
<%=Html.CustomHtmlTag(r => r.Add("One"), r.Add("Two")...).Render()%>

I try to find and example but all the code was for (r => r.Add("One"))
Thanks a lot for any help.

A: You can write complete functions with lambdas by simply putting braces.
r =>
{
    r.Add("One");
    r.Add("Two");
}

A: The answer provided by @VoidStar is correct if you get suck here is a more detailed example.
MVC Code
@Html.CustomHtmlTag(Model, x => {
                                    Model.Add("One");
                                    Model.Add("Two");
                                    Model.Add("Three");
                                    Model.Add("Four");
                                }).Render()

Model
public class MyModel
{
    private readonly IList<string> _values = new List<string>();

    public void Add(string value)
    {
        _values.Add(value);
    }

    public string ValuesToString()
    {
        return string.Join(",", _values);
    }
}

HTML helper
public static class MyMvcHelpers
{
    public static IMyClass CustomHtmlTag(this HtmlHelper helper, MyModel viewModel, Action<MyModel> action)
    {
        action.Invoke(viewModel);

        var expressionResult = viewModel.ValuesToString();

        return new MyClass(expressionResult);
    }
}

Render class
public interface IMyClass
{
    MvcHtmlString Render();
}

public class MyClass : IMyClass
{
    private readonly string _value;

    public MyClass(string value)
    {
        _value = value;
    }

    public MvcHtmlString Render()
    {
        return new MvcHtmlString(string.Concat("
", _value, "
"));
    }
}

Result

One,Two,Thee,Four


text:
Q: HTML Element not working properly after dynamic insertion I´m creating a new append html element but it lose the functionality to use on key up.  Is there anyway to fix that (I can use ES6 but including more frameworks on this project could be hard since it´s legacy code. I´m with JQuery and JQuery UI)
I tried to read a lot about it but is seems that when you create a HTML element with append the functionality is lost.
            } else if (opcaoSelecionada === 'cidade'){
                    var microtime = Date.now();
                    $('#add_destino').prepend   (`

                        Type a country name
                        <input type="text" name="country" id="country" placeholder="Enter country name" class="form-control">

                    `);
                }
            }

            $('#country').on('keyup',function() {
                console.log('Teste');
                var query = $(this).val();
                console.log(query)
                $.ajax({
                    url:"http://localhost/autocomplete/cidadeTourCode",
                    type:"GET",
                    data:{'cidade':query},
                    success:function (data) {
                    $('#country_list').html(data);
                    }
                })
            });

            $(document).on('click', 'li', function(){
                var value = $(this).text();
                $('#country').val(value);
                $('#country_list').html("");
            });
´´´


text:
Q: return static_cast C++ and C I would like to know about C and C++ language.
C++ uses:
return static_cast<int>

How can I transform return static_cast<int>to C?
For example:

*

*C printf()

*C++ cout

A: C style casting is simply prefixing the value with the type in parentheses. Instead of
static_cast<type>(value)

you simply do
(type)value

e.g.
static_cast<int>(x)

becomes
(int)x

Or you could do
#ifdef __cplusplus
    #define STATIC_CAST(Type_, Value_) static_cast<Type_>(Value_)
#else
    #define STATIC_CAST(Type_, Value_) (Type_)(Value_)
#endif

and use one invocation for both languages
STATIC_CAST(int, x) // C++ static_cast<int>(x), C (int)(x)

The extra parentheses in the C version around the Value_ aren't required for simple cases but are there because this is a macro and if you said
STATIC_CAST(int, 1.0 + 2.0)

you don't want it to expand to
(int)1.0 + 2.0

but want it to expand to
(int)(1.0 + 2.0)

Note that C++ allows the C form of casting but the templated cast mechanism is preferred by C++ engineers.


text:
Q: How to install dlib and update gcc on Yocto I'm trying to install dlib on Yocto following the instructions on this page. However the installation fails at the last command, with the message "error: 'exception-ptr' in namespace 'std' does not name a type".
I suspect this is because of C++11 not being properly supported by the gcc version 4.8.2 installed on my machine, based on the very few reports of this happening.
However trying to update gcc to a higher version like 4.9.2 or 5.4.0 also failed because apparently gcc isn't directly compatible with Yocto. Attempting to run make resulted in failure complaining about unknown OS. Therefore I may also need to know how I can update the gcc installed on my Yocto machine as well.
If anyone knows of a good workaround I'd be very glad to know it.

A: It is not because of gcc version. In yocto you have to specify mcpu flag along with your cxx flags if you are compiling a program with c++11 features.
If you are compiling dlib with python bindings you have to set cxx flags(-mcpu=cortex-a15) in the CMakeList.txt.
I have created a recipe for dlib-19.7 on yocto-1.6 with some patches for boost and if you want i can help you with cross compilation


text:
Q: Healpy query_polygon returns incorrect area I'm using healpy.query_polygon to find the pixel indices corresponding to a rectangular FOV. However, the indices which are returned do not match my input- creating a polygon in healpy space which is ~100x larger than the FOV (or returns ~14000 pixels instead of the expected ~30 pixels).
The query_disc function works as I expect, however, this is not the function I'm looking to use.
The corresponding outputs:
Top(disc), bottom (polygon)
For hp.query_disc:
disc_center = astropy.coordinates.spherical_to_cartesian(1, np.deg2rad(47.3901), np.deg2rad(319.6428))
#(<Quantity 0.5158909828269898>, <Quantity -0.4383926760027675>, <Quantity 0.7359812195055898>)
radius = 0.06208
qd = hp.query_disc(128,disc_center,radius)
#plotting
for ind in range(len(prob)):
        if ind in qd:
            prob[ind] = 1
        else:
            prob[ind] = 0

For hp.query_polygon:
ra_poly, dec_poly = (array([ 48.51458308,  48.51458308,  46.20781856,  46.20781856]), array([ 317.00403838,  322.28167591,  317.11703852,  322.16867577]))
xyzpoly = astropy.coordinates.spherical_to_cartesian(1, np.deg2rad(dec_poly), np.deg2rad(ra_poly))
#xyzpoly = array([[ 0.48450204,  0.52400015,  0.50709248,  0.5465906 ],
   [-0.45174162, -0.40526109, -0.47093848, -0.42445795],
   [ 0.74912435,  0.74912435,  0.72185467,  0.72185467]])

qp = hp.query_polygon(128,xyzpoly)
#plotting
for ind in range(len(prob)):
        if ind in qp:
            prob[ind] = 1
        else:
            prob[ind] = 0

Can anyone explain this discrepancy? By all accounts I don't see any errors, unless the vertices are being implemented incorrectly into the function.

A: Your problem is easily solved by considering what query_polygon accepts as input: it wants an (N, 3) array of coordinates, not an (3, N). The value you're passing it is a 3-tuple of 4 elements each, which is transformed into an array of shape (3, 4). Not sure what query_polygon does with the fourth component (possibly ignoring it), but otherwise it will match a triangle (on the sphere).
The solution is straightforward: transpose the coordinate array first.
>>> qp = hp.query_polygon(128, array(xyzpoly).T)
>>> len(qp)
36

There are two problems with your example code:

*

*swap RA and dec. spherical_to_cartesian will complain

*swap the last two values for the RA. Healpy will crash Python(!) with the message that your polygon is not convex (connect the dots and you'll see).
An additional problem is that your polygon doesn't define what is inside, and what is outside. It looks like healpy does the "right" thing, and assumes the smallest area is "inside". Defining the polygon the "other way around" (reverse the spherical coordinates) yields the same result.


text:
Q: cannot set right charset when uploading files Please be patient and check this problem.
I wrote some simple PHP code for uploading images.
Here is the code (snippets)
 <?php

 header('Content-Type: text/plain; charset=utf-8');

//set encoding for prepared statements
$dbh->exec("SET NAMES UTF8");
$dbh->query('SET NAMES UTF8');

//check if file is actually an image etc.

//send image to "upload" folder
     move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);

//save to the database a string like "upload/myImage.jpg", so I can render it on the site later
$stu = $dbh->prepare("UPDATE multi SET m_place=:name WHERE m_id = :id");
$stu->bindParam(':name', $n, PDO::PARAM_STR);
$n= "upload/".$_FILES["file"]["name"];
$stu->execute();

If the name of the image is in English, everything is fine. If is in Greek, it saved ok in the database , but not in the folder. In the database I see χωρις τιτλο.jpg (which is right) and in the folder χωΟΞ―Ο' τίτλο.jpg which is wrong.
I've tried everything and cannot fix this. To get the right titles in the folder.
The encoding of the database (postgreSQL 9.1) is UTF8, the Collation and the Character Type are Greek_Greece.1235. The collaction in table's column which I save the image's title is pg_catalog."C".
I use DreamWeaver. The file that handles the uploads is a php file. Encoding is utf8, Unicode Normalization Form is C and the Include Unicode Signature (BOM) is unchecked.
The default language is Greek in Region and Language in the control panel. (Windows 7 Home Premium)
The encoding of the browser is utf8
I also use Apache 2.2.22. Is it Apache's fault? Or its the php file? Or the database?
I dont know what else to do...What am I missing? Please please please advice

A: This seems to be a StackOverflow issue and not related to ServerFault. However, you should take a look at this post:
For naming files in UTF-8:
Can a PHP file name (or a dir in its full path) have UTF-8 characters?
For writing files in UTF-8:
How to write file in UTF-8 format?

A: Turns out , I had not tried everything.
Thanks to this I found the solution.
It has to do with PHP and how "PHP filesystem functions can only handle characters that are in system codepage"
So I used the iconv function.
I changed the code like so
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . iconv('UTF-8', 'Windows-1253',$_FILES["file"]["name"]));

A: For the application using japanese, the code page is cp932
This can be comfirm by using chcp command in commandline.

Sample Code
$fullPath = $uploadFolderPath."\\".iconv("utf-8", "cp932", $fileName);
move_uploaded_file($this->request->data["file_name"]['tmp_name'], $fullPath);


text:
Q: Twin Primes of the form $3k-1, 3k+1$ I wanted to discuss something.
Yesterday I thought about the twin prime conjecture and I constructed numbers of the form
$$
3k-1, 3k, 3k+1
$$
Then I proved with the help of quadratic reciprocity, that there are inifinitely many prime numbers of the form $3k+1$. I plugged in some even numbers for $k$ and I thought, that if $3k+1$ is prime, then $3k-1$ has to be prime, hasn't it? - No, because $3\cdot 12+1=37,$ which is prime but $35=5\cdot 7$ surely isn't. I was disappointed but nevertheless I figured that there are quite a lot of prime pairs $3k-1,3k+1$. Is there a way to prove or contradict this? If so, we would have infinitely many twin primes, wouldn't we? Maybe we have to find more conditions so that this pair of numbers is really prime.


text:
Q: how to bind model value to selected item text from dropdownlist mvc4 In my application, I have two dropdownlists. First to display country values and second to display the states of selected countries. The values are generated and displayed in both dropdownlists. But on post, both dropdownlist return the id of the model values and not the name or value. How to bind the selected item text of dropdownlist on post ?
Model :
public string State { get; set; }
public string Country { get; set; }
public SelectList CountryList { get; set; }
public SelectList RegionList { get; set; }
public class Countries
{
   public string ID { get; set; }
   public string Name { get; set; }
}
public class Region
{
   public string ID { get; set; }
   public string Name { get; set; }
}

View
@Html.DropDownListFor(model =>model.State, new SelectList(Model.RegionList, "Value", "Text", Model.RegionList.SelectedValue))
@Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue), new { data_url = Url.Action("GetRegionDetail", "WPindex") })

<script type="text/javascript">
            $(document).ready(function () {
                $("#Country").change(function () {
                    $("#State").empty();
            var url =$(this).data(url);
            var Id = $('#Country option:selected').attr('value');
                    $.getJSON(url, { ID: Id },
                        function (data) {
                            jQuery.each(data, function (key, Region) {
                                $("#State").append($("<option></option>").val(Region.ID).html(Region.Name));
                            }
                            );
                        });
                });
        });
</script>

Controller :
 public JsonResult GetRegionDetail(int ID)
    {
        AddressModel amodel = new AddressModel();
        List<Model.Region> objRegion = new List<Model.Region>();
        objRegion = GetRegionList(ID);
        SelectList objlistofRegiontobind = new SelectList(objRegion, "ID", "Name", 0);
        amodel.RegionList = objlistofRegiontobind;
        return Json(objRegion, JsonRequestBehavior.AllowGet);
    }
[HttpPost]
public ActionResult UpdateDetails(Model objmodel)
{
    string state   = objmodel.State; // returns ID and not Name (selected text)
    string country = objmodel.Country; // returns ID and not Name
}

A: When you define a dropdown list in Html, each option has an attribute for value and text the text value is shown to the user and the value is the "selected value" of that dropdown. When the form is posted to the controller, only the value is posted. If you wish to have the name instead of the Id to post, simply set the value attribute of the dropdown list items to the name of the source data.
For example, when you populate your state dropdown you could do it like this:
$("#State").append($("<option></option>").val(Region.Name).html(Region.Name));

A: That's not a problem. You want the DropDownList to give you the selected Value which in this case is the ID, not the Text. So, I would recommend that you change the properties of your ViewModel with the following:
public int StateID { get; set; }
public int CountryID { get; set; }
public SelectList CountryList { get; set; }
public SelectList RegionList { get; set; }

However, if you don't want the IDs, you can define your DropDownLists like this:
@Html.DropDownListFor(model => model.State, new SelectList(Model.RegionList, Model.State))
@Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, Model.Country), new { data_url = Url.Action("GetRegionDetail", "WPindex") })


text:
Q: Any other reputation bonus, except association? In our reputation audit page, there is such line near the end:

** rep from bonuses: ___

Does the use of plural word mean there are other bonuses except association, maybe secret?
Has anyone ever saw a number other 0 or 100 in there?

A: Yes, testers and contributors to the first version of the API received badges that also had bonuses.  This is exclusive to stackapps.com.  For example, see the 2k bonus here.
The badges involved were the API Beta and API Evangelist.  These were awarded manually.
And yes, I agree, the "rep change" description in the reputation tab sucks.  It sucks because it's really old, hasn't been used since, and we have no plans to use it again.


text:
Q: Add Azure Availability Set to Load Balancer (backend pool) to with Terraform Hope someone can help me. I created a cluster of multiple VMs inside an Availability Set and a Load Balancer.
With Terraform I can say to add the single NICs to the BackendPool:
resource "azurerm_network_interface_backend_address_pool_association" "backendPool" {
  count                   = "${var.nb_instances}"
  network_interface_id    = "${element(azurerm_network_interface.nic.*.id, count.index + 1)}"
  ip_configuration_name   = "ipconfig01"
  backend_address_pool_id = "${var.backendPoolID}"
}

Instead of adding each VM separate, I want to say the LB to add the whole AV-Set, which works fine with the Azure GUI, but I can not find any solution to do it inside Terraform.
I tried to add this resource to my AV-Set module and replaced the "network_interface_id" with the AV-Set ID, but it didn´t work.
Is there such a solution?

A: As you say you can add the availability set to the load balancer in Azure GUI, actually, Azure also associate the Nics of the VMs in the availability set to the load balancer backend pool. It's the same as it provides in Terraform. The difference is that Azure GUI does all the things behind for you. But you do all the things yourself in Terraform. So there are no other solutions to add the VMs to the load balancer backend pool in Terraform.


text:
Q: Teradata - Create two rows from one I need to create two rows with different keys from one using SQL.  I have been unable to accomplish this.
I have one ELEMENT which needs to be separated into two.

*

*GAAP: Should only be populated with Special Handling when it is in
the company A, B, C, or D.

*Statutory: Should ALWAYS equal what is in the parent (Special Handling)

My current code does not work because of the case statement.  If it is in A,B,C,D then it is assigned correctly, but the second one does not.  It only picks up the other companies.
SELECT
  CASE
    WHEN (AB.DATA_ELEMENT_BUSINESS_NME = 'Special Handling'  AND AB.UNIT_COMPANY_NME IN ('A','B','C','D')) THEN 'GAAP Special Handling'
    WHEN AB.DATA_ELEMENT_BUSINESS_NME = 'Special Handling' THEN 'Statutory Special Handling'
    ELSE AB.DATA_ELEMENT_BUSINESS_NME
END AS DATA_ELEMENT_BUSINESS_NME,
sum(AB.DATA_ELEMENT_AMT) as DATA_ELEMENT_AMT
FROM

Any suggestions?
Update
Data IN: Special Handling   -3727286.720000
Data OUT: GAAP Special Handling -3727286.720000
Statutory Special Handling  -3727286.720000

A: For a single input record, you are expecting two output records. The basic idea you are missing here is that how much ever logic you put in there, a single query like this is going to give you a single output record for a single input record.
What you need is a union:
SELECT
  'GAAP Special Handling' AS DATA_ELEMENT_BUSINESS_NME,
  sum(AB.DATA_ELEMENT_AMT) as DATA_ELEMENT_AMT
FROM YOUR_TABLE
WHERE
  AB.DATA_ELEMENT_BUSINESS_NME = 'Special Handling'  AND
  AB.UNIT_COMPANY_NME IN ('A','B','C','D')

UNION ALL

SELECT
  CASE WHEN AB.DATA_ELEMENT_BUSINESS_NME = 'Special Handling'
      THEN 'Statutory Special Handling'
      ELSE AB.DATA_ELEMENT_BUSINESS_NME
  END AS DATA_ELEMENT_BUSINESS_NME,
  sum(AB.DATA_ELEMENT_AMT) as DATA_ELEMENT_AMT
FROM YOUR_TABLE


text:
Q: How to contact an api many times a minute? Hello I need to create an application that contacts the api shopify, stripe, facebook api and many others. I contact as many times the api as I have customer in my application to update information in my database. I integrate for each user these different api every 30 minutes. So if I have 100 users I will contact 100 times the shopify api... every 30 minutes.
My script is in python and I use request. I wanted to use a new proxy for each request because I make many requests. However even with a proxy I get a message from webshare that provides me with proxies "We have received potential abuse reports from our network partners with the following reason: brute-force attempts on payment gateways." So here is my question how I can contact many times api every second without being blocked for ddos. My current script in python
s = requests.session()
s.proxies['http'] = 'socks5h://' + proxy_information
s.proxies['https'] = 'socks5h://' + proxy_information
server_proxies = s.proxies
response = requests.get(url, auth=(token, ''), proxies=server_proxies, params=param_data)


text:
Q: Strange result of DeleteCases in an association Bug introduced in 10.1.0 and fixed in 10.3.1

The function DeleteCases can be used for associations, also with level specification. Here is an example where some values are associations:
asc = Association["a" -> Association[], "b" -> Association["c" -> Association[1 -> 1]]]

(* <|a -> <||>, b -> <|c -> <|1 -> 1|>|>|> *)

Deleting on level 1 works:
DeleteCases[asc, _Association]

(* <||> *)

Deleting on level 2 works as well:
DeleteCases[asc, _Association, {2}]

(* <|a -> <||>, b -> <||>|> *)

But deleting on both levels does not return what I would expect:
DeleteCases[asc, _Association, {1,2}]

(* <|a -> <||>|> *)

I cannot figure out why this happens. Is this a bug or intended behaviour?


text:
Q: how to pass attribute of type Set using postman? so i've been trying to implement a jwt authentication/authorization example , i am trying to register a new user using postman but the post procedure couldn't be completed because of attribute "role" that is declared as a "Set" , i tried putting the attribute role as null like this:
{
   "id": 1,
    "username": "jacksonBez",
    "email": "bezkoder@gmail.com",
    "role":"",
    "password": "123bezko"
}

and this warning has occured :

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Cannot coerce empty String ("") to element of
java.util.HashSet<java.lang.String> (but could if coercion was
enabled using CoercionConfig); nested exception is
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot
coerce empty String ("") to element of
java.util.HashSet<java.lang.String> (but could if coercion was
enabled using CoercionConfig) at [Source:
(org.springframework.util.StreamUtils$NonClosingInputStream); line: 5,
column: 13] (through reference chain:
com.test.jwt.payload.request.SignUpRequest["role"])]

i want to know how to use postman with a variable declared a list or a Set
here my controller's code :
package com.test.jwt.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.test.jwt.model.ERole;
import com.test.jwt.model.Role;
import com.test.jwt.model.User;
import com.test.jwt.payload.request.LoginRequest;
import com.test.jwt.payload.request.SignUpRequest;
import com.test.jwt.payload.response.JwtResponse;
import com.test.jwt.payload.response.MessageResponse;
import com.test.jwt.repository.RoleRepository;
import com.test.jwt.repository.UserRepository;
import com.test.jwt.security.jwt.JwtUtils;
import com.test.jwt.security.services.UserDetailsImpl;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserRepository userRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    PasswordEncoder encoder;

    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtils.generateJwtToken(authentication);

        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        List<String> roles = userDetails.getAuthorities().stream()
                .map(item -> item.getAuthority())
                .collect(Collectors.toList());

        return ResponseEntity.ok(new JwtResponse(jwt,
                                                 userDetails.getId(),
                                                 userDetails.getUsername(),
                                                 userDetails.getEmail(),
                                                 roles));
    }

    @PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) {
        if (userRepository.existsByUsername(signUpRequest.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Username is already taken!"));
        }

        if (userRepository.existsByEmail(signUpRequest.getEmail())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Email is already in use!"));
        }

        // Create new user's account
        User user = new User(signUpRequest.getUsername(),
                             signUpRequest.getEmail(),
                             encoder.encode(signUpRequest.getPassword()));

        Set<String> strRoles = signUpRequest.getRole();
        Set<Role> roles = new HashSet<>();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);
        } else {
            strRoles.forEach(role -> {
                switch (role) {
                case "admin":
                    Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(adminRole);

                    break;
                case "mod":
                    Role modRole = roleRepository.findByName(ERole.ROLE_AGENT)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(modRole);

                    break;
                default:
                    Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(userRole);
                }
            });
        }

        user.setRoles(roles);
        userRepository.save(user);

        return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    }
}

you can also find full project here : https://github.com/bezkoder/angular-10-spring-boot-jwt-authentication
thank you.

A: {
  "id": 1,
  "username": "jacksonBez",
  "email": "bezkoder@gmail.com",
  "role": {{roles}},
  "password": "123bezko"
}

You are missing brackets [].
"role": "" means single value
"role": [] means array/list/set of values
For postman to resole {{role}} you need to set it as global/collection or environment value for example ["admin", "mod"]
More about postman variables here
https://learning.postman.com/docs/sending-requests/variables/


text:
Q: avconv error: av_interleaved_write_frame I use avconv to cut a video and to remove subtitles.
Depending on the length of the output video, I get a success or and error.
The input video has the following information:
avconv -i video.mkv

Metadata:
Duration: 00:02:07.01, start: 0.000000, bitrate: 15559 kb/s
Stream #0.0(eng): Video: mpeg2video (Main), yuv420p, 720x576 [PAR 64:45 DAR 16:9], 15000 kb/s, 25 fps, 25 tbr, 1k tbn, 50 tbc (default)
Stream #0.1(fre): Audio: mp2, 48000 Hz, stereo, s16, 192 kb/s (default)
Stream #0.2(ger): Audio: mp2, 48000 Hz, stereo, s16, 112 kb/s (default)
Stream #0.3(eng): Audio: mp2, 48000 Hz, stereo, s16, 128 kb/s (default)
Stream #0.4(qaa): Audio: mp2, 48000 Hz, stereo, s16, 128 kb/s (default)
Stream #0.5(fre): Subtitle: [0][0][0][0] / 0x0000 (default)
Stream #0.6(fre): Subtitle: [0][0][0][0] / 0x0000 (default)
Stream #0.7(ger): Subtitle: [0][0][0][0] / 0x0000 (default)
Stream #0.8(ger): Subtitle: [0][0][0][0] / 0x0000 (default)

At least one output file must be specified

For a duration of 40s of video, this works properly:
avconv -i video.mkv -vcodec copy -acodec copy -ss 00:02:30 -t 00:00:40 -sn test3.mkv
For a duration of 2min30s, an error is raised:
avconv -i video.mkv -vcodec copy -acodec copy -ss 00:02:30 -t 00:10:40 -sn test3.mkv
Output:

Application provided invalid, non monotonically increasing dts to muxer in stream 0: 308600 >= 308600
             av_interleaved_write_frame(): Invalid argument

Has anyone an idea of the reason of this problem?


text:
Q: Express Cookie Session 'undefined' After I define a cookie in an express cookie session, I can log it to the console with ease. However, when I attempt to access this cookie in another route of my application, it returns 'undefined'.
Setting the cookie:
router.get('/callback', catchAsync(async (req, res) => {
  console.log("in /callback");
  if (!req.query.code) throw new Error('NoCodeProvided');
  const code = req.query.code;
  const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
  var response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
    {
      method: 'POST',
      headers: {
        Authorization: `Basic ${creds}`,
      },
    });
  var json = await response.json();

  req.session.token = json.access_token

  console.log(req.session.token)

>>> RETURNS THE TOKEN CORRECTLY <<<

Attempting to access the cookie in another route:
router.get('/loggedin', catchAsync(async (req, res) => {
  console.log("/loggedin");
  console.log("token: " + req.session.token);

>>> RETURNS 'token: undefined' <<<

A: In the first router.get('/callback'..) the catchAsync() function is not declared globally. It just handle this specific route, and doesn't really require a name.
You should wrap this function inside a middleware or create a function which is available globally, I don't know what is the goal but here is the 2 option.
Option 1 initiate the functionality as a middleware. The behaviour is depends on where you place it!!!! Maybe in that case doesn't fully makes sense, but you can play around, but I think you will get it.
// if you put before your router initiation it is going to have effect on all of the routes
app.use(async(req, res, next) => {
    if (!req.query.code) throw new Error('NoCodeProvided');
    const code = req.query.code;
    const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
    var response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
      {
        method: 'POST',
        headers: {
          Authorization: `Basic ${creds}`,
        },
      });
    var json = await response.json();

    req.session.token = json.access_token

    console.log(req.session.token)
    //
    // and you can do whatever want to do
    // but have to call next
    //
    next()

})

// and your router looks like

router.get('/callback', (req, res) => {
    // do what have to do
})

Option 2 - declare the middleware and use where you want
// defining this middleware somewhere in the code
const catchAsync = async(req, res, next) => {
    if (!req.query.code) throw new Error('NoCodeProvided');
    const code = req.query.code;
    const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
    var response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
      {
        method: 'POST',
        headers: {
          Authorization: `Basic ${creds}`,
        },
      });
    var json = await response.json();

    req.session.token = json.access_token

    console.log(req.session.token)
    //
    // and you can do whatever want to do
    // but have to call next
    //
    next()
}

router.get('/callback', catchAsync, (req, res) => {
    // do what have to do
})

router.get('/loggedin', catchAsync, (req, res) => {
    // do what have to do
})