text:
Q: Can't read the numbers and values inside of a file in Java? First of all excuse my bad typing errors and posting mistakes because I'm new to the site and still learning how use it.
I'm supposed to create a code that asks the user if he wants to deposit or withdraw and then asks him to enter the file name and then uses the info inside to add to the account; anyway this code is about 25% finished and I'm having trouble while testing the code so far, because it doesn't seem to read the file's name after I enter it when it asks me, Do you know what may cause this problem? any suggestions or a feedback?
import java.io.*;
import java.util.*;

public class read {

    public static void main(String [] args)  throws FileNotFoundException {
        Double currentbalance = 500.00;
        System.out.println("To deposit enter 1");
        System.out.println("To Withdrwawl enter 2");
        Scanner depositOrWithdrawl = new Scanner(System.in);
        int choose = depositOrWithdrawl.nextInt();
        if(choose == 1) {

            double currentBalance = 500.00;
            System.out.println("your current balance is: $"+ currentBalance);
            System.out.println("Please enter the file name to deposit: ");
            Scanner deposit = new Scanner(System.in);
            String depositAmount = deposit.nextLine();
            File depositFile = new File(depositAmount);
            int nextLine = 1;

            while(deposit.hasNextLine()){
                double numbers = deposit.nextDouble();
                System.out.println("You are about to add: $"+ numbers + " To your Balance");
                currentBalance = currentBalance + numbers;
                System.out.println("Your current balance is: $" + currentBalance);
                nextLine++;
            }

        }
    }

}

By the way it will be very helpful if you tell me how to include the first few lines of the code  to use stackoverflow properly

A: If you want your loop to scan the file instead of stdin, you need to point the scanner to the file first:
deposit = new Scanner(depositFile);

A: I am guessing that you want to read the file, but you are not doing it anywhere in your program. This line File depositFile = new File(depositAmount); doesn't actually read a file, it only creates a File class object. I strongly suggest you google how to read a file in java. There are plenty of very good tutorials on this subject. Anyways the following code should help you in doing what you are trying to do :-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
// It is a bad practice to start a Java class name with a lower case character
public class IdentifiableImpl {

public static void main(String[] args) throws FileNotFoundException {
    Double currentbalance = 500.00;
    System.out.println("To deposit enter 1");
    System.out.println("To Withdrwawl enter 2");
    Scanner depositOrWithdrawl = new Scanner(System.in);
    int choose = depositOrWithdrawl.nextInt();
    if (choose == 1) {

        double currentBalance = 500.00;
        System.out.println("your current balance is: $" + currentBalance);
        System.out.println("Please enter the file name to deposit: ");
        // Scanner deposit = new Scanner(System.in);
        String depositAmount = depositOrWithdrawl.nextLine();
        File depositFile = new File(depositAmount);
        //  Create a stream to read from a file
        BufferedReader br = new BufferedReader(new FileReader(depositFile));
        // String st;
        // int nextLine = 1;
        String input;
        // Read a file line by line
        try {
            while ((input = br.readLine()) != null) {
                try {
                    // Convert read line into double
                    double numbers = Double.valueOf(input);
                    System.out.println("You are about to add: $" + numbers + " To your Balance");
                    currentBalance = currentBalance + numbers;
                    System.out.println("Your current balance is: $" + currentBalance);
                    // nextLine++;
                }
// Handle bad input gracefully
catch (NumberFormatException e) {
                    System.out.println("Seems like there is an invalid amount in input file." + input
                            + " Will not proceed further");
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//Close the stream in finally block
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

}


text:
Q: Flutter Android Build Stuck after Upgrading to Android V2 I am experiencing this issue when I am trying to run my app on an Android Emulator(API 31, Android 12) after upgrading to Android V2:
Normal Run gets Stuck here:
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Error waiting for a debug connection: The log reader stopped unexpectedly
Error launching application on sdk gphone64 x86 64.

Running it with the flutter run --verbose gets stuck with the last output being:
[   +1 ms] Installing build\app\outputs\flutter-apk\app.apk... (completed in 4.5s)
[   +3 ms] executing: C:\Users\14166\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell echo -n 32cccba394c538fcf9ce787aea14716102705201 >
/data/local/tmp/sky.com.example.flutter_urban_state.sha1
[  +71 ms] executing: C:\Users\14166\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell -x logcat -v time -t 1
[ +315 ms] --------- beginning of main
                    02-24 07:38:41.859 E/.apps.wellbein( 7277): Not starting debugger since process cannot load the jdwp agent.
[  +15 ms] executing: C:\Users\14166\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell am start -a android.intent.action.RUN -f 0x20000000 --ez enable-dart-profiling true
--ez enable-checked-mode true --ez verify-entry-points true com.example.flutter_urban_state/com.example.flutter_urban_state.MainActivity
[+1065 ms] Starting: Intent { act=android.intent.action.RUN flg=0x20000000 cmp=com.example.flutter_urban_state/.MainActivity (has extras) }
[   +1 ms] Waiting for observatory port to be available...

Things I tried that did not work:

*

*Clearing the build, cache, and deleting the outputs folder in build and restarting the app again

*Made sure that the package names in AndroinManifest, and MainActivity.kt are exactly the same

*Upgraded my Dart Version, Flutter Version, and All my pub packages

*uninstalled my adb

Flutter doctor doesn't seem to show any errors either.

A: So after spending a lot of time I was able to fix the issue.
What I did to fix it:

*

*Changed the SDK version in the pubspec.yaml from sdk: ">=2.12.0 <3.0.0" to   sdk: ">=2.16.1 <3.0.0"

*In my AndroidManifest.Xml moved my manually added <meta-data.../>
sections to be under the <application.../> tag, where as they were
included under the <activity.../> tag before

I really hope this answer is useful and will help someone!
Cheers

A: For my case I got this issue and it should be coming from a package. The solution for me was to set the android:exported="true" (it was false)
<activity
android:name="com.example.lib.MainActivity"
android:label="Example"
android:exported="true">

redpajama_set_name: RedPajamaStackExchange


text:
Q: WHERE conditions in query using two columns My question is better explained by the following example:
select *
from PEOPLE
WHERE
  NAME like @SearchString OR
  SURNAME like @SearchString OR
  NAME + SURNAME like @SearchString OR
  SURNAME + NAME like @SearchString

Basically which is the exact syntax for:
NAME + SURNAME like @SearchString OR
SURNAME + NAME like @SearchString

? (I want to be able to search in 2 fields at the same time)
Imagine the case where @SearchString = 'John Doe'
Thanks.
Update:
to better express myself what i mean is that the following query returns no results, even if JOHN DOE is in the table
declare @searchstring varchar(100)
set @searchstring = 'John%Doe'

select *
from PEOPLE
WHERE
  NAME + SURNAME like @searchstring

A: By trial and error I realized the syntax
WHERE NAME + SURNAME like @SearchString

is correct and works fine. May be it is an overhead in some cases but it works fine in a normal (no big data) scenario.
For the pleasure of sharing I write here the query i used inmy real application (a web application that returns a list of people where the user just has one editbox to search: so he can search "John D", "Doe John", "John", "Doe", ...):
declare @searchstring varchar(100)
set @searchstring = 'John Doe'

SELECT *
FROM PEOPLE
WHERE ( (SURNAME LIKE @SearchString) OR
       (NAME LIKE @SearchString) OR
       (NAME + ' ' + SURNAME LIKE @SearchString) OR
       (SURNAME + ' ' + NAME LIKE @SearchString))


text:
Q: Is it possible to install Flow on Windows 10 I am trying to install flow but I am on Windows 10. When reading the installation instruction https://flow.readthedocs.io/en/latest/flow_setup.html#local-installation I feel like it is only possible to do it on a Ubuntu/Mac distribution ...
Do you know if it is possible to install it on Windows 10 ?
Thank you

A: I had the same question some weeks ago and came to the conclusion, that is is not possible to install the whole thing on windows. The whole learning part is done with the help of the ray framework, which unfortunately is not available on windows, yet.
I ended up creating an ubuntu partition on my windows laptop, to be able to use it.
BR, Vallout

A: If you are running windows10 professional. I would suggest you to run flow in  ubuntu virtual machine through hyper-v. It is very convenience other than you are not able to utilise gpu.


text:
Q: JVM bug? java.lang.VerifyError: Bad type on operand stack Using org.apache.wss4j artifacts to support ws-security part of a SOAP service calling inside a Play Framework (Java version) application resulted in this mess:

java.util.concurrent.CompletionException: java.lang.RuntimeException: java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator.validateSignedEncryptedPolicies(Ljava/util/List;Ljava/util/List;Ljava/util/List;Lorg/apache/cxf/message/Message;)Z @28: invokespecial
  Reason:
    Type 'org/apache/wss4j/policy/model/EncryptedParts' (current frame, stack[1]) is not assignable to 'org/apache/wss4j/policy/model/SignedParts'
  Current Frame:
    bci: @28
    flags: { }
    locals: { 'org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator', 'java/util/List', 'java/util/List', 'java/util/List', 'org/apache/cxf/message/Message' }
    stack: { 'org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator', 'org/apache/wss4j/policy/model/EncryptedParts', integer, 'java/util/List', 'java/util/List', 'org/apache/cxf/message/Message' }
  Bytecode:
    0x0000000: 2a2a b400 2d03 2c2b 1904 b700 2e9a 0005
    0x0000010: 03ac 2a2a b400 2f04 2d2b 1904 b700 2e9a
    0x0000020: 0005 03ac 2a2a b400 3003 2c2b 1904 b700
    0x0000030: 319a 0005 03ac 2a2a b400 3203 2d2b 1904
    0x0000040: b700 31ac
  Stackmap Table:
    same_frame(@18)
    same_frame(@36)
    same_frame(@54)

        ... suppressed 8 lines
Caused by: java.lang.RuntimeException: java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator.validateSignedEncryptedPolicies(Ljava/util/List;Ljava/util/List;Ljava/util/List;Lorg/apache/cxf/message/Message;)Z @28: invokespecial
  Reason:
    Type 'org/apache/wss4j/policy/model/EncryptedParts' (current frame, stack[1]) is not assignable to 'org/apache/wss4j/policy/model/SignedParts'
  Current Frame:
    bci: @28
    flags: { }
    locals: { 'org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator', 'java/util/List', 'java/util/List', 'java/util/List', 'org/apache/cxf/message/Message' }
    stack: { 'org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator', 'org/apache/wss4j/policy/model/EncryptedParts', integer, 'java/util/List', 'java/util/List', 'org/apache/cxf/message/Message' }
  Bytecode:
    0x0000000: 2a2a b400 2d03 2c2b 1904 b700 2e9a 0005
    0x0000010: 03ac 2a2a b400 2f04 2d2b 1904 b700 2e9a
    0x0000020: 0005 03ac 2a2a b400 3003 2c2b 1904 b700
    0x0000030: 319a 0005 03ac 2a2a b400 3203 2d2b 1904
    0x0000040: b700 31ac
  Stackmap Table:
    same_frame(@18)
    same_frame(@36)
    same_frame(@54)

        at ir.iais.playCommons.utils.F$Promise$1.get(F.java:232) ~[play-commons_2.11-2017.0.2.12-SNAPSHOT.jar:2017.0.2.12-SNAPSHOT]
        ...
        ... 5 more
Caused by: java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator.validateSignedEncryptedPolicies(Ljava/util/List;Ljava/util/List;Ljava/util/List;Lorg/apache/cxf/message/Message;)Z @28: invokespecial
  Reason:
    Type 'org/apache/wss4j/policy/model/EncryptedParts' (current frame, stack[1]) is not assignable to 'org/apache/wss4j/policy/model/SignedParts'
  Current Frame:
    bci: @28
    flags: { }
    locals: { 'org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator', 'java/util/List', 'java/util/List', 'java/util/List', 'org/apache/cxf/message/Message' }
    stack: { 'org/apache/cxf/ws/security/wss4j/policyvalidators/AbstractSupportingTokenPolicyValidator', 'org/apache/wss4j/policy/model/EncryptedParts', integer, 'java/util/List', 'java/util/List', 'org/apache/cxf/message/Message' }
  Bytecode:
    0x0000000: 2a2a b400 2d03 2c2b 1904 b700 2e9a 0005
    0x0000010: 03ac 2a2a b400 2f04 2d2b 1904 b700 2e9a
    0x0000020: 0005 03ac 2a2a b400 3003 2c2b 1904 b700
    0x0000030: 319a 0005 03ac 2a2a b400 3203 2d2b 1904
    0x0000040: b700 31ac
  Stackmap Table:
    same_frame(@18)
    same_frame(@36)
    same_frame(@54)

        at org.apache.cxf.ws.security.wss4j.policyvalidators.ValidatorUtils.configureSupportingTokenValidators(ValidatorUtils.java:97) ~[cxf-rt-ws-security-3.1.7.jar:3.1.7]
        at org.apache.cxf.ws.security.wss4j.policyvalidators.ValidatorUtils.(ValidatorUtils.java:46) ~[cxf-rt-ws-security-3.1.7.jar:3.1.7]
        at org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JInInterceptor.doResults(PolicyBasedWSS4JInInterceptor.java:576) ~[cxf-rt-ws-security-3.1.7.jar:3.1.7]
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessageInternal(WSS4JInInterceptor.java:277) ~[cxf-rt-ws-security-3.1.7.jar:3.1.7]
        at org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:171) ~[cxf-rt-ws-security-3.1.7.jar:3.1.7]
        at org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JInInterceptor.handleMessage(PolicyBasedWSS4JInInterceptor.java:80) ~[cxf-rt-ws-security-3.1.7.jar:3.1.7]
        at org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JInInterceptor.handleMessage(PolicyBasedWSS4JInInterceptor.java:66) ~[cxf-rt-ws-security-3.1.7.jar:3.1.7]
        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:798) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1670) ~[cxf-rt-transports-http-3.1.7.jar:3.1.7]
        at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1551) ~[cxf-rt-transports-http-3.1.7.jar:3.1.7]
        at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1348) ~[cxf-rt-transports-http-3.1.7.jar:3.1.7]
        at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:651) ~[cxf-rt-transports-http-3.1.7.jar:3.1.7]
        at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:514) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:423) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:324) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:277) ~[cxf-core-3.1.7.jar:3.1.7]
        at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96) ~[cxf-rt-frontend-simple-3.1.7.jar:3.1.7]
        at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139) ~[cxf-rt-frontend-jaxws-3.1.7.jar:3.1.7]
        at com.sun.proxy.$Proxy124.sendMessageToConsignee(Unknown Source) ~[?:?]
        at ir.iais.rasam.services.AnnouncementAboutDeclarationService$1.get(AnnouncementAboutDeclarationService.java:61) ~[classes/:?]
        at ir.iais.rasam.services.AnnouncementAboutDeclarationService$1.get(AnnouncementAboutDeclarationService.java:48) ~[classes/:?]
        at ir.iais.playCommons.utils.F$Promise$1.get(F.java:230) ~[play-commons_2.11-2017.0.2.12-SNAPSHOT.jar:2017.0.2.12-SNAPSHOT]
        ...
        ... 5 more

The used modules of org.apache.wss4j artifacts are these:
"org.apache.wss4j" % "wss4j-bindings" % wss4jversion,
"org.apache.wss4j" % "wss4j-policy" % wss4jversion,
"org.apache.wss4j" % "wss4j-ws-security-dom" % wss4jversion,
"org.apache.wss4j" % "wss4j-ws-security-stax" % wss4jversion,
"org.apache.wss4j" % "wss4j-integration" % wss4jversion,
"org.apache.wss4j" % "wss4j-ws-security-policy-stax" % wss4jversion,
"org.apache.wss4j" % "wss4j-ws-security-common" % wss4jversion,

Where wss4jVersion is:
val wss4jVersion = "2.1.10"

By searching this part: Type ... (current frame, stack[1]) is not assignable to ... I landed on this page that said the problem is from JVM. However this Q/A is for 2013 and by now this bug must be resolved.
Besides if I replace all of above dependencies from org.apache.wss4j artifacts by this one: "org.apache.ws.security" % "wss4j" % "1.6.18" (well it means downgrading the package), the problem will be solved and service calling will work successfully.
Now my question is: Where the bug has lied? in JVM or WSS4J or Play Framework?
Play Framework version: 2.5.8
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)

A: The problem is caused by the version incompatibility between Apache CXF Runtime and WSS4J.
cxf-rt-ws-security 3.1.7 depends on wss4j-policy 2.1.7, but you use wss4j-policy 2.1.10.
The bytecode verifier fails since EncryptedParts class from wss4j-policy cannot be longer assigned to SignedParts (though in earlier versions these classes were in the same hierarchy).
There are two ways to solve the problem:

*

*upgrade Apache CXF Runtime to version 3.1.11 or above;

*downgrade Apache WSS4J to version 2.1.7 or below.


text:
Q: Django - how to import from a .csv file in memory I'm writing a page to upload a .csv file and import its content into my models. My current view:
class ContentImport(LoginRequiredMixin, PermissionRequiredMixin,View):
    permission_required = 'delivery.change_delivery'

    def get(self, request, *args, **kwargs):
        form = UploadFileForm()
        return render(request, 'delivery/content_import.html', { 'form': form })

    def import_contents(self, f):
        reader = csv.reader(f)
        for row in reader:
            print row[0]

    def post(self, request, *args, **kwargs):

        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            self.import_contents(request.FILES['file'].read())
            messages.add_message(self.request, messages.SUCCESS, "Contents deleted successfully.")
            return redirect(reverse('delivery:delivery-detail', args=[self.kwargs['delivery_id']]))
        else:
            messages.add_message(self.request, messages.ERROR, "Select a file to upload.")
            return redirect(reverse('delivery:delivery-content-import', args=[self.kwargs['delivery_id']]))

My question is about the import_contents method and the call for it self.import_contents(request.FILES['file'].read()). When I print row[0] I get the following error: list index out of range.
My idea with this view is to upload a file, not saving it in the server, read the .csv from the memory and create new records in my models. This read from .csv I got from other answers here in stackoverflow.
I think the problem is how I pass the file to the import_contents function or how I read from it. I just can't figure out. Can you help me? If you have a suggestion on how to do it in an easier way, or the right way, let me know.
Thanks for any help

A: This is your problem.
self.import_contents(request.FILES['file'].read())

csv.reader() expects a file like object, not its content.
This can definitely be construed as a related answer.


text:
Q: Tcl: How to get namespace and procedures of calling namespace? I have some generic procedure. I would like this procedure to be able to get the name of the namespace and names of the procedures within the namespace where this procedure is called.
I have tried following code:
proc register {} {
    puts [info procs]
    puts [namespace current]
}

namespace eval Foo {
    proc bar {} {
        puts bar
    }

    proc _baz {} {
        puts baz
    }

    register
}

However, this prints results for the namespace where register is defined, not for the namespace where it is executed. It looks like there are no dedicated commands for these tasks or at least these are not info or namespace commands.

A: To get information about the calling context, use uplevel:
proc register {} {
    puts [uplevel 1 [list info procs]]
    puts [uplevel 1 [list namespace current]]
}


text:
Q: How to define a custom keyPad in my App? I want define a custom keyboard in my App,When I  press one TabBar Item in my UITabBarController, then custom keyboard slide up, when I touch the the tabview, I hope the custom keyboard can slide down, But, Because the custom keyboard add in UITabBarController's view, and tableView add in UIViewController one of UITabBarController's  ViewController, they are not in the same Class, How can I define the Keyboard, and add to which view?
I want to do like this:
When Press tab bar Item keyboard slide up,
http://i.stack.imgur.com/66NDu.png
When touch tableview, keyboard slide down.
http://i.stack.imgur.com/ZiHaR.png

A: Make a custom UIView with your custom keyboard buttons.
UITextField and UITextView have a property called inputView. If you set your custom view to this, iOS automatically takes care of resignFirstResponder and becomesFirstResponder messages on the text field.
This is the easiest way to use a custom keyboard.

A: *

*Why are you declaring the custom keyboard in the UITabBarController class ? You can declare it in the view controller that is attached to that particular tabBarItem. If you add it to the that view controller, I am sure you can just make it resignFirstResponder or removeFromSuperView and manipulate it as you want.

*Or you can just create a separate class for your customKeyboard, and add it along with your other classes. Simply include that class and create objects in other view controllers to manipulate them, and then release them. This is very easy and it is better programming compared to your approach, as at a later point of time, if you need to make changes or release 2.0 version of your app, it will come in handy and save some development time !


text:
Q: How to pass custom argument to authorization policy I need a custom attribute for my rest API in asp.net core MVC. I want to add this attribute optionally to some of my APIs. This attribute checks if the API is accessible to user or not based on some condition and throws a 403 if it's not accessible. I was using filters to achieve this and the issue with filter is that filter code gets executed whether the attribute is added or not to my API.
I would want that my filter code is executed only when this attribute is added to the API.
My colleague suggested that I should be using authorization policy instead of filters for this use case. Policies are executed only when it's added to the API. Also since I am throwing 403, authorization policy is a better candidate. I explored authorization policy but my issue is I am unable to pass custom attributes to Authorization policy.
For example, I was able to do this using filters and custom attributes.
[MyCustomFeature("param1", "param2")]

How can I do the same in authorization policy? I am using this example for authorization policy.
Custom Authorization attribute asp.net core

A: See here. Strongly recommend reading top to bottom.
The summary is that, regardless of how you tap in to the policy-basd auth system, a policy is always resolved via a single string. So, to get what you want, you need to:

*

*Implement a custom attribute that subclasses AuthorizeAttribute and that takes the arguments you pass in and uses them to generate a policy name string. Read the "Custom Authorization attributes" example in the linked docs page closely, see how it actually stores the value of "Age" in the Policy string.

*Implement and register a custom IAuthorizationPolicyProvider that can interpret the strings generated by your custom attribute and generate the appropriate policy on the fly.

There's not a ton of code involved and it's not super complex, but it's a little strange/awkward that it comes down to putting stuff into a string.


text:
Q: Amazon S3 Permission Issue I have 2 buckets for my application:
- gambify-dev-devil ( for development)
- gambify-prod (for production)
I have set them up absolutely identical, but for my production I have issues accessing some ressources. My production environment is a pagodabox. I use Gaufrette, LiipImagine and Vichuploader for my File handling. The issue I have is that in my production environment seems that either my application requests the wrong ressources or that there is an access issue. Because I have a lot logs indicating the an AccessDenied error within my bucket:
<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>D90C05F182C91003</RequestId>
<HostId>
i7SkwNCbyUnCCBCnkyyrv7x9pOLGtr4sUgqWYkJMqk0X0lXYIW5zeu4688FCqBiA
</HostId>
</Error>

In order to investigate this issue further (I really have no idea where it is coming from because its working fine in every other environment and also in production it was working fine 2 weeks ago), I would like to see which ressource was requested. Is there a chance to find the URL that was requested or who tried to request what, that caused this issue? Because if I provide a correct path to an existing ressouce the bucket works fine:
e.g: https://s3-eu-west-1.amazonaws.com/gambify-prod/profile/default.png
Update:
Now I found the real error message that is causing me problems:

04fadbab7a82c23143855d5c918e1ba8fa32ef1d622c00a3daa9fcdc6daf5d90
  gambify-prod [05/Aug/2013:19:03:57 +0000] 173.193.185.250 -
  133EF43443891C63 REST.HEAD.OBJECT
  profile_thumb_small/51e9a03453c80.jpeg "HEAD
  /profile_thumb_small/51e9a03453c80.jpeg HTTP/1.1" 403
  SignatureDoesNotMatch 1015 - 7 -
  "https://gambify-prod.s3.amazonaws.com/profile_thumb_small/51e9a03453c80.jpeg"
  "aws-sdk-php/1.5.17.1 PHP/5.3.23 Linux/2.6.32-042stab068.8 Arch/x86_64
  SAPI/fpm-fcgi Integer/9223372036854775807 Build/20121126140000
  simplexml/0.1 json/1.2.1 pcre/8.31 spl/0.2 curl/7.19.7 openssl/0.9.8k
  apc/3.1.9 pdo/1.0.4dev pdo_sqlite/1.0.1 sqlite/2.0-dev sqlite3/0.7-dev
  zlib/1.1 memory_limit/200M date.timezone/Europe.Berlin
  open_basedir/off safe_mode/off zend.enable_gc/on" -

I still have no idea what is causing the initial issue.
Moved the discussion about the signature error to: Amazon S3 signature not working with SDK

A: If you haven't already done so, you can configure your production bucket to keep a log of all the requests made against it, similar to an Apache or other web server access log.
http://docs.aws.amazon.com/AmazonS3/latest/dev/ServerLogs.html
Once you have logging enabled, you will be able to find out the URL of the request, who requested it and when it was requested.
Update:
If an AccessDenied error is returned when trying to access the S3 server log files through the API or the AWS console, the problem is caused by missing permissions (ACLs) on the log files.
To access those log files, the Open/Download permission should be granted for the user that owns them. Having a bucket policy with public read enabled is not enough to get access to the server log files.
More details on the issue are available in the comments below.

A: These look like responses that S3 sends back when the ACL/Grant permissions aren't set correctly. I'd check those first. If your bucket is behind a CloudFront distribution, make sure you invalidate the CloudFront cache as well.


text:
Q: Folder browser/picker breaks when ported to Mac I've been searching for awhile for an answer to this, almost all were vague, so I'm still pretty clueless. I created a program that opens 2 files, synchronizes them, and then saves the file to a location the user chooser. Works perfect on Windows, which is what I assumed it would run on (stupid assumptions...), but is broken on Mac. I've been able to fix the opening of folders, but I need the saving section fixed. Heres the code:
Function GetFolder(strPath As String) As String
Dim sItem As String
Dim sFile As String
Dim fldr As FileDialog
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)

With fldr
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = strPath

    If .Show <> -1 Then GoTo NextCode
    sItem = .SelectedItems(1)
End With

NextCode:
GetFolder = sItem
Set fldr = Nothing

sFile = "\" & sSubID & "-" & sSubSession & "-synced.txt"
ActiveWorkbook.SaveAs Filename:=sItem & sFile, FileFormat:=xlTextWindows, CreateBackup:=False
End Function

I need to be able to control the NAME of the file with the program (subject's ID and session ID) but I need the FOLDER to save it to. I'm pretty knew to Mac, but pick up on things relatively quickly. Any advice would be appreciated!

A: For future searchers:
Function GetFolder(strPath As String) As String
Dim sFile As String
Dim folderPath As String
Dim RootFolder As String

sFile = sSubID & "-" & sSubSession & "-synced.txt"
On Error Resume Next
RootFolder = MacScript("return (path to desktop folder) as String")
folderPath = MacScript("(choose folder with prompt ""Select the folder""" & _
"default location alias """ & RootFolder & """) as string")
On Error GoTo 0

If folderPath <> "" Then
   ActiveWorkbook.SaveAs Filename:=folderPath & sFile, FileFormat:=xlTextWindows, CreateBackup:=False
End If

Please note, after a few pages on Google, I finally stumbled upon this site:
http://www.rondebruin.nl/mac/section3.htm

A: I think I found your problem :
sFile = "\" & sSubID & "-" & sSubSession & "-synced.txt"

Backslash \ are specific for Windows paths. For UNIX based OS, you have to use /.
Some tip found on the Internet to have a cross-platform path :
Application.PathSeparator

For your line, it would be :
sFile = Application.PathSeparator & sSubID & "-" & sSubSession & "-synced.txt"


text:
Q: Unable to click on shadow root element using Selenide I've imported Selenide shadowCss selector into my project and now trying to click on the element that is under shadow-root. Sadly no luck but I've managed to do it with javascript but how to do it properly with Selenide?
import static com.codeborne.selenide.Selectors.shadowCss;

Trying to click on "Installed products"

    <company-tab variant="light" class="hydrated">
     #shadow-root (open)

        <company-vst class="hydrated"></company-vst>

            <company-tab-header data-index="2" is-key-press class="hydrated">

            <button class="company-tab-header company-tab-header--light" role="tab" tabindex="-1" data-index"2">

              <company-icon class="company-tab-header__icon company-icon company-icon--md hydrated">...</company-icon>

               Installed products
               Installed products

              ::after
             </button>
                 .........

JS that managed to capture "Installed products"
document.querySelector('#__next > div > main > div > div > div:nth-child(2) > div.sc-50b84693-2.ebYhch > div > div > div.sc-50b84693-1.dUDDAN > div > company-tab').shadowRoot.querySelector('ul:nth-child(1) >li:nth-child(3) > company-tab-header >button > span >span>span.company-tab-header__hidden-title')

examples of shadowCss use: https://github.com/selenide/selenide/blob/master/src/test/java/integration/ShadowElementTest.java
Using 5.20 Selenide version. Upgrade is not possible in this case.

A: locating button with shadowCss Selenide:
@And("click installed products")
public void clickInstalledProducts() {
    $(shadowCss("button[data-index='2']", "company-tab")).click();
        System.out.println("Managed to click");
");

Sadly by text we were not able to find solution, but we managed to catch element with button tag.


text:
Q: Searching for quotation marks in a varchar(max) field I have a field in a table set to VARCHAR(MAX) and I am unable to search for quotation marks ["].
If I search for any other character it is working.
select * from xml_file_log where request like '%"%'


text:
Q: Using an if/else statement in the middle of AWK I have a 5-column file:
PS 6 15 0 1
PS 1 17 0 1
PS 4 18 0 1

that I would like to get it in this 7-column format:
PS.15 PS 6 N 1 0 1
PS.17 PS 1 P 1 0 1
PS.18 PS 4 N 1 0 1

To create 6 of the 7 columns requires just grabbing directly (and sometimes applying small arithmetic) from columns in the original file. However, to create one column (column 4) requires an if-else statement.
Specifically, to create new columns 1, 2, 3, I use:
 cat File | awk '{print $1"."$3"\t"$1"\t"$2}'

and to create new columns 5, 6,7, I use:
 cat testFileB | awk '{print $4+$5"\t"$4/($4+$5)"\t"$5/($4+$5)}'

and to create new column 4, I use:
 cat testFileB | awk '{if ($2 == 1 || $2 == 2 || $2 == 3) print "P"; else print "N";}'

These three statements work fine independently and get me what I want (the correct values for the columns that are all separated by tabs). However, when I try to apply them simultaneously (create all 7 columns at once), I can only do so with unwanted new lines (instead of tabs) before and after column 4 (the if/else statement column):
For instance, my attempt to simultaneously create columns 1, 2, 3, 4:
 cat File | awk '{print $1"."$3"\t"$1"\t"$2; if ($2 == 1 || $2 == 2 || $2 == 3) print "P"; else print "N";}'

results in unwanted new lines before column 4:
PS.15 PS 6
N
PS.17 PS 1
P
PS.18 PS 4

Similarly, my attempt to simultaneously create columns 4, 5, 6, 7:
 cat File | awk '{if ($2 == 1 || $2 == 2 || $2 == 3) print "P"; else print "N"; print $4+$5"\t"$4/($4+$5)"\t"$5/($4+$5)}'

results in unwanted new lines after column 4:
N
1 0 1
P
1 0 1
N
1 0 1

Is there a solution so that I can create all 7 columns at once, and there are only tabs between them (no new lines)?

A: If you don't want automatic line feeds, you can just use printf instead of print. I'm not quite sure if you want a tab separating the N1 or not, but that's easy enough to adjust;
cat testfile | awk '{printf "%s.%s\t%s\t%s\t",$1,$3,$1,$2; if ($2 == 1 || $2 == 2 || $2 == 3) printf "P"; else printf "N"; print $4+$5"\t"$4/($4+$5)"\t"$5/($4+$5)}'

PS.15   PS  6   N1  0   1
PS.17   PS  1   P1  0   1
PS.18   PS  4   N1  0   1

A: Simply set your OFS (instead of repeating a \t all across the line), and use the ternary operator to print P or N:
$ awk -v OFS='\t' '{s=$4+$5;print $1"."$3,$1,$2,($2~/^[123]$/?"P":"N"),s,$4/s,$5/s}' file
PS.15   PS      6       N       1       0       1
PS.17   PS      1       P       1       0       1
PS.18   PS      4       N       1       0       1


text:
Q: Ansible Jinja2 template to replace only a few lines for a configuration file? (Jinja2 template doesn't cover the whole content of the target file) For example, the configuration file is as below:
    # debug flags = 0x0000000000000000
    # debug log = /var/log/netdata/debug.log
    # error log = /var/log/netdata/error.log
    # access log = /var/log/netdata/access.log
    # facility log = daemon
    # errors flood protection period = 1200
    # errors to trigger flood protection = 200
    # OOM score = 1000

I know I can make a Jinja file as below to achieve the task easily to define certain parameter as a variable:
    # debug flags = 0x0000000000000000
    # debug log = /var/log/netdata/debug.log
    # error log = /var/log/netdata/error.log
    # access log = /var/log/netdata/access.log
    # facility log = daemon
    # errors flood protection period = 1200
    # errors to trigger flood protection = 200
     OOM score = {{ variable }}

but if the base file itself is not totally definitive, where some of the other portion of the text may change over time(we don't wish to freeze the change due to Ansible/Jinja2 to make it static), so can I just define a Jinja2 template file only with the lines I care about, logic may like this:

*

*ignoring the lines which is not matched with OOM score =

*if the line matches OOM score =, change the line to OOM score = {{ variable }} with variable to substitute of course.

#jinja template
#ignore lines if it's not matched
     OOM score = {{ variable }}

I know the above case can be easily achieved by lineinfile, but let's say many lines need to do the same(not a block, scattered in a text file), is there a way to achieve by template/Jinja2 instead of lineinfile with loops?

A:
Q: "Is there a way to achieve by template/Jinja2 to replace only a few lines for a configuration file instead of lineinfile with loops?"

A: No. Modul template creates a temporary file from the template first. Then compares this temporary file with the current file, if any, and writes the file, if the files are different.
What you are looking for is to take the current file and create a template by adding lines which is defacto the functionality of the lineinfile module.


text:
Q: Angular 5 app doesn't render in safari mobile browser Hi I have a simple angular 5 application that uploads an image to my web server. This angular 5 app works perfectly in chrome(mobile/desktop) and only Safari desktop version. but when I access it from my iPhone using Safari as a web browser, it does not render.....to be able to work I have to enable JS:

When I make this configuration in IOS the web application works without problems...then my question is....what can I do so that my angular web app be rendered in mobile safari, without having to make this configuration in IOS?
Angular Code:
HTML

  <input type="file" class="custom-file-input" lang="es" (change)="onFileChange($event)">
  {{fileName}}

TS
export class AppComponent{
  title = 'app';
  fileName:string;
  base64:string;

  constructor(private imageService: ImageService) {
  }

  onFileChange(event) {
    let image:File = event.target.files[0];
    this.base64=image.name;
    this.imageService.saveImage(image).subscribe();
  }

Many thanks!

A: An Angular app (in Typescript) is transpiled in Javascript, so it will not work until JavaScript is enabled.
It looks like the default value of this setting is "enabled" so don't worry about your visitors.

A: The problem is with the IOS version (11.4.1) that I have, because when you've never manipulated it, the button looks like it's disabled, but it's actually active ... but when you manipulate it, it actually shows the status button ... that is, active or inactive...which means that JS is active by default in IOS, but it is shown as inactive
See more details


text:
Q: vim-latex and Okular: forward/inverse search not working for DVI I'm trying to get DVI forward search to work (I don't think SyncTeX is relevant) with vim-latex/latex-suite and Okular. I'm using Arch Linux.
I've been following the official vim-latex beginner's guide, and am up to this step. Some info:

*

*The \ll command correctly compiles the code. I can view the resulting DVI file in Okular.

*The \lv command correctly opens Okular and displays the file.

*If Okular is already open, the \ll command also causes Okular to reload the file automatically. I'm not sure if this is some sign that forward search is almost working, or if, by default, Okular just reloads when it detects changes.

*I installed vim-latex with Vundle, so I have the directory ~/.vim/bundle/vim-latex/ftplugin/ instead of ~/.vim/ftplugin/. There is no tex.vim file in ftplugin/, but there is bib_latexSuite.vim, latex-suite/, and tex_latexSuite.vim.

*Okular is shown here to support forward search.

As for inverse search, I placed the command gvim -c ":RemoteOpen +%l %f" (according to this page) in Okular > Settings > Configure Okular > Editor > Command, but Shift+leftclick in browse mode doesn't do anything.


text:
Q: How to catch correct value in conditional in React.js? const [
  MessageListDataProvider,
  useMessageListData
] = constate(() => {
  const [newValue, setNewValue] = useState({})

  const [messagePath, useMessagePath] = useState(api.UNRESOLVED_MESSAGES_PATH)
  const getMessagePath = (newPath) => {
    useMessagePath(newPath)
  }
  const {
    value,
    loading,
    error,
    retry: refresh
  } = useAsyncRetry(async () => {
    return api.fetchAllMessages(messagePath)
  }, [messagePath])

   if (value !== undefined) {
    console.log('value.messages', value.messages.length)
    if (!newValue[messagePath]) {
      console.log('newValue in conditional', newValue)
      setNewValue(oldObj => ({ ...newValue, [messagePath] : value.messages }))
    }
  }
  console.log('newValue', newValue)
  return {
    newValue,
    getMessagePath,
    value,
    loading,
    error,
    refresh
  }
})

I am trying to store specific values from an API call in a separate object based different keys.
example:
newValue : {
    `/messages?limit=100&offset=0`: [{}, {}, {}],
    `/messages?status=Unresolved&limit=100&offset=0`: [{}, {}, {}, {}, {}],
}

Strangely, the key gets updated and added but not the array value???!
See below...

Any idea how I can—for a lack of a better idea "catch" that API array value?


text:
Q: Erlang type system I've been scrounging around the web looking for various typing practices of Erlang programs and there seem to be a few... although its somewhat difficult to find a solid source of info
namely Im looking for practical info about:
1.-specs - this one looks pretty attractive. a few places mention that the functions that have an associated -specs directive with it are checked at compile time(for correct type usage)... I cant seem to find more info on how to use it (which tool to use - Dialyzer,TypEr?). Im really eager to create a small parser/code-gen that would generate these "specs" from function declarations of the form
functionName(param1 :List, param2 :Tuple) -> ...

I have not seen if -spec supports abstract types (user declared types - "Car" type -
{car,{weight,_},{height,_},{maxSpeed,_}}

2.-deftype directive mentioned here
Erlang would become so much more powerful for me, if I could start typing things and have them be checked at compile time. The run-time the parser/code-gen I mentioned above would generate guard type checks in the output source-code.

A: Take a look to
http://learnyousomeerlang.com/types-or-lack-thereof
(very clean explanation) and the reference here:
http://erlang.org/doc/reference_manual/typespec.html

A: More info on the type and spec attributes here:
http://www.erlang.org/eeps/eep-0008.html
Dialyzer can be used to check them (see dialyzer --help).
Typer can be used to generate them (see typer --help).

A: Compile time type checking is not the done thing with Erlang. Instead use the Dialyzer which performs post-compile type checking.
The way in which you create 'user-defined types' is by using tagged tuples as you suggest.  The Dialyzer will examine code paths to identify ones that MIGHT end up creating function returns that fail.
For the dialyzer to work best you must embrace 'let if fail' and only write clauses that match the expected results - eschew 'else' constructs that always match and a few other best practices.
You should document your functions with edoc. The dialyzer uses the type specification of the document system to infer types for you. The edoc manual can be found here.


text:
Q: Flutter slideTransition is not animating So I'm trying to create a trivial slide transition element in flutter and I'm having some difficulty. What the below does is wait for the animation time, and then just display the Text("hello there sailor"). I don't know why this is not animating - it seems very similar to this previous post that has a trivial example (Sliding animation to bottom in flutter).
This is how I call the below code: DeleteCheck(offsetBool: widget.model.deleteNotify, widthSlide: 0.50*width100) where double width100 = MediaQuery.of(context).size.width;.
Does anyone see what I am doing wrong?
class DeleteCheck extends StatefulWidget{

  final offsetBool;
  final double widthSlide;

  DeleteCheck({
    Key key,
    this.offsetBool,
    this.widthSlide
  }): super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _MyDeleteCheck();
  }
}

class _MyDeleteCheck extends State<DeleteCheck> with TickerProviderStateMixin {
  AnimationController _controller;
  Animation<Offset> _offsetFloat;

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

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );

    _offsetFloat = Tween<Offset>(begin: Offset(widget.widthSlide, 0.0), end: Offset.zero)
        .animate(_controller);

    _offsetFloat.addListener((){
      setState((){});
    });

    _controller.forward();

  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double height100 = MediaQuery.of(context).size.height;
    double width100 = MediaQuery.of(context).size.width;
    return new SlideTransition(
      position: _offsetFloat,
      child: Container(
        color: Colors.cyan,
        width: 0.525*width100-3.0,
        child: Text("hello there sailor")
      )
    );
  }
}

A: I have good news for you! Your code is working! :) The animation looks like it is not happening, because the distance it moves is huge. The Offset, passed to the SlideTransition, is relative to its childs size. For example your child has width: 100.0 and you offset with Offset(2.0, 0.0), your child will have moved 200.0 pixels to the right.
Just try to
change begin: Offset(widget.widthSlide, 0.0), end: Offset.zero
to begin: Offset(2.0, 0.0), end: Offset.zero. You'll see the text slowly animating from the right to the center of the screen. Therefore you just need to adjust your parameterisation.

Anyway here are some additional suggestions for optimizing your code:

*

*If you are using prebuilt AnimatedWidgets like the SlideTransition, you do not need to call addListener with setState on the controller. The AnimatedWidget takes care of it by itself. Hence you can remove the follwing lines:

lines:
_offsetFloat.addListener((){
  setState((){});
});

*

*Also it is not necessary to call const constructors. You can just leave this keyword out like new. The compiler will optimize and choose the right constructor in each case.


text:
Q: Windows Live OAuth access XBox Live Info So, I'm working on a website, and I want users to be able to log in with their xbox account to link their gamer tag to my site. I can use oauth like this:

But, I can't figure out how to get xbox live permissions. Other sites that do this have permissions like this:

How do I get this permissions which allow me to get info from an xbox account, like the gamertag? On the permissions page I don't see xbox anywhere.

A: You can do this pretty easily by using Xbox Live API,
Sign up for the Xbox Live Creators Program
and then you can call the Xbox Live REST endpoints directly to ask the user to authorize your application.
The official API documentation provides excellent examples to help you progress at a quick pace. Also you can refer to Windows UWP for Xbox Live Services for some detailed info.

Sources:
Xbox Live Creators Program
Github Repo of Xbox Live API


text:
Q: Scss Mixin Not Recognized New to Scss/Sass
I am attempting to use a mixin to structure a media query on the fly. I am doing this more as a test to pass the variable later in the particular module.scss file, but I am getting a strange error.
Here is my mixin code:
@mixin breakPoint($length){
    @media (max-width: $length){
        @content;
    }
}

Once in the mod file, I am attempting to write something like the following:
.header-fixedWidth
    {
        height: inherit;
        width: 853px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        justify-content: space-between;

        @include breakPoint(916px)
        {
            width: 90vw;
        }
    }

But, when I save/process the file, I get the following error: "Error No mixin named break backtrace: ..//[...]"
When I check the mixin.css page, nothing is being logged, so I am failing to pass something, I just don't know what.
Here is my overall style page, in case, perhaps, I am missing something there as well:
@import "Mods/_base";
@import "Mods/_headerAndNav";
@import "Mods/_mainContent";
@import "Mods/_mixins";

A: to use any mixin you need to make sure that your mixin files are already loaded , so if you use a mixin in _maincontent, given your overall SASS file, it will give an error, so do something like this:
@import "Mods/base",
        "Mods/mixins",
        "Mods/headerAndNav",
        "Mods/mainContent";

Or
@import "Mods/mixins",
        "Mods/base",
        "Mods/headerAndNav",
        "Mods/mainContent";


text:
Q: How to convert Psd to psf? I have PSD document but my client requires the file in .psf format.Is there any way to convert PSD file to PSf file? Desperately need help.

A: This is a rather strange request from a client, but I suppose there may be circumstances calling for such arcane undertakings.
Check this: https://fileinfo.com/extension/psf
Then locate that file, package and send.
RobC is correct in his comment. If I were you, I would research ICC (International Colour Consortium) processes. This is standard tools if you work in a (precision) print environment. The general thinking regarding screens (in my neck of the woods anyway) is that there is no colour control on the consumer side (meaning that screens produce varying colour results) and so don't bother with precision — just get it close.
If you want to comment on the specific end-use environment, we can respond to that.


text:
Q: Symfony 2.5 - IvoryCKEditorBundle fatal error (class not found) I was trying to get installed the bundle egeloen/IvoryCKEditorBundle in my Symfony 2.5 but it's my first time installing a bundle and I need specific steps to make it, I don't understand in which files I have to put the code lines to get it installed, I write the code in the README file in appKernel, autoload.php and composer.json. It runs in a local host and I Use Xampp, my OS is Windows 7.
The error I got was:

Fatal error: Class 'web\bundles\IvoryCKEditorBundle' not found in
D:...\Source\app\AppKernel.php on line 19


text:
Q: Prevent stdin wait for first message from named pipe I need to communicate with a background process via a named pipe. This background process is a node.js process.
So I do this in a shell script:
mkfifo MYPIPE
node script.js < MYPIPE

what happens is that the node.js script does not start - it appears to be waiting for the first stdin message to be written to MYPIPE.
What I want to do, is send the data from MYPIPE to the stdin of the node process, but I want to start the node.js process instead of it waiting for the first message from MYPIPE. How do I do that?

A: this was just a simple case of doing this instead:
cat MYPIPE | node script.js

I guess I just don't understand why that behaves differently than
node script.js < MYPIPE


text:
Q: How can I call a function within HTML tags inside a content editable div? Why can I call myFunction() onkeyup with this html:

A function is triggered when the user is pressing a key in the input field.

But I can't do it using this:

A function is triggered when the user is pressing a key in the input field.

In the second, I'm trying to call it only over a specific word, triggered, and I'm not sure what the difference is.  Thanks.
Check out the FIDDLE

A: Try this:
HTML (note that you have to set contenteditable on the span, not the parent paragraph, and it cannot be both):

A function is triggered when the user is pressing a key in the input field.

A function is triggered when the user is pressing a key in the input field.

Not Yet

CSS:
.bold { font-weight: bold; }

Fiddle: http://jsfiddle.net/wTy3C/2/


text:
Q: Tail a file efficiently in nodejs I am creating an application which would watch a file and fetch the contents  from that file (similar to tail but with the possibility of paging in previous data as well). I read up on quite a few solutions ranging from spawning a new process to getting only the updated bytes of the file but I am still a little confused on a few parts.
What I want to do exactly is the following:

*

*Watch a file and trigger an event/callback whenever new data comes into the file

*Read this new data from the file and efficiently send it to a client. Using a websocket or something else. (suggest a good way to do this please)

*At the client end, take this data and display it to user and keep updating it with new data as it comes

*If the user requests older data a way to fetch that data from the file we are watching

I am looking for efficient solutions for the above sub problems and any suggestions for a better approach are also welcome.
FYI I am new to nodejs so verbosity in your solutions would be highly appreciated.

A: Watch for changes
Suggest you look at chokidar, it is an optimized implementation of fs.watch, fs.events, the native node.js libraries.
// Initialize watcher.
const watcher = chokidar.watch('some/directory/**/*.xml', config);

// Add event listeners.
watcher
  .on('add', path => log(`File ${path} has been added`))
  .on('change', path => log(`File ${path} has been changed`))
  .on('unlink', path => log(`File ${path} has been removed`));

To get the changed value
Here you can look at diff module. And you will need to store the state of the previous and current files. In order to build the changes.
To notify the client
You will need to create a websocket server, recommend you to use socket.io and then in your application you will create the diff and send a websocket message to the server. The server will notify/broadcast the message to the needed clients.


text:
Q: Print Inheritance Function I am attempting to complete a past Object Oriented Programming examination paper that involves inheritance in C++. This is the UML .
I am trying to print the second line of the sample output, as shown on the question paper. The program should use inheritance to output the student name, DOB, and the department, but I am not sure how to output the first two. I have implemented inheritance but the print functions of the Person and Date classes do not print. Full code implementation here.
This is the Student class:
#include "Person.h"

class Student :
    public Person
{
public:
    Student(string, string, int, int, int);
    void print();
    ~Student();
private:
    string Dept;
};

Student::Student(string d, string name, int mm, int dd, int yy)
    : Person(name, mm, dd, yy)
{
    Dept = d;
}

void Student::print()
{
    cout << Dept;
}

This is the Person class:
#include "Date.h"

class Person
{
public:
    Person(string, int, int, int);
    void getName();
    void setName(string);
    void print();
    ~Person();
private:
    string Name;
    Date DOB;
};

Person::Person(string n, int bmonth, int bday, int byear)
    : DOB(bmonth, bday, byear)
{
    setName(n);
}

void Person::getName()
{
    cout << Name;
}

void Person::setName(string nm)
{
    Name = nm;

}

void Person::print()
{
    getName();
    cout << ", DOB: ";
    DOB.print();
}

Test output:
Student s("Applied Computing", "James Hall", 12, 12, 1988);
    cout << endl;
    cout << "Student created: ";
    s.print();

A: Are you trying to run the exact code that you supplied? Because it's missing the main function.
s.print() will never call the Person class print method, since you define a method with the same name in Student. Hence, it will only print the student's name. If you want to use the base class method, you have to either call it explicitly in the derived class' method (for instance, by writing Person::print() in the Student class print method), or simple not define another method with the same name on the derived class (you should read up on how inheritance and virtual classes works in C++). For your problem in particular, you'll want the first option, i.e., something like:
void Student::print()
{
  Person::print();
  cout << ", " << Dept << endl;
}

Also, it's good practice to flush the stream. Output streams are buffered, so you either flush them manually or hope that they get flushed. Add a cout << endl or a cout << flush at the end of printing.


text:
Q: Qt C++ QTabWidget I am designing a GUI without using only code and QLayout.
I have 2 Tabs, each with a QPushButton in them.
I already have the basic layout done and all that, and it's really basic, and will add functions to the QPushButtons later, just have them give a warning/message when clicked.
My problem is that I cannot seem to get the Widgets to resize with the window.
Here is my code:
//widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTabWidget>
#include <QPushButton>

class Widget : public QWidget
{
    Q_OBJECT
public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
private:
    QPushButton *btn1;
    QPushButton *btn2;
    QTabWidget *widg;
};
#endif // WIDGET_H

and here is it's .cpp file
//widget.cpp

#include "widget.h"
#include <QLayout>

Widget::Widget(QWidget *parent)
    : QWidget(parent), btn1(new QPushButton("Button 1")), btn2(new QPushButton("Button 2")),
      widg(new QTabWidget(this))
{
    QWidget *w1(new QWidget);
    QWidget *w2(new QWidget);
    widg->addTab(w1, "TAB 1");
    widg->addTab(w2, "TAB 2");
    resize(200,200);

//    w1->resize(this->width(),this->height());

    QGridLayout *L1(new QGridLayout);
    QGridLayout *L2(new QGridLayout);

    L1->addWidget(btn1,0,0);
    L2->addWidget(btn2,0,0);

    w1->setLayout(L1);
    w2->setLayout(L2);
}

Widget::~Widget()
{
}

I have looked online, but everything I found so far pointed to people using the ui-creator.
I am using Qt 6.3.0 C++.


text:
Q: get the container ID of an image What command do I run to get the container ID of an image?
I would think docker ps -a something...
CONTAINER ID   IMAGE                        COMMAND                  CREATED          STATUS                    PORTS                              NAMES
17ef697da46d   local_django         "/entrypoint /start"     56 minutes ago   Up 56 minutes             0.0.0.0:8000->8000/tcp             django-1

I only want the container ID returned from an image search

A: You can add the -q option to only get the ID back. And the -f option to filter on 'ancestor' which means the image name or any image in the chain of images it's based on.
ps -aqf ancestor=local_django

A: Based on image
docker ps -aqf ancestor=<image_name>

You can get it based on name as well
docker ps -aqf name=<container_name>

Also to get all container ids
docker ps -q


text:
Q: Compile with multiple cores with Intel Fortran for Linux there,
I ran into trouble in compiling my Fortran program. It took me over 40 mins to build the program on my institute's computer. I used the following specification for compiling my current program with the Intel Fortran compiler for Linux. Would anyone be kindly letting me know how to modify my command so that the compilation is done with the full support of multiple cores (in my case 8 cores per CPU)?
Thanks,
Li
FC= mpiifort
FCFLAGS = -g -O3 -openmp -xSSE4.2 -axAVX -mt_mpi -I$(MKLROOT)/include/intel64/lp64 -I$(MKLROOT)/include
LDFLAGS = $(MKLROOT)/lib/intel64/libmkl_blas95_lp64.a \
      $(MKLROOT)/lib/intel64/libmkl_lapack95_lp64.a \
      $(MKLROOT)/lib/intel64/libmkl_scalapack_lp64.a \
      -Wl,--start-group \
      $(MKLROOT)/lib/intel64/libmkl_cdft_core.a \
      $(MKLROOT)/lib/intel64/libmkl_intel_lp64.a \
      $(MKLROOT)/lib/intel64/libmkl_core.a \
      $(MKLROOT)/lib/intel64/libmkl_intel_thread.a \
      -Wl,--end-group \
      $(MKLROOT)/lib/intel64/libmkl_blacs_intelmpi_lp64.a \
      -lpthread -lm

PROGRAM = main
all: ${PROGRAM}
main: universe.o model.o variable.o toolbox.o
main.o: universe.o
universe.o: model.o
model.o: variable.o
variable.o: toolbox.o
%: %.o
    $(FC) $(FCFLAGS) -o $@ $^ $(LDFLAGS)
%.o: %.f90
    $(FC) $(FCFLAGS) -c $< $(LDFLAGS)
.PHONY: clean
clean:
    find . -maxdepth 1 -type f -name "*.txt" ! -name "_*.txt" -exec rm '{}' \;
    rm -f *.o
rm -f *.mod
rm -f *~
rm -f *.gz

A: The command you're looking for is make -j N, where N is the number of parallel make jobs you want to run concurrently. In your case, with 8 cores, that would be 8 or thereabouts.
Note that the number of source files and the dependencies between them can also limit the number of jobs make is able to run concurrently. In your case it seems you have a linear dependency chain between your object files, allowing no concurrency, so you might want to split your code into more source files.


text:
Q: Show that $\mathbb{C}^3$ is a vector space over $\mathbb{R}$ We know that $\mathbb{C}^3$ = {(z1, z2, z3) | z1, z2, z3 $\in$ $\mathbb{C}$}
How can I show that $\mathbb{C}^3$ is a vector space over $\mathbb{R}$?
Edit: Why was this closed? it is not a duplicate, the question is asking HOW to show something, the possible duplicate does not show how to do what this question is asking.

A: Hint: for $z\in\mathbb{C}$, write $z=x+iy$. Define scalar multiplication by $rz=rx+iry$ and addition by $(x+iy)+(x'+iy'):=(x+x')+i(y+y')$. You can even prove that $\mathbb{C}^3\cong\mathbb{R}^6$
Edit (Since OP seems confused about this).
We have $\mathbb{C}^3=\{(z_1,z_2,z_3): z_1,z_2,z_3\in\mathbb{C}\}$. We define scalar multiplication by $r\cdot(z_1,z_2,z_3)=(rz_1,rz_2,rz_3)$ for all $r\in\mathbb{R}$ and addition by $(z_1,z_2,z_3)+(w_1,w_2,w_3):=(z_1+w_1,z_2+w_2,z_3+w_3)$.
To show that $\mathbb{C}^3$ is a vector space over $\mathbb{R}$, we need to see that
(1) $\mathbb{C}^3$ with the addition defined above is an abelian group. This is trivially true (since you asked why it is closed under addition: well, obviously $(z_1+w_1,z_2+w_2,z_3+w_3)$ is a triplet of complex numbers, that is an element of $\mathbb{C}^3$!)
(2)$ (r_1r_2)\cdot(z_1,z_2,z_3)=r_1\cdot(r_2\cdot(z_1,z_2,z_3))$ for all $r_1,r_2\in\mathbb{R}$ and $(z_1,z_2,z_3)\in\mathbb{C}^3$. Again, this is trivial.
(3) $(r_1+r_2)\cdot(z_1,z_2,z_3)= r_1\cdot(z_1,z_2,z_3)+r_2(z_1,z_2,z_3)$. Again, this is trivial.
(4) $r\cdot((z_1,z_2,z_3)+(w_1,w_2,w_3))=r\cdot(z_1,z_2,z_3)+r\cdot(w_1,w_2,w_3)$. Again, this is trivial.
(5) $1\cdot(z_1,z_2,z_3)=(z_1,z_2,z_3)$. Again... this is trivial!
If you convince yourself that (1)-(5) are true, you got it.
Now if you want to see that $\mathbb{C}^3\cong\mathbb{R}^6$, write $(z_1,z_2,z_3)$ uniquely as $(x_1+iy_1,x_2+iy_2,x_3+iy_3)$ with $x_i,y_i\in\mathbb{R}$ and define $f:\mathbb{C}^3\to\mathbb{R}^6$ by
$$f(x_1+iy_1,x_2+iy_2,x_3+iy_3)=(x_1,y_1,x_2,y_2,x_3,y_3).$$
I leave it as an exercise to show that this is a linear isomorphism.


text:
Q: A vector space is finite dimensional if all of its proper subspaces are finite dimensional Suppose every proper subspace $(\neq V)$ of a vector space $V$ is finite dimensional. Prove that $V$ is finite dimensional.
This question just popped into my head when I was reading about inner product space, so I can't guarantee how legitimate the question is.
My try:
Assume V is an inner product space. Take any proper subspace $U$ of $V$. Then $V=U\oplus U^{\bot}$. Both $U$ and $U^{\bot}$ are finite dimensional. So they both have a basis of finite dimension and we will be done.
So for the inner product space $V$ the statement holds true.
What about other cases? Does the statement hold true for every vector space? Does there exist a characteristic to identify vector spaces with this property?

A: Let $V$ be an infinite dimensional vector space, let $v$ be a vector of $V$. Then in particular there exists a countable subset $\{v_1,\cdots, v_n,\cdots\}$ of $V$ such that $\{v_1,\cdots, v_n,\cdots\}$ spans a subspace of $V$. We may assume $\{v_1,\cdots, v_n,\cdots\}$ is a basis, so in particular $\{v_2,\cdots, v_n,\cdots\}$ spanns a proper subspace $U$ of $V$ which is of countable dimensionality. The finite dimensional case is automatic.

A: Your proof for inner product spaces can be generalized (in some sense) in the following manner:
Let $U$ be a (nonzero) subspace of $V$, and let $\ \mathcal U=\{u_1,\ldots, u_n\}$ be a basis for $U$.  Using Zorn's lemma we can extend $\ \mathcal U$ to a basis $\mathcal V$ of $V$.  Let $U'$ be the subspace spanned by $\mathcal V \setminus \mathcal U$. Then $V=U\oplus U'$, and since both $U$ and $U'$ are finite-dimensional it follows that $V$ is finite-dimensional.

A: Take a subspace $U$ of codimension $1$ (why exits it?), i.e. $\dim V/U = 1$. Applying the First Isomorphism Theorem to the the projection
$$\pi:V\longrightarrow V/U,$$
we have
$$\dim V = \dim(\ker\pi) + \dim (V/U).$$
But by hypothesis $\dim(\ker\pi)<\infty$.

A: You need to use the fact that every linearly independent set can be extended to a basis.
Then you can take any nonzero vector $v$, extend $\{v\}$ to a basis $B$, and consider the span of $B\setminus\{v\}$. Being finitely dimensional, it means that $B\setminus\{v\}$ is finite, so $B$ is finite, and so $V$ has a finite dimension.

It might be relevant to point out that the fact "every linearly independent set can be extended to a basis" is equivalent to the axiom of choice. Of course we need only a small fraction of choice for this specific proof (although that would alter the formulation a bit).
Nevertheless, it is consistent without the axiom of choice that there is a vector space which is not finitely dimensional, but every proper subspace does in fact have a finite dimension. Weird.


text:
Q: Update datatable based on user input, include update of corresponding columns, not just the one edited The small app below generates a DT::datatable with two columns x,y. X starts out being a random number with rnorm. y should be whatever x is plus 1.
The app allows the user to edit column x in a DT::datatable. I have built it so that the user can amend column x, however, column y does not update as expected, it just stays the same.
Shiny code:
library(shiny)
library(tidyverse)
library(shinydashboard)
library(scales)
library(DT)

# define functions

## generate example data
create_sample_df <- function(x) {
    data.frame(
        x = x %>% unlist
    ) %>% mutate(y = x + 1)
}

## render DT
render_dt = function(data, editable = 'cell', server = TRUE, ...) {
    renderDT(data, selection = 'none', server = server, editable = editable, ...)
}

# UI ----

header <- dashboardHeader(title = 'blah')
sidebar <- dashboardSidebar()
body <- dashboardBody(DT::DTOutput('ex_df'))
ui <- dashboardPage(header, sidebar, body)

# Server ----
server <- function(input, output) {

    x <- rnorm(10, 0, 2) %>% as.integer %>%  as.list

    # the df to be displayed as a DT::datatable.
    ex_df <- reactive({create_sample_df(x)})

    ## set to initially be the on open result of ex_df, before any user input
    reactivs <- reactiveValues(ex_df = ex_df)

    observeEvent(input$ex_df_cell_edit, {
        info = input$ex_df_cell_edit
        str(info)
        i = info$row
        j = info$col
        v = info$value

        # update budgets, which in turn is used to generate data during create_sample_df()
        x[[i]] <<- v

        # now update the reactive values object with the newly generated df
        reactivs$ex_df <<- reactive({create_sample_df(x)})
    })

    output$ex_df <- render_dt(data = reactivs$ex_df(),
                              rownames = FALSE,
                              list(target = 'cell',
                                   disable = list(columns = c(1))))

}

shinyApp(ui, server)

Screen shot:

In the screen I am about to edit the first row in column x from -1 to say 10. After hitting enter, desired result is that for row 1, x value is 10 an y value is 11.
Currently this does not happen, y stays the same no matter what. Also, The first attempt to edit column x does not work, only after the second attempt does the new value persist.

A: The problem is how you pass the reactive data to your custom render_dt. I'm not completely sure why, but changes to reactivs$ex_df are not recognised. The changes you see in the x column are not due to the updated ex_df, but the changes directly made in the table. Therefore, I changed it back to using renderDT directly. I've made some additional changes:

*

*ex_df itself is not reactive. It is stored in a reactiveValues object, where every entry itself is already reactive.

*assignments to reactiveValues don't need <<-

*the edited value in cell_edit is a character vector

library(shiny)
library(tidyverse)
library(shinydashboard)
library(scales)
library(DT)

# define functions

## generate example data
create_sample_df <- function(x) {
  data.frame(
    x = x %>% unlist
  ) %>% mutate(y = x + 1)
}

# UI ----

header <- dashboardHeader(title = 'blah')
sidebar <- dashboardSidebar()
body <- dashboardBody(DT::DTOutput('ex_df'))
ui <- dashboardPage(header, sidebar, body)

# Server ----
server <- function(input, output) {

  x <- rnorm(10, 0, 2) %>% as.integer %>%  as.list

  # the df to be displayed as a DT::datatable.
  ex_df <- create_sample_df(x)

  ## set to initially be the on open result of ex_df, before any user input
  reactivs <- reactiveValues(ex_df = ex_df)

  observeEvent(input$ex_df_cell_edit, {
    info = input$ex_df_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value

    # update budgets, which in turn is used to generate data during create_sample_df()
    x[[i]] <<- as.numeric(v)

    # now update the reactive values object with the newly generated df
    reactivs$ex_df <- create_sample_df(x)
  })

  output$ex_df <- renderDT({
    datatable(reactivs$ex_df,
              editable = "cell",
              rownames = FALSE,
              options = list(target = 'cell',
                             disable = list(columns = c(1))))
  })

}

shinyApp(ui, server)

Edit
here a solution without observeEvent and only a reactive() for ex_df. Then you can pass the unevaluated reactive to your render_dt function:
library(shiny)
library(tidyverse)
library(shinydashboard)
library(scales)
library(DT)

# define functions

## generate example data
create_sample_df <- function(x) {
  data.frame(
    x = x %>% unlist
  ) %>% mutate(y = x + 1)
}

## render DT
render_dt = function(data_in, editable = 'cell', server = TRUE, ...) {
  renderDT(data_in(), selection = 'none', server = server, editable = editable, ...)
}

# UI ----

header <- dashboardHeader(title = 'blah')
sidebar <- dashboardSidebar()
body <- dashboardBody(DT::DTOutput('ex_df'))
ui <- dashboardPage(header, sidebar, body)

# Server ----
server <- function(input, output) {

  x <- rnorm(10, 0, 2) %>% as.integer %>%  as.list

  # the df to be displayed as a DT::datatable.
  setup_df <- create_sample_df(x)

  ex_df <- eventReactive(input$ex_df_cell_edit, {
    # on startup
    if (is.null(input$ex_df_cell_edit)) {
      setup_df

      # for edits
    } else {

      info = input$ex_df_cell_edit
      str(info)
      i = info$row
      j = info$col
      v = info$value

      # update budgets, which in turn is used to generate data during create_sample_df()
      x[[i]] <<- as.numeric(v)

      create_sample_df(x)
    }
  },
  ignoreNULL = FALSE)

  output$ex_df <- render_dt(data_in = ex_df,
                            rownames = FALSE,
                            list(target = 'cell',
                                 disable = list(columns = c(1))))

}

shinyApp(ui, server)


text:
Q: Deleted ubuntu partition, re-partitioned it into an E: drive, now grub rescue I used the Windows Disk Management to delete the ubuntu partition, then re-partition the old space as an E: drive on the windows system. Now when I try to boot, I get an unknown filesystem error, then grub rescue starts.
I can get into windows using an Ubuntu OS drive I have and loading grub through it to boot windows, but how can I repair the computer so that I can boot windows without needing to use this flash drive?

A: You can use a Ubuntu LiveUSB to repair your bootloader..
Just boot using the live USB, not the other drive with Ubuntu, then install boot-repair, hit the fix button and it should be OK after the reboot..
You can download boot-repair using:
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install -y boot-repair && boot-repair

Take a look at the wiki page to get more details about boot-repair usage

A: Looks like you installed GRUB on first partition of your hard disk, instead of same partition you installed Ubuntu on.
Follow these steps to fix your MBR and restore Windows Bootloader.

*

*Boot into Windows installation disk.

*Select language.

*At System Recovery Options screen, select Command Prompt.

*Execute these command in sequence:

bootrec /fixmbr
bootrec /fixboot
bootrec /ScanOs
bootrec /rebuildBcd

*Close Command Prompt and reboot.

A: I had a similar problem trying to end a dual-boot and go back to just Windows. Not sure how specific this is to how I originally installed the dual-boot, but I was able to reset to use the Windows boot loader by accessing the BIOS menu during setup, then going to Boot > Boot Device Priority and resetting Boot Option #1 to Windows Boot Manager and disabling Boot Option #2.


text:
Q: Keyboard navigation across text and decorator nodes I'm building a template editor with lexical that uses custom decorator nodes to represent template fields (placeholders) following this example.

When changing the selection using the arrow keys, the selection gets stuck at the decorators. For example, when the cursor is just before a decorator (as in the image above) and I press Arrow Right, the RangeSelection changes into a NodeSelection for the decorator node. From that point, pressing arrow keys does not change the selection anymore.
Is is possible to configure decorator nodes so that they are skipped, i.e. the selection changes from the location before to the location after the decorator?
I'm using lexical@0.5.0.

A: here is the fix I used:
inside of your custom decorator node, use the isIsolated method and return true.
it's my understanding that when you select nodes, modify is invoked.
here is the block of code that you will be interested in:
    if ($isDecoratorNode(possibleNode) && !possibleNode.isIsolated()) {
      // Make it possible to move selection from range selection to
      // node selection on the node.
      if (collapse) {
        const nodeSelection = $createNodeSelection();
        nodeSelection.add(possibleNode.__key);
        $setSelection(nodeSelection);
        return;
      }

      const sibling = isBackward ? possibleNode.getPreviousSibling() : possibleNode.getNextSibling();

      if (!$isTextNode(sibling)) {
        const parent = possibleNode.getParentOrThrow();
        let offset;
        let elementKey;

        if ($isElementNode(sibling)) {
          elementKey = sibling.__key;
          offset = isBackward ? sibling.getChildrenSize() : 0;
        } else {
          offset = possibleNode.getIndexWithinParent();
          elementKey = parent.__key;

          if (!isBackward) {
            offset++;
          }
        }

        focus.set(elementKey, offset, 'element');

        if (collapse) {
          anchor.set(elementKey, offset, 'element');
        }

        return;
      } else {
        const siblingKey = sibling.__key;
        const offset = isBackward ? sibling.getTextContent().length : 0;
        focus.set(siblingKey, offset, 'text');

        if (collapse) {
          anchor.set(siblingKey, offset, 'text');
        }

        return;
      }
    }

by setting your decorator as isolated, you'd be able to select that node's siblings

A: I had a very similiar issue for anyone coming across this question. The only difference is, that I wanted the node to be selectable and not jump over the node. The issue of my selecton getting 'stuck' was still the same.
The funny part was that when using my exact same custom node in the playground example, I was able to get the correct keyboard behaviour. isIsolated was not giving me the behaviour I was hoping for either because it would just skip over my node.
After doing some digging, I found out that the issue was the PlainTextPlugin. I switched to the RichTextPlugin and got the correct keyboard navigation for decorator nodes.
The critical difference is in the KEY_ARROW_ handler. The RichTextPlugin handles node selections:
          if ($isNodeSelection(selection)) {
            // If selection is on a node, let's try and move selection
            // back to being a range selection.
            const nodes = selection.getNodes();
            if (nodes.length > 0) {
              event.preventDefault();
              nodes[0].selectPrevious();
              return true;
            }
          }


text:
Q: Came across weird loop behaviour I feel kinda dumb, but I couldn't find a solution, so I'm asking here. The purpose of my code is to fill 2D array 4x4 with random numbers in range from 0-255 and render them to a panel. Problem is, that I have two functions: RenderArray() and WriteToTextbox(). They both return same values from the array only if one of them reads from the array as array[y,x], instead of array[x,y]. I find this behaviour rather weird and I cannot simply think of the reason why. Here's the code:
    private bool newRequest;
    private bool hasGenerated;
    private int[,] array = new int[4, 4];
    private static Random random = new Random();

    private void btnRandom_Click(object sender, EventArgs e)
    {
        if (!HasGenerated)
        {
            HasGenerated = true;
        }

        NewRequest = true;
        pnlRandom.Refresh();
    }

    public bool NewRequest
    {
        get { return newRequest; }
        set { newRequest = value; }
    }

    public bool HasGenerated
    {
        get { return hasGenerated; }
        set { hasGenerated = value; }
    }

    public static Random GetRandom
    {
        get { return random; }
    }

    private void pnlRandom_Paint(object sender, PaintEventArgs e)
    {
        if (!HasGenerated)
        {
            return;
        }

        if (NewRequest)
        {
            for (int x = 0; x < 4; x++)
            {
                for (int y = 0; y < 4; y++)
                {
                    array[x, y] = GetRandom.Next(0, 256);
                }
            }

            NewRequest = false;
        }

        RenderArray(e);
        WriteToTextbox();
    }

    private void RenderArray(PaintEventArgs e)
    {
        Graphics g = e.Graphics;

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 4; y++)
            {
                //int color = array[y, x]; If I write it like that
                //they will return same values.
                int color = array[x, y];
                SolidBrush brush = new SolidBrush(Color.FromArgb(color, color, color));
                Rectangle rect = new Rectangle(x * 64, y * 64, 64, 64);

                g.FillRectangle(brush, rect);
            }
        }
    }

    private void WriteToTextbox()
    {
        txtRandom.Clear();

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 4; y++)
            {
                int length = array[x, y].ToString().Length;
                txtRandom.Text += array[x, y].ToString().PadLeft(3 * 4 - length + 3 * 4 % 3);
            }

            txtRandom.Text += "\r\n";
        }
    }

A: You're iterating the loops in the wrong order.
When drawing the array, it doesn't matter whether you loop through x or y first; either way, each cell will be drawn at the coordinates you pass to FillRectangle().
When printing the array to a string, you write the characters in the order that you iterate them.
By looping through x, then y, you're looping through every column (x) in the array, then looping throw the cells vertically down that column (y).
Therefore, you're printing the array transposed.


text:
Q: How to get currently selected choice from CharField in Django? I'm trying to get the currently selected choice from the CharField and use it in str method like this:
class Foo(models.Model):
    measurement_value = models.FloatField(max_length=200)

    CHOICES = (('a', 'Alpha'), ('b', 'Beta'))
    choice = models.CharField(max_length=5, choices=CHOICES, default='a')

    def __str__(self):
        """String representation for the foo object."""
        return str(self.measurement_value) + " " + self.choice

So for example, if I'd like to add object foo with measurement 10.5 and choice 'a' (Alpha), str would return this: "10.5 Alpha"
Currently, the code that I provided returns this: "10.5 a".

A: You can get the human readable choice name by using instance method get_{}_display
your example
 def __str__(self):
     return str(self.measurement_value) + " " + self.get_choices_display()


text:
Q: Not able to pass value between forms ( maybe because of the Div element in form) in ASP I am not able to pass value between forms ( maybe because of the Div element in form) in ASP
My first file's code:
<form method=POST>

<SELECT id=text2 name=text2  disabled style="WIDTH: 450px">
<option value="1" selected>One</option>
</select>

<input type="submit" Value="Submit Button" onclick="this.form.action='GS_Ajax_test_1.asp'">

</form>

2nd file's code:

<%
Room_Number= Request.Form("text2")
Response.write Room_Number+"hi"
%>

I ma not able to access value in text2...
Any help?

A: Take the disabled off your select item.
It'll work.


text:
Q: plot a daily profile with python I want to make a daily profile plot: hour vs concentrations. I'm using matplotlib and datetime module.
When I write:
import datetime
from pylab import *
b = [datetime.time(12,0), datetime.time(13,0)]
c = [4,5]
plot(b,c)
show()

... it doesn't work.
I have to use datetime objects instead of time objects to be able to make the plot:
a = [datetime.datetime(2005,5,10,12), datetime.datetime(2005,5,10,13)]
c = [4,5]
plot(a,c)
show()

But I really would like to be able to make the plot using time objects instead of datetime...
Any ideas?

A: Have a look at the matplotlib documentation here:
http://matplotlib.sourceforge.net/api/dates_api.html
The issue is that matplotlib only knows how to convert the datetime object to a float and it doesn't look there is the same support for datetime.time
Edit:
One possible solution is to just get a default date ('today') and then combine it with the specific time you want if you don't care about the date:
import datetime
from pylab import *
d = datetime.date.today()
tt = [datetime.time(12,0), datetime.time(13,0)]
b = []
for t in tt:
    b.append(datetime.datetime.combine(d,t))
c = [4,5]
plot(b,c)
show()

A: Time returns the amount of seconds.
>>>print time.time()
1297696979.78

>>>print date.fromtimestamp(today)
2011-02-14

Today being a variable I set equal to the current time.time(). I'm not quite sure why you're entering variables into the time() function.


text:
Q: dwm doesn't load fontawesome I want to set up icons for my tags in dwm. I have downloaded the ttf-font-awesome package with sudo pacman -S ttf-font-awesome and I changed this line in my config.h of dwm:
static const char *fonts[] = { "FontAwesome:size=16", "consolas:size=16" };

But it still doesn't work. Some icons show up correctly, while others show up slightly or even completely different. I copied the unicode glyph from fontawesome.com and added it to my *tags array in config.h. Did I miss something? Any help is greatly appreciated!

A: The solution was quite simple. I had a Nerd font loaded also, and this font caused the icons to be loaded differently from what I expected. I removed the ner font and everything worked just fine.


text:
Q: I can't find how to get text with selenium python i try to get the content of
0 Jours restants

(which is the expiration date of the warranty)
but i don't know how to get it (i need to print it in a file)
my code
def scrapper_lenovo(file, line):
   CHROME_PATH = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
   CHROMEDRIVER_PATH = 'C:\webdriver\chromedriver'
   WINDOW_SIZE = "1920,1080"
   chrome_options = Options()
   chrome_options.add_argument("--headless")
   chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
   chrome_options.binary_location = CHROME_PATH
   d = driver.Chrome(executable_path=CHROMEDRIVER_PATH,
                          chrome_options=chrome_options)
   d.get("https://pcsupport.lenovo.com/fr/fr/warrantylookup")
   search_bar = d.find_element_by_xpath('//*[@id="input_sn"]')
   search_bar.send_keys(line[19])
   search_bar.send_keys(Keys.RETURN)
   time.sleep(4)
   try:
      warrant = d.find_element_by_xpath('//*[@id="W-Warranties"]/section/div/div/div[1]/div[1]/div[1]/p[1]/span')
      file.write(warrant)
   except:
      print ("test")
      pass
   if ("In Warranty" not in d.page_source):
    file.write(line[3])
    file.write("\n")
   d.close()

i tried as you can see to print the content of 'warrant' and i couldn't find any function allowing it (i saw some using .text(), .gettext() but for whatever reasons i couldn't get them to work).

A: You could try explicitly matching the required tag, the relevant XPath expression would be:
//span[@class='noactive']

I would also recommend getting of this time.sleep() function, it's some form of a performance anti-pattern, if you need to wait for presence/visibility/invisibility/absence of a certain element you should rather go for Explicit Wait
So remove these lines:
time.sleep(4)
warrant = d.find_element_by_xpath('//*[@id="W-Warranties"]/section/div/div/div[1]/div[1]/div[1]/p[1]/span')

and use this one instead:
warrant = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.XPATH, "//span[@class='noactive']")))

More information: How to use Selenium to test web applications using AJAX technology


text:
Q: Can I use spring liferay for mobile web development Can I use spring liferay for mobile web development?
This is very basic question but I tried on google but I can't find any tutorial on this. Can anyone suggest anything on this.

A: Yes you can use it I think, since Spring is a server side java framework and for mobile web-development I don't think you need to do anything special apart from customizing the look-and-feel of the page which can be done through themes in liferay.
Starting from Liferay 6.1 you can even define Mobile Device Rules.
For a quick demo of this you can go to Liferay site, and try to change the window size of the browser and then see how the page changes. Even you can try to view this site in a mobile phone.
Hope this helps.


text:
Q: What is the difference between Association and Aggregation? I am very confused about the differences between Associations and Aggregations as both are almost the same, and both objects in the relation can exist without the other.
There is a post on stack overflow trying to explain this
Association - I have a relationship with an object.  Foo uses Bar
public class Foo {
    private Bar bar;
};

Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.
public class Foo {
    private Bar bar;
    Foo(Bar bar) {
       this.bar = bar;
    }
}

source {https://stackoverflow.com/a/10394722}
Both looks almost identical to me, can someone explain when is a relation an association and when is it an aggregation.


text:
Q: Вытащить видео с youtube по id-автора Добрый день.
Кто-то сталкивался с youtube api?
Не поделитесь ссылкой на документацию/примеры как можно вытащить список видео определенного пользователя по id этого пользователя?
A: Как я понял: id автора = его логин.
Я решил это таким образом:
var author_name='stevesattlerfilms';   //будем вытягивать видео этого автора

$.ajax({
    url: 'http://gdata.youtube.com/feeds/api/videos?author='+author_name+'&max-results=10',      //максимум 10 штук
    type: 'get',
    success: function(callback){
        var Events=$(callback).find('entry');   //ответ возращает нам xml документ, так что парсим его по тегу entry

        $(Events).each(function(){

            var link=$(this).find('id').text();  //в каждом теге находим тег id, в нем вшит адрес на видео
            console.log(link);

        })
    }
})


text:
Q: How to find parameter values that minimises the total deviation of a function f(x) from a substituted linear function? Suppose I have a continuous differentiable function $f:\mathbb{R}\rightarrow\mathbb{R}^+$ such that $\int_{\mathbb{R}}f(x)dx<\infty$.
Let's assume the function to be convex and increasing.
Now, for an $x_1$ and $x_2$, I would like to substitute $f(x)$ with a linear function $l(x)=\alpha+\beta x$ such that the area under the curve for the interval $(x_1,x_2]$ remains the same. Mathematically,
$$\int_{x_1}^{x_2}f(x)dx=\int_{x_1}^{x_2}l(x)dx$$

Now, how can I find the values of $\alpha$ and $\beta$ that would minimise the total deviation of $l(x)$ form $f(x)$?
In other words, I would like to find $\alpha$ and $\beta$ that minimises $$\int_{x_1}^{x_2}\{f(x)-l(x)\}^2dx,$$
the area shaded purple in image 3.

A: Hint: Before expanding the integral, find the derivatives of the square error ($\epsilon$) w.r.t $\alpha$ and $\beta$. Then,expand the integral and set to zero. Finally, resolve the obtained system.
Solution: First, lets define $\epsilon$ as follow:
$$
\epsilon = \int_{x_1}^{x_2}\left(f(x)-l(x)\right)^2dx = \int_{x_1}^{x_2}\left(f(x)-(\alpha+\beta x)\right)^2dx
$$
Derivate it w.r.t $\alpha$ and $\beta$:
$$
\frac{\partial\epsilon}{\partial \alpha} = \int_{x_1}^{x_2}2 \left(f(x)-(\alpha+\beta x)\right)(-1)dx = 0 \Rightarrow \int_{x_1}^{x_2} f(x) dx = \alpha \left(x_2 - x_1 \right) + \beta \left(x_2^2 - x_1^2\right)
$$
$$
\frac{\partial\epsilon}{\partial \beta} = \int_{x_1}^{x_2}2 \left(f(x)-(\alpha+\beta x)\right)(-x)dx = 0 \Rightarrow \int_{x_1}^{x_2} xf(x) dx = \frac{\alpha}{2} \left(x_2^2 - x_1^2 \right) + \frac{\beta}{3} \left(x_2^3 - x_1^3\right)
$$
Finllay you can resolve this system and get the desired $\alpha$ and $\beta$.


text:
Q: directional derivative of an expression let $f:\mathbb{R}^n \times\mathbb{R}^m \rightarrow \mathbb{R}^m$ and $f(x,y)=0$ where $x\in \mathbb{R}^n $ and $y\in \mathbb{R}^m$. then suppose that we can write $y$ as a function of $x$ like $g(x)$ (in a small interval)
so $h(x)=f(x,g(x))=0$.
Now I see a statement in this book thatI can't understandt:
$D_xh = 0 $
$Dh = D_xf + D_yf.D_xg = 0$
my first question: what is the meaning of the first line $D_xh = 0 $ (what is the meaning of $D_xh$)  and how he concluded it?
second question: how he concluded the second statement $Dh = D_xf + D_yf.D_xg = 0$ ?

A: First question
$D_x h = 0$ means that the partial derivative $\frac{\partial}{\partial x}$ of $h$ is always vanishing. This is the consequence that $h$ is supposed to be always vanishing.
By the way $h$ is a function of $x$ only so the partial derivative is equal to the partial derivative.
Second question
The (Fréchet) derivative of a map $(x,y) \mapsto f(x,y)$ is
$$Df.(k,l) = D_x f.k+D_y f.l$$
You then get the formula $Dh = D_xf + D_yf.D_xg = 0$ using the chain rule for derivatives.

A: Hint.
The directional derivative can be taken as
$$
Df_u=<\nabla f, \vec u >
$$
Now $\vec u$ is tangent to $f(x,y)=0$ because is taken over $(x,g(x))$ and $\nabla f$ is normal to the tangent plane to $f(x,y)=0$ so obviously
$$
<\nabla f, \vec u > = 0
$$


text:
Q: JNI Call to MIP SDK gives error - Can't open database, check folder permissions: mip_data\mip\mip.policies.sqlite3 We have application in java where Java security is enabled. We need to fetch the tags from AIP cloud. We could get the access token using msal4j java library.
There is no java library provided by MS for MIP so we have implemented native dll to fetch the AIP Labels. This dll is integrated with our web application. Application does the JNI calls to the native library to fetch the labels.
I think MIP SDK creates the sqlite database to cache the Labels. So it creats the sqlite file on the local disk internally. But as the security is enabled I am getting access denied error for the MIP dll.
"Can't open database, check folder permissions: mip_data\mip\mip.policies.sqlite3"
I have tried giving below permissions in manager.policy but not working
grant codeBase "../Protect/lib/native/*" {

permission java.io.FilePermission "../Protect/bin/mip_data/mip/mip.policies.sqlite3", "read,write,delete";
permission java.io.FilePermission "../Protect/bin/mip_data/mip", "read,write,delete";
permission java.io.FilePermission "../Protect/bin/mip_data", "read,write,delete";
permission java.io.FilePermission "../Protect/bin", "read,write,delete";
};

grant codeBase "../Protect/lib/native/-" {

permission java.io.FilePermission "../Protect/bin/mip_data/mip/mip.policies.sqlite3", "read,write,delete";
permission java.io.FilePermission "../Protect/bin/mip_data/mip", "read,write,delete";
permission java.io.FilePermission "../Protect/bin/mip_data", "read,write,delete";
permission java.io.FilePermission "../Protect/bin", "read,write,delete";
};

grant codeBase "../Protect/lib/native/-" {

permission java.io.FilePermission "../Protect/bin/mip_data/mip/mip.policies.sqlite3", "read,write,delete";
permission java.io.FilePermission "../Protect/bin/mip_data/mip", "read,write,delete";
permission java.io.FilePermission "../Protect/bin/mip_data", "read,write,delete";
permission java.io.FilePermission "../Protect/bin", "read,write,delete";
};

grant codeBase "file:${catalina.home}/webapps/ProtectManager/WEB-INF/lib/*"
{
permission java.io.FilePermission "../Protect/bin/mip_data/mip/mip.policies.sqlite3", "read,write,delete";
permission java.io.FilePermission "../Protect/bin/mip_data/mip", "read,write,delete";
permission java.io.FilePermission "../Protect/bin/mip_data", "read,write,delete";
permission java.io.FilePermission "../Protect/bin", "read,write,delete";

}

How does the Java security works in case of JNI? Does it inherits all the permissions to native calls?

A: Which OS are you using? I can't answer your Java question, but we do have a private preview of the MIP SDK Java Wrapper on Windows. We plan to expand to a few Linux distros in the near future, but are collecting feedback on the Windows version, first.
If you're interested, I'm happy to provide a build.


text:
Q: How to retrieve SQL Server RAISERROR (or PRINT) messages? I'm trying to get the warning message from SQL Server's Raiserror in python with PyODBC.
The severity is low on purpose, because it acts as a printing functionality, but it doesn't have to wait until the query is done before printing.
The output I expect would be something like:
*Test Message*
|col1|
|:-|
|1|

Here's my code:
import pyodbc

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=ECH-DWPROD02;DATABASE=Test;Trusted_Connection=yes;')
cursor = conn.cursor()

cursor.execute("SET NOCOUNT ON; RAISERROR('Test Message',0,1) WITH NOWAIT; select 1 as col1")
cursor.fetchall()

A: Cursor.messages is a fairly recent addition to pyodbc (v4.0.31 – July 2021). It allows us to retrieve messages emitted from SQL Server stored procedures et al. via PRINT and RAISERROR.
Note that such messages constitute a "result" from the server so if they are returned then one must call .nextset() to retrieve additional results, otherwise a "Previous SQL was not a query." error will occur:
crsr.execute("""\
SET NOCOUNT ON;
RAISERROR('Test Message',0,1) WITH NOWAIT;
select 1 as col1
""")
print(crsr.messages)
# [('[01000] (50000)', '[Microsoft][ODBC SQL Server Driver][SQL Server]Test Message')]
crsr.nextset()  # required before .fetchall()
print(crsr.fetchall())
# [(1, )]


text:
Q: How to create a header for perl? I am new to perl. I wish to create a perl program which sends request to a website and downloads the data. I read HTTP::Headers and HTTP::Request.
I wish to use HTTP::Request->new( 'POST', $URL, $Header, $PostData ).
My question is how can I determine header values and post data.
Thank you

A: I was creating a similar script sometime back. I think first you should capture the http request using the browser.
1) Add "HTTPFox" to firefox. It is very helpful.
2) Open HttpFox in a new window. Press start button. This will start capturing packets.
3) Open the website and follow the procedures to download the data.
Please ask if anything is not clear.