text:
Q: Async write to PassThrough stream I need to read a wav file into memory, and pipe it repeatedly to node-speaker. The following code attempts to do this, but the sound only plays once. Why is this?
const fs = require('fs')
const { PassThrough } = require('stream')
const { Reader } = require('wav')
const Speaker = require('speaker')

fs.readFile('sample.wav', (e, buffer) => {

  const speaker = new Speaker()
  const reader = new Reader()
  const pass = new PassThrough()

  reader.pipe(speaker)
  pass.pipe(reader)

  setInterval(() => {
    pass.write(buffer)
  }, 1000)

})

Additionally, if two play events happen in quick succession, I'd like to cut-off the original as soon as the new event occurs.
UPDATE
I've made some progress with this. The following code now plays the sample repeatedly, but every time it writes speaker error: write() failed: 2556 and the sample is cut short.
const fs = require('fs')
const { Reader } = require('wav')
const Speaker = require('speaker')

const chunks = []
const reader = new Reader()
const speaker = new Speaker()
const file = fs.createReadStream('sample.wav')

file.pipe(reader)
reader.on('data', c => chunks.push(c))

speaker.on('error', e => console.log(`speaker error: ${e.message}`))
reader.on('error', e => console.log(`reader error: ${e.message}`))

reader.on('end', () => {

  const buffer = Buffer.concat(chunks)

  setInterval(() => {
    console.log('writing')
    speaker.write(buffer)
  }, 1000)

})


text:
Q: How to access subcclass attributes in super class methods, without passing them in How does one access a derived class'es property (static variable in other languages), in its base classes method?
I.e.
class Base:
    @classmethod
    def get_list(cls):
        return [1, 2, cls.x]

class Derived(Base):
    x = 3
    foo = Base.get_list()

Derived.foo # Hope to have it set to [1, 2, 3]

I wish to not pass x directly to the base class, i.e. foo = Base.get_list(x) because I have a lot of methods to be called with the same variables.
EDIT
The comments have asked for context. I tried to make a minimum reproducible example to spare you guys the details.
Here's the full context: So its actually to do with Django Admin.
I have a abstract model. Then I have various admin interfaces for the various concrete implementation of the abstract model. As you can guess I created an abstract admin model to handle the common logic. A part of handling the common admin logic, e.g. generating properties on the derived admin model.
So for example the list display, here's the logic to create the list display:
class FactAdmin(admin.ModelAdmin):
    @classmethod
    def build_list_display(cls, *custom):
        return (
            'created_utc',
            *custom,
            'foo__bar__abbreviation',
            'foo__baz__name',
            'foo__caz__name',
            'foo__daz__description',
            'foo__eaz__code',
        )

@admin.register(FooEntry)
class FoopEntryAdmin(FactAdmin):
    fieldsets = FactAdmin.build_list_display('cannon_ball', 'pogo_stick')

So in the base admin class, it keeps reusing a list of custom fields, custom models, and other things. So instead of passing them in each time, for each property, it seemed more DRY to set them as static attributes.  Hence I wished to set them as static member fields on the derived class, and access them in the base class.

A: You shouldn't be using class attributes and methods.  You should be defining classes that you create instances of, and use instance methods and attributes, so that normal inheritance works the way it was intended to be used in the language.
Then you need to take advantage of the fact that instance methods can be overridden by subclasses.  Here, to let the parent class get at the child class's x, you define a get_x method in the parent class that you expect to have overridden in the child class.  That's how the child class's x gets used by the parent without it ever being passed to it.
Here's an example:
class Base:
    def set_foo(self):
        return [1, 2, self.get_x()]

    def get_x(self):
        return 0

class Sub(Base):

    def __init__(self):
        self.x = 3
        self.foo = super().set_foo()

    def get_x(self):
        return self.x

print(Sub().foo)

Result:
[1, 2, 3]

A: Accessing subclass attributes in a superclass classmethod called on the subclass isn't a problem. This works as expected:
class Base:
    @classmethod
    def get_list(cls):
        return [1, 2, cls.x]

class Derived(Base):
    x = 3

assert Derived.get_list() == [1, 2, 3]

However, you can't easily call that classmethod right in the subclass's class body, as at that time, the class object for Derived and indeed the name Derived don't exist yet. (You could call it in methods, classmethods and staticmathods, because their body is evaluated when they are invoked, and not already when they are defined. But that doesn't help here.) And if called on Base, it obviously lacks x. (And being a Python classmethod, get_list has to be explicitly called on something. We can't just make an unqualified call as in Java.)
So
class Derived(Base):
    x = 3
    foo = get_list()

results in NameError: name 'get_list' is not defined,
class Derived(Base):
    x = 3
    foo = Base.get_list()

results in AttributeError: type object 'Base' has no attribute 'x' and
class Derived(Base):
    x = 3
    foo = Derived.get_list()

results in NameError: name 'Derived' is not defined.
But all is not lost. Let's not forget that Python allows us to create and set class attributes from outside the class. So this works:
class Base:
    @classmethod
    def get_list(cls):
        return [1, 2, cls.x]

class Derived(Base):
    x = 3

Derived.foo = Derived.get_list()

assert Derived.foo == [1, 2, 3]

A: If you want super to access the property of a derived class, it's probably because this property is shared by all derived subclasses (you don't make any check on the derived class type anyway). In such case, the most logical thing to do is to implement the property in super instead, and that solves the problem :
class Base:
    x = 3
    @classmethod
    def get_foo():
        return [1, 2, self.x]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can SQLite be used when a program was written with mySQL? i'm copying a series of examples from  Robin Nixon's Learning PHP, javascript and MySql
http://www.amazon.com/Learning-MySQL-JavaScript-Step-Step/dp/0596157134/ref=pd_sim_b_3
which ultimatly unite to form a basic social networking site. All of these examples are written in php, javscript and mySql. At some point I would like to use SQLite instead of mySql. My question is, will i be able to finish the site in mysql and then simply began using SQLite, or will other steps be be needed, such as rewriting the whole thing?

A: First, unless you are using an abstraction layer, you will need to switch to a different API for using the completely different database.
Next, you are probably using some MySQL specific functions that will need to be worked around.
Finally, work around anything not implemented in SQLite.
I'd really be curious to know why you want want to do this anyway.  Do you understand that SQLite databases really aren't meant for a lot of concurrent connections, and aren't generally considered appropriate for websites of any decently sized scale?


text:
Q: Rigid Uniformization vs Grothendieck's Local Monodromy Theory I've noticed that some interesting results about abelian varieties can each be proven using one of two ways: the theory of rigid uniformization of abelian varieties or Grothendieck's local monodromy theory of SGA 7 1. I'm therefore wondering about possible interconnections between the two.
Detailed Motivation:
The first example of a result referred to above is the fact that CM abelian varieties have (potentially) good reduction everywhere. The proof using rigid uniformization is discussed in Silverman, Advanced Topics in the Arithmetic of Elliptic Curves (ATAoEC) in Chapter V. ATAoEC also gives a proof in Chapter II Section 6 using local class field theory, Neron-Ogg-Shafarevich, and the fact that a pro-$p$ group can only map trivially into a pro-$\ell$ group. I consider this latter proof to be part of Grothendieck's local monodromy theory, as one uses a similar method to prove the local monodromy theorem (at least, as demonstrated to me in Nicholas Katz's course at Princeton this fall; the original should be in the elusive SGA 7 1 Exposé III).
The next example is the following. SGA 7 1 Exposé IX proves that if $A/K$ has semistable reduction over a local field $K$ with inertia group $I$ with dimension $g$ and toric dimension $\mu$, then $T_\ell(A)^f := T_\ell(A)^I$ has rank $2g-\mu$, and $I$ acts trivially on the quotient as well. Furthermore, it has a complement under the Weil pairing (for a fixed polarisation), denoted $T_\ell(A)^t$, of rank $\mu$. See 2.2.5, 2.4, 2.5.4, and 3.5 of the Exposé notes.
Of course, one can prove the same result using rigid uniformization, where $T_\ell(A)^t$ corresponds to the $\ell^n$th roots of unity in $\bar{K}^*$. See Ribet, Galois Action on Division Points of Abelian Varieties with Real Multiplications, Section III, or these notes by Mihran Papikian.
Specific Question: Why do these two theories seem to prove the same results?
This would make sense if I saw similar arguments being used to develop both theories. But I don't see how analyzing the inertia using local class field theory and then looking at profinite groups is the same as writing down $p$-adic power series. While they both have a $p$-adic and $\ell$-adic "flavor," they seem to be very different proofs.
However, please tell me if I'm wrong - could it be that one can trace the arguments developing each theory to find a common thread?
More specifically, can one prove in general that if one can prove a result with one theory, then one can do it with the other? Is one theory strictly stronger than the other? Is there a common generalization?


text:
Q: ajaxForm is not running when used in jquery dialog why is that ajaxForm is not running in jQuery Dialog modal confirmation whenever it is included in a "Delete Item" button.
Here is my jquery dialog:

      <form id="deleteDialogForPartylistForm" action="mEdit/editPartylist/storeDataToDb/deleteData.php">

 will be permanently deleted and cannot be recovered. Are you sure?

        <input type="hidden" id="deleteDialogForPartylistHiddenId" name="deleteDialogForPartylistHiddenId">
      </form>

Here is my script
$(function(){
$( "#deleteDialogForPartylist" ).dialog({
  autoOpen: false,
  resizable: false,
  height:225,
  hide: 'fade',
  modal: true,
  buttons: {
    Cancel: function() {
      $("#deleteDialogForPartylist").dialog('close');
    },
    "Delete item": function() {
      $('#deleteDialogForPartylistForm').ajaxForm({
            target: '#partyListInAddCandidate',
            type: "post",
            success: function(){
                alert("Success");
                $("#deleteDialogForPartylist").dialog('close');
            }
        });
    }
  }
});
});

A: .ajaxForm() does not submit the form as stated in the documentation of the plugin (http://malsup.com/jquery/form/#api)
In your case you should use .ajaxSubmit() instead, which will instantly submit your form on button-click as already suggested by charlietfl's comment


text:
Q: When are views automatically transformed based on their superview? I asked a similar question before, but now I have done some more work on it and have a more refined question.
I have the following code in my applicationDidFinishLaunching:, creating 3 views and adding them as subviews of the window:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
    GLViewController* controller = [[GLViewController alloc] init];
    self.glViewController = controller;
    [controller release];

    glView = [[GLView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    glView.controller = glViewController;
    [glView stopAnimation];
    [window addSubview:glView];

    invisibleView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    invisibleView.alpha = 1.0;
    invisibleView.tag = 2;
    // By the definition of UIViewAutoresizing, 0x3F corresponds to resizing in every direction.
    invisibleView.autoresizingMask = 0x3F;
    obstaclesViewController = [[ObstaclesViewController alloc] init];
    obstaclesViewController.view = invisibleView;
    [window addSubview:invisibleView];

    viewController = [[GazeIntroViewController alloc] initWithNibName:@"GazeIntroViewController" bundle:[NSBundle mainBundle]];
    [viewController.view setFrame:[[UIScreen mainScreen] bounds]];
    [window addSubview:viewController.view];
    [window bringSubviewToFront:viewController.view];

    [window makeKeyAndVisible];

    NSLog(@"window: %@", [window description]);
    NSLog(@"window subviews: %@", [[window subviews] description]);
}

The app is supposed to work only in landscape, so I have set it (in the plist) to launch in landscape, which it does. But the last added subview (GazeIntroViewController) appears rotated by 90 deg. (as if the device was still in portrait).
What's really baffling me, is that the first and second view seem ok. If I take out the middle block where I add the invisibleView, then GazeIntroViewController will also come out right. From the NSLogs, I can see that the views that come out right have a transform automatically applied ([0, 1, -1, 0, 0, 0]), but I don't understand why this transform is applied to some views and not others, when their parent is the window for all of them.
Output when invisibleView is not added:
2011-07-31 21:00:51.271 GazeDemo[53515:207] window: <UIWindow: 0xa713ab0; frame = (0 0; 768 1024); autoresize = RM+BM; layer = <CALayer: 0xa713b90>>
2011-07-31 21:00:51.277 GazeDemo[53515:207] window subviews: (
"<GLView: 0x68bc350; frame = (0 0; 768 1024); layer = <CAEAGLLayer: 0x68bc4e0>>",
"<UIView: 0x68c3ce0; frame = (0 0; 748 1024); transform = [0, 1, -1, 0, 0, 0]; autoresize = LM+W+RM+TM+H+BM; layer = <CALayer: 0x68c2150>>"
)

Output when invisibleView is added:
2011-07-31 21:11:05.489 GazeDemo[53710:207] window: <UIWindow: 0x689d4d0; frame = (0 0; 768 1024); autoresize = RM+BM; layer = <CALayer: 0x689d5b0>>
2011-07-31 21:11:05.496 GazeDemo[53710:207] window subviews: (
"<GLView: 0x689cf50; frame = (0 0; 768 1024); layer = <CAEAGLLayer: 0x689dcb0>>",
"<UIView: 0x68a05f0; frame = (0 0; 748 1024); transform = [0, 1, -1, 0, 0, 0]; autoresize = LM+W+RM+TM+H+BM; tag = 2; layer = <CALayer: 0x68a06c0>>",
"<UIView: 0x6b484b0; frame = (0 0; 768 1024); autoresize = LM+W+RM+TM+H+BM; layer = <CALayer: 0x6b4bad0>>"
)

A: All apps starts with portrait mode only and then in UIViewController's autoRotate methode it turns to landscape.
so, we cant change orientation of MainWindow.xib's orientation. thats why if you will add a view as subView of main window it will always in portrait mode and you think that it is rotated at 90 degree.
try to add sub view on rootViewController.view like:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Some code
     [self.window.rootViewController.view addSubview:YourView];
    //some code
}

and if you are using navigation controller then use this:;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Some code
     [self.navigationController.topViewController.view addSubview:YourView];
    //some code
}


text:
Q: disable other button in a buttonGroup when clicks one button I have an array of data
const projectTypeValues = [
{ name: 'Hour', value: 'hour'},
{ name: 'Day', value: 'day'},
{ name: 'Session', value: 'session'},
{ name: 'project', value: 'project'}]

From there I am showing the buttons in a material ui buttonGroup through an loop.
{projectTypeValues.map(element=>
          <Button variant="contained" color="primary">{element.name}</Button>
        )}

how do i implement an onClick function that will make the other buttons in the loop disable except the one that was clicked?

A: You can manage it by storing a selected button value in state and checking on disabled time. You can use the button disabled attribute for disabling. You can store unique value for matching button disable like name or id.
If we use name for selecting the button so we need to check like this way.
disabled={currentSelect && currentSelect !== element.name}

Example:

const projectTypeValues = [
  { name: "Hour", value: "hour" },
  { name: "Day", value: "day" },
  { name: "Session", value: "session" },
  { name: "project", value: "project" }
];
const App = () => {
  const [currentSelect, setSelect] = React.useState(null);
  console.log(currentSelect);
  return (

      {projectTypeValues.map((element) => (

          <button
            disabled={currentSelect && currentSelect !== element.name}
            variant="contained"
            color="primary"
            onClick={() => setSelect(element.name)}
          >
            {element.name}
          </button>

      ))}

  );
};

ReactDOM.render(<App />, document.getElementById("root"));

A: import React from "react";
function App() {
    const [disable, setDisable] = React.useState(false);

 return (
        <button variant="contained" color="primary"
         disabled={disable} onClick={() =>
         setDisable(true)}>
         {element.name}
        </button>
         );
 }

A: You should define a state for the selected button, something like this:
const [selectedButtonIndex, setSelectedButtonIndex] = useState(-1)
then you need to use map and get the index and disable or other buttons:
 {projectTypeValues.map((element, index)=>
          <Button variant="contained" disabled={index !== -1 && index !== selectedButtonIndex} onClick={() => setSelectedButtonIndex(index)} color="primary">{element.name</Button>
 )}

Note: I started with -1 as initial value, as this enables all buttons initially and then it locks your choice. You could use another state to signal the fact that a choice has been made.


text:
Q: How to dynamically generate XML file for RSS Feed? I want to create a RSS Feed generator. The generator is supposed to read data from my database and generate RSS feeds for them. I want to write a script that would automatically generate the xml file for validation.
So if a typical xml file for RSS feed looks like this:
  <item>
  <title>Entry Title</title>
  <link>Link to the entry</link>
  <guid>http://example.com/item/123</guid>
  <pubDate>Sat, 9 Jan 2010 16:23:41 GMT</pubDate>
  <description>[CDATA[ This is the description. ]]</description>
  </item>

I want the script to replace automatically the field between the <item> and the </item> tag.
Similarly for all the tags. The value for the tags will be fetched from the database. So I will query for it. My app has been designed in Django.
I am looking for suggestions as to how to do this in python. I am also open to any other alternatives if my idea is vague.

A: What have you tried so far?
A very basic approach would be to use the Python DB API to query the database and perform some simple formatting using str.format (I type directly in SO -- so beware of typos):
>>> RSS_HEADER = """
<whatever><you><need>
"""
>>> RSS_FOOTER = """
</need></you></whatever>
"""

>>> RSS_ITEM_TEMPLATE = """
<item>
    <title>{0}</title>
    <link>{1}</link>
</item>
"""

>>> print RSS_HEADER

>>> for row in c.execute('SELECT title, link FROM MyThings ORDER BY TheDate'):
        print RSS_ITEM_TEMPLATE.format(*row)

>>> print RSS_FOOTER

A: Since this is python. Its good to be using PyRSS2Gen. Its easy to use and generates the xml really nicely. https://pypi.python.org/pypi/PyRSS2Gen

A: This rough code uses a very useful library called BeautifulSoup. It serves as a parser for HTML/XML markup languages providing a python object model. It can be used to extract/change information from XML or create XML by building up the object model.
This code below works by changing XML tags from a the template on pastebin. It does this by copying the template "item" tag, clearing its child tags and filling them with the suitable dictionary entries which will be presumably sourced from a database.
# Import System libraries
from copy import copy
from copy import deepcopy

# Import Custom libraries
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, Tag, NavigableString, CData

def gen_xml(record):

    description_blank_str = \
    '''
    <item>
    <title>Entry Title</title>
    <link>Link to the entry</link>
    <guid>http://example.com/item/123</guid>
    <pubDate>Sat, 9 Jan 2010 16:23:41 GMT</pubDate>
    <description>[CDATA[ This is the description. ]]</description>
    </item>
    '''
    description_xml_tag = BeautifulStoneSoup(description_blank_str)

    key_pair_locations = \
    [
        ("title", lambda x: x.name == u"title"),
        ("link", lambda x: x.name == u"link"),
        ("guid", lambda x: x.name == u"guid"),
        ("pubDate", lambda x: x.name == u"pubdate"),
        ("description", lambda x: x.name == u"description")
    ]

    tmp_description_tag_handle = deepcopy(description_xml_tag)

    for (key, location) in key_pair_locations:
        search_list = tmp_description_tag_handle.findAll(location)
        if(not search_list):
            continue
        tag_handle = search_list[0]
        tag_handle.clear()
        if(key == "description"):
            tag_handle.insert(0, CData(record[key]))
        else:
            tag_handle.insert(0, record[key])

    return tmp_description_tag_handle

test_dict = \
{
    "title" : "TEST",
    "link" : "TEST",
    "guid" : "TEST",
    "pubDate" : "TEST",
    "description" : "TEST"
}
print gen_xml(test_dict)


text:
Q: How to convert a dictionary into a list of its keys sorted by its values? I want to get a list of keys sorted by its values and in case of any ties, sorted alphabetically. I'm able to sort by values. In case of ties, I'm facing issues.
for dictionary:
aDict = {'a':8, 'one' : 1, 'two' : 1, 'three':2, 'c':6,'four':2,'five':1}

I've tried this:
sorted(aDict, key=aDict.get, reverse=True)

which gives me:
['a', 'c', 'three', 'four', 'two', 'five', 'one']

but I want:
['a', 'c', 'four', 'three', 'five', 'one', 'two']

A: You can use a keyfunction that returns a tuple. The values will be sorted by the second element of the tuple if the first elements are equal.
>>> aDict = {'a':8, 'one' : 1, 'two' : 1, 'three':2, 'c':6,'four':2,'five':1}
>>> sorted(aDict, key=lambda x: (-aDict[x], x))
['a', 'c', 'four', 'three', 'five', 'one', 'two']


text:
Q: I want multiple @ postconstruct methods in a class to be executed sequentially I hope they will be executed in the specified order, but the execution result is random,Use @order invalid,Each method is independent, temporarily unable to put it in one method

A: You can try calling these methods from a single @postconstruct method.

A: @Bean
public void test1(){
    System.out.println("bean A init");
}

@Bean
@DependsOn("test1")
public void test2(){
    System.out.println("test2");
}

@Bean
@DependsOn("test2")
public void test3(){
    System.out.println("test3");
}

You can use this scenario to control the loading order

A: Try this
public void method1() {
        System.out.println("method 1");
    }

    public void method2() {
        System.out.println("method 2");
    }

    public void method3() {
        System.out.println("method 3");
    }

    @PostConstruct
    public void postConstruct() {
        method1();
        method2();
        method3();
    }

result:
method 1
method 2
method 3


text:
Q: Javascript markers issue On my page i have bootstrap owl carousel and contact form. Problem is either contact form is working or carousel slider sliding pictures - one from both. I found out where the problem is but have no idea how to solve that. Below find my JS code. First is for owl carousel and rest two for my contact form.
<script>

$(document).ready(function() {

    var owl = $("#owl-hero");

    owl.owlCarousel({

        navigation: false, // Show next and prev buttons
        slideSpeed: 1,
        paginationSpeed: 400,
        singleItem: true,
        transitionStyle: "fade"

    });
    });

$(document).ready(function() {
    $("#contactForm").on("submit", function(event) {
        if (event.isDefaultPrevented()) {
        } else {
            event.preventDefault();
            submitForm();
        }
    });

});

function submitForm() {
    $.ajax({
        type: "POST",
        url: "mail.php",
        data: $("#contactForm").serialize(),
        success: function(text) {
            if (text == "success") {
                $("#msgSubmit" ).removeClass( "hidden" );
                setTimeout(function() {
                    $("#msgSubmit" ).addClass( "hidden");
                }, 6000);
            }
        },
        error : function() {
            /* You probably want to add an error message as well */
            $("#msgError" ).removeClass( "hidden" );
        }
    });
};

</script>

When i use as above - my contact form is working i mean mail i send and message is shown to user - but my carousel is not sliding pictures - it's stack.
If i want my carouse works i have to cut markers at the end like within below:
$(document).ready(function() {

    var owl = $("#owl-hero");

    owl.owlCarousel({

        navigation: false, // Show next and prev buttons
        slideSpeed: 1,
        paginationSpeed: 400,
        singleItem: true,
        transitionStyle: "fade"

    });

this one was cutted from the end:
});

and now carousel works but not contact form. I belive i still have some marker typo within my JS, can you take a look?
FURTHER DISCUSSION:
If i split carousel JS to separate  bracket - but without correctly enclosed mark - then everything seems to be working.. ;/ see below:
<script>

$(document).ready(function() {

    var owl = $("#owl-hero");

    owl.owlCarousel({

        navigation: false, // Show next and prev buttons
        slideSpeed: 1,
        paginationSpeed: 400,
        singleItem: true,
        transitionStyle: "fade"

    });
    }
</script>

    <script>
$(document).ready(function() {
    $("#contactForm").on("submit", function(event) {
        if (event.isDefaultPrevented()) {
        } else {
            event.preventDefault();
            submitForm();
        }
    });

});

function submitForm() {
    $.ajax({
        type: "POST",
        url: "mail.php",
        data: $("#contactForm").serialize(),
        success: function(text) {
            if (text == "success") {
                $("#msgSubmit" ).removeClass( "hidden" );
                setTimeout(function() {
                    $("#msgSubmit" ).addClass( "hidden");
                }, 6000);
            }
        },
        error : function() {
            /* You probably want to add an error message as well */
            $("#msgError" ).removeClass( "hidden" );
        }
    });
};

</script>

A: Try below code:

$(document).ready(function() {

    var owl = $("#owl-hero");

    owl.owlCarousel({

        navigation: false, // Show next and prev buttons
        slideSpeed: 1,
        paginationSpeed: 400,
        singleItem: true,
        transitionStyle: "fade"

    });

    $("#contactForm").on("submit", function(event) {
        if (event.isDefaultPrevented()) {
        } else {
            event.preventDefault();
            submitForm();
        }
    });

});

function submitForm() {
    $.ajax({
        type: "POST",
        url: "mail.php",
        data: $("#contactForm").serialize(),
        success: function(text) {
            if (text == "success") {
                $("#msgSubmit" ).removeClass( "hidden" );
                setTimeout(function() {
                    $("#msgSubmit" ).addClass( "hidden");
                }, 6000);
            }
        },
        error : function() {
            /* You probably want to add an error message as well */
            $("#msgError" ).removeClass( "hidden" );
        }
    });
}
</script>

A: Try to remove the comment inside the json:
$(document).ready(function() {
var owl = $("#owl-hero");

owl.owlCarousel({

    navigation: false,
    slideSpeed: 1,
    paginationSpeed: 400,
    singleItem: true,
    transitionStyle: "fade"

});
});

It is not syntactically correct.


text:
Q: Accessing textbox controls in foreach loop I have 2 list string like this :
List<string> answerList = new List<string>();
List<string> choiceList = new List<string>();

answerList is already added with string inside
choiceList is the list where i want to add the text of each textboxes in the panel
I have many textboxes in a panel and each textbox , user input text into each textbox
then when user click Check button , i want to do a foreach loop to access the loop controls .
So i want to do a foreach loop to loop the textboxes controls text and compare it with answerList , and if it is different , it will change the textbox background color.
I manage to do until here ( it doesn't even enter the IF statement ) :
protected void btnCheck_Click(object sender, EventArgs e)
{
    foreach (Control s in Panel1.Controls)
    {
        //it won't enter here.
        if (s.GetType() == typeof(TextBox))
        {
            TextBox tb = s as TextBox;
            choiceList.Add(tb.Text.Trim());

           //Compare here but i don't know how .
        }
    }
}

FYI , textboxes are dynamically created and added to Panels .
I need help as i did this before but i forgotten how been a long time since i did programming ...
EDIT

The rest of my code ( partial , the way i create my controls and add them to panel ) :
  dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        Label question = new Label();
        question.Text = dr["question"].ToString();
        Panel1.Controls.Add(question);

        LiteralControl lc = new LiteralControl();
        lc.Text = "&nbsp&nbsp&nbsp&nbsp";
        Panel1.Controls.Add(lc);

        TextBox answer = new TextBox();
        answer.Width = 100;
        Panel1.Controls.Add(answer);

        LiteralControl lc1 = new LiteralControl();
        lc1.Text = " <br />";
        Panel1.Controls.Add(lc1);

        answerList.Add(dr["answer"].ToString());

    }

A: You can still use the way you already did, only use is to see if it is indeed a TextBox:
protected void btnCheck_Click(object sender, EventArgs e)
{
    foreach (Control s in Panel1.Controls)
    {
        if (s is TextBox)
        {
            TextBox tb = (TextBox)s;
            choiceList.Add(tb.Text.Trim());
        }
    }
}

Or you can use LinQ's OfType<T> method to skip the if statment:
protected void btnCheck_Click(object sender, EventArgs e)
{
    foreach (TextBox t in Panel1.Controls.OfType <TextBox>())
    {
        choiceList.Add(t.Text.Trim());
    }
}

More reading:

*

*is (C# Reference)

*Enumerable.OfType Method
Edit:
If the textboxes are evaluated in the same order as the values in the answerlist, you can compare the value after you added the item to the choicelist. Your code will look like:
foreach (TextBox t in Panel1.Controls.OfType <TextBox>())
{
    string tmp = t.Text.Trim();
    choiceList.Add(tmp);

    if(answerList[choiceList.Count-1] != tmp)
    {
        //Change background-color of t
        t.BackColor = Color.Red;
    }
}

But if you work this way and you don't need the answers afterwards anymore, you can just skip the part of adding the value to the choiceList. And then you can work with a counter:
int i = 0;

foreach (TextBox t in Panel1.Controls.OfType <TextBox>())
{
    if(answerList[i++] != t.Text.Trim())
    {
        //Change background-color of t
        t.BackColor = Color.Red;
    }
}

If the textboxes are not evaluated in the same order you can use Contains to see if a choice is in the answerlist:
if(!answerList.Contains(t.Text.Trim())
    //Change background-color

A: Try with
foreach (TextBox t in Panel1.Controls.OfType <TextBox>())
{
  if(!answerList.Contains(t.text)
  {
       t.BackColor= Color.Red;
  }

}

A: Try
List<string> notInanswerList = new List<string>();
foreach (textbox t in Panel1.Controls.OfType<TextBox>())
{
    choiceList.Add(t.Text.Trim());
    if (!answerList.Contain(t.Text.Trim()))
    {
        notInanswerList.Items.Add(t.Text.Trim());
        t.BackColor = System.Drawing.Color.Red; // changes the textBox BackColor
    }
}

A: To compare 2 List, you can also use this
        List<string> questions = new List<string>() { "a", "b", "c", "d", "e", "f" };
        List<string> answers = new List<string>() { "b","c","d","x"};

        foreach (string str in answers)
        {
            if (questions.Exists(q => q == str))
            {
                Console.WriteLine("answer found " + str); //print b,c,d
            }
            else
            {
                Console.WriteLine("answer not found " + str); //print x
            }

        }


text:
Q: Exception: Microsoft Excel has stopped working There is an application running perfectly in Windows PC (desktop, laptop). But when I try to run this application in Surface, it gives me the error below.

I debugged the code and it gives error at the code where we try to lock the cell.
Public Function temp1()
ActiveSheet.Unprotect "pswd"
ActiveSheet.EnableSelection = xlUnlockedCells
        Sheets("Travel_Requisition").Range("B" & "2", "S" & "105").Locked = True
        Sheets("Travel_Requisition").OptionButton12.Enabled = False
        Sheets("Travel_Requisition").OptionButton13.Enabled = False
        ActiveSheet.Protect Password:="?Inapune2007", DrawingObjects:=False, _
        Contents:=True, Scenarios:=True

End Function

It stops working when code executes the below line.
Sheets("Travel_Requisition").Range("B" & "2", "S" & "105").Locked = True


text:
Q: Unity Geometry Shader: Dynamic Grass So, I have a functioning voxel engine that creates smoothed terrain in chunks of 1x1x1 meter in a 1024 radius around my player.
I wanted to create a geometry shader that not only continues to texture the ground appropriately, but also creates grass (preferably waving with the wind).
I have found some basic billboard geometry shaders to get me started, but they seem to cause the mesh to stop texturing. Is there anyway to do both from one shader?
Do I pass the mesh triangles and the new grass triangles on to the fragment shader with a flag? Thanks in advance!

A: You can do this by implementing two passes to the shader as it turns out. My first pass is a simple surface shader, but my second pass is the geometry shader. The multi-pass still results in 130 FPS, so it seems to be adequate.


text:
Q: Decode cp1252 stdout with umlauts I want to list the services running on the local Windows machine. For that, I am using this code:
with Popen(["net", "start"], stdout=PIPE, stderr=PIPE) as p:
    stdout, stderr = p.communicate()  # type: (bytes, bytes)

A part of the output looks like this (German Windows version):
Folgende Windows-Dienste sind gestartet:

   Anmeldedienst
   [...]
   Benachrichtigungsdienst für Systemereignisse

Decoding the bytes to a string should be easy. I checked the documentation and found the local encoding on the command line:
>>> import locale
>>> locale.getpreferredencoding()
'cp1252'

Therefore, I would like to decode the bytes:
lines = stdout.decode('cp1252')

However, for the umlaut ü listed in the example, I get an error message:
File "test.py", line 511, in my_func
    lines = stdout.decode('cp1252')
File "C:\Python344\lib\encodings\cp1252.py", line 15, in decode
    return codecs.charmap_decode(input,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 152: character maps to <undefined>

However, I know that UTF-8 contains a representation of the ü character:
U+00FC  ü   c3 bc   LATIN SMALL LETTER U WITH DIAERESIS

I am at a loss why this translation cannot be done.
Notes:

*

*I know when using universal_newslines=True for the Popen call, I can circumvent the whole ordeal, but using that was what lead me to analyse what the problem with the encoding is.

*Starting with Python 3.5, it seems that the Popen constructor got an encoding= option added, maybe this would prevent questions like this. Sadly, Python 3.4 is the version included in certain LTS Linux versions.

Edit 1: Something is afoot here. Although the Python 3.4 documentation states that the default encoding is cp1252 on Windows, when running the command on the CLI and redirecting to a file, the file is encoded in IBM850. Best guess would be that the locale.getpreferredencoding() doesn't return the encoding of the CLI.
Edit 2: A decoding of the stdout using ibm850 works like a charm. That means that using universal_newlines=True for the Popen call does use the encoding returned by locale.getpreferredencoding(), however, that is the wrong encoding to decode the CLI output.

A: The solution is:
When using a Popen call with universal_newslines=True, that forces a string interpretation of the returned stdout, stderr data. However, the interpretation is done using the encoding that is returned by locale.getpreferredencoding(), which in this case was cp1252. However, the data on the command line was not encoded using cp1252 (Windows-like ANSI style encoding), but ibm850 (DOS encoding). Because decoding operated on bytes and int, and because the int in the stdout for ü (0x81) had no corresponding value in the cp1252 decoding table, an exception from the depths of Python was thrown.
Decoding the command line data manually with str.decode('ibm850') decoded correctly.
Note: Starting with Python 3.5, Popen allows the passing of an encoding to be used for the data flow, which Python 3.4 lacks.


text:
Q: Restoring corrupted bak file Our server & Backup data got crashed and we had a recovered the data using the recovery Tool. Currently I am having .BAK Files.
When we are trying to rebuild the DB using the recovered .bak file getting the Errors
when i try restoring through query
RESTORE DATABASE dbName
   FROM DISK = N'Path\To\Backup.bak'
   WITH MOVE 'dbName_DataFileLogicalName' TO 'Path\To\Data.mdf',
        MOVE 'dbName_LogFileLogicalName' TO 'Path\To\Log.ldf',
       REPLACE,
       STATS = 10

i get the error as

Msg 3241, Level 16, State 0, Line 1 The media family on device
  'D:\DB\NASH_20160718.bak' is incorrectly formed. SQL Server cannot
  process this media family. Msg 3013, Level 16, State 1, Line 1 RESTORE
  DATABASE is terminating abnormally.

please help thanks !!

A: you can get this message in different error/ issues on during the backup/restore process. To identify and fix this problem.

*

*You might using different backup version than what your current database. This is the most probable cause of what I suspect from the error message displayed. You might have a backup file from higher version and now your current server is lower version. you can always restore from lower to higher but can not backward.

*The second issue could be, you might have a corrupted backup file. So first make sure you have restore able backup file.

*Your backup file might be encrypted. Make sure your backup is not encrypted and if so you might need to find the decryption key.

Hopefully this will resolve your issue.


text:
Q: Execute commands from shell script fails I'm trying read a file which contains lines like this:
 Run COMMAND with options "OPTIONS" and arguments "ARGUMENTS"

Then I want to execute this command with given options and arguments. For example I'd like to execute these commands:
 Run pwd with options "" and arguments ""
 Run ls with options "-al" and arguments "$HOME"
 Run ls with options "-al" and arguments "Example: \"strange folder name\""

This is my code
#!/bin/bash

while read -r line
do
 COMMAND=$(echo "$line" | cut -d" " -f 2)
 OPTIONS=$(echo "$line" | cut -d" " -f 5 | tr -d '"')
 ARGUMENTS=$(echo "$line" | cut -d" " -f 8)

 $COMMAND $OPTIONS $ARGUMENTS
 done <$1

First example is working as it should, second one is giving me error ls: cannot access $HOME: No such file or directory' and third one is not storing the name of the folder to $ARGUMENTS correctly.

A:
second one is giving me error ls: cannot access $HOME: No such file or directory'

This is because the folder named $HOME does not exist. I am not talking about the value of $HOME variable, but the string literal. The shell does not execute the parameter expansion in your situation.

third one is not storing the name of the folder to $ARGUMENTS correctly

This is because -f 8 only extract column 8, try -f 8- to extract the 8th column and all the others until the end of line.
You can give a try to this version below:
while read -r line; do
  COMMAND=$(printf "%s" "${line}" | cut -d" " -f 2)
  OPTIONS=$(printf "%s" "${line}" | cut -d" " -f 5 | tr -d '"')
  ARGUMENTS=$(printf "%s" "${line}" | cut -d" " -f 8-)
  $COMMAND $OPTIONS "$(eval printf \"%s\" "$ARGUMENTS")"
done < "${1}"

The eval is a shell built-in command which is used to enable parameter expansion of ARGUMENTS, if applicable.
I have to warn you that the eval is usualy say risky to use.


text:
Q: Java: HashMap behaving in an unexpected manner So I have this hashmap with key as String and holds values as an integer array.
HashMap<String, Integer[]> h = new HashMap<String, Integer[]>();
h.put("PID", new Integer[] {3, 5});

I was trying int first, but then I read somewhere that primitive types can't be used in generics.
So, Eclipse says
Multiple markers at this line
- Syntax error on token(s), misplaced construct(s)
- Syntax error on tokens, ConstructorHeaderName expected
 instead
- Syntax error on tokens, delete these tokens

for the second line. First line is fine for it.

A: This statement must be executed inside of any function or constructor. you can not insert, delete or update in global space.
This is a statement, you can't write statement at the place you are trying to do

h.put("PID", new Integer[] {3, 5});

Again you can not execute below statement because int[] is a primitive array and Integer[] is a arary of Integer Object. you have declared key,value == String,Integer[] so you can not insert int[] array

h.put("PID", new int[] {3, 5});

Again java Hashmap does not support primitive data type. you must have to use Object as key or value of Hashamp.

A: This code works fine for me:
import java.util.HashMap;

public class HelloWorld{

     public static void main(String []args){
        HashMap<String, int[]> h = new HashMap<String, int[]>();
        h.put("PID", new int[] {3, 5});

        System.out.println(h.get("PID")[0]); //prints "3"
        System.out.println(h.get("PID")[1]); //prints "5"
     }
}


text:
Q: React 0.14 - using refs via findDOMNode I am trying to access an input field on the click of button using refs. The syntax that I have written works fine in ComponentDidMount but gives the following error on click of the button.
Uncaught TypeError: Cannot read property 'refs' of null.
"use strict"

import React from 'react'
import ReactDOM from 'react-dom'

class Dashboard extends React.Component {
    componentDidMount() {
        console.log("in component did mount", ReactDOM.findDOMNode(this.refs.Url))
    }
    shortenURL() {
        console.log("in function", ReactDOM.findDOMNode(this.refs.Url)) //Gives error: Uncaught TypeError: Cannot read property 'refs' of null
    }
    render() {
        return (

            <form>

URL Shortener

                  Enter your long URL here
                  <input type="text" ref="Url" className="form-control" placeholder="Enter Your Long URL here"></input>

                  <button className="btn  btn-info" type="button" onClick={this.shortenURL}>Shorten</button>

        </form>

        )
    }
}
export default Dashboard;

A: It's because you lose the context for this when a user clicks. Try this instead:
<button className="btn btn-info" type="button" onClick={this.shortenURL.bind(this)}>Shorten</button>

A: You can read more about this issue in a discussion on React Github. Basically ES6 methods don't auto-bind to this. You can either use bind as Thomas mentioned, or you can use the succinct Arrow function -
onClick={(e) => this.shortenURL()}


text:
Q: Tilde approximation for $\frac{N^{100}}{2^N}$? I am having some trouble getting the tilde approximation for a computer algorithms class. Here is what I have so far:
$\frac{N^{100}}{2^N} \rightarrow \lg\left(\frac{N^{100}}{2^N}\right) = \lg(N^{100}) - \lg(2^N) =
100\lg(N) - N\lg(2)$
From here I am stuck. I was thinking that the tilde might be $0$ given that $2^N$ grows faster of the two.

A: I don't know if I answered your question:
$f(N) = \frac{N^{100}}{2^N}$ is not only bounded, but it eventually goes to 0, as $N$ goes to infinity. The short answer is that for any positive constants $c$ and $k$ independent of $N$, the function $e^{cN}$ always dominates $N^k$ as $N$ gets large. Even though, depending on the specific values of $c$ and $K$, the value of $N^k$ may be much much larger than $e^{cN}$ for "practical" values of $N$.
ETA: Looks like you already understand this.
So $f(N) \in O(1)$ would technically be correct; $f(N) \in o(1)$ would also be correct (and a stronger statement as $o(1) \subset O(1)$ ). I am really not sure what other answer would be called for here.
What would be incorrect though is $f(N) \in \theta(1)$; that would imply that (put informally) $N^{100}$ and $2^N$ grow roughly proportionally to each other for $N$ arbitrarily large.  Put more formally, the statement $f(N) \in \theta(1)$ would imply that there exists an $\epsilon > 0$ such that, for any $N_0$ there is some $N > N_0$ such that $|f(N)| > \epsilon$. And in this particular instance this is not true.

A: The ratio never exceeds $3.076*10^{172}$ at $N=144$. So I guess the approximation would be a constant.


text:
Q: trouble installing accelerate-cuda I have been trying to run cabal install accelerate-cuda -fdebug to no avail. at first i had some issues i think with my version of cuda, so i upgraded ghc to version 8.0.1 and cabal to version 1.22.5.0.
I was able to run cabal install accelerate which worked but cabal install accelerate-cuda has resulted in :

Resolving dependencies... cabal: Could not resolve dependencies:
  trying: accelerate-cuda-0.15.1.1 (user goal) next goal: base
  (dependency of accelerate-cuda-0.15.1.1) rejecting:
  base-4.9.0.0/installed-4.9... (conflict: accelerate-cuda => base>=4.7
  && <4.9) rejecting: base-4.9.0.0, 4.8.2.0, 4.8.1.0, 4.8.0.0, 4.7.0.2,
  4.7.0.1, 4.7.0.0, 4.6.0.1, 4.6.0.0, 4.5.1.0, 4.5.0.0, 4.4.1.0, 4.4.0.0, 4.3.1.0, 4.3.0.0, 4.2.0.2, 4.2.0.1, 4.2.0.0, 4.1.0.0, 4.0.0.0, 3.0.3.2, 3.0.3.1 (global constraint requires installed instance) Dependency tree exhaustively searched.

A: Ghc 8.0.1 came with an updated version of base (4.9) which might be incompatible with the accelerate-cuda package.
You can try and pass the flag --allow-newer to cabal, or dowload the package with cabal get and edit the cabal fie manually setting base >= 4.8 && <5.0 in the build dapends section.


text:
Q: How you manage EM or EMF in integration testing with testcontainers? I have java web application and I would like to write integration tests for service layer. I decided to use testcontainers, so in test I would like to call service, which will work with database in docker container.
My test class looks like example below.
@Testcontainers
class ITPlayerServiceImpl {

  @Container
  private static final PostgreSQLContainer POSTGRE_SQL_CONTAINER =
  new PostgreSQLContainer()
            .withDatabaseName("dbName")
            .withUsername("dbUserName")
            .withPassword("dbPassword");
}

Tested service.
@Stateless
public class PlayerServiceImpl implements PlayerService {

  @PersistenceContext(unitName = "persistence_unit_name")
  private EntityManager entityManager;

  //Methods

I need create EMF connected to DB in container and then populate EM from that EMF into tested service.
Thank you for help or hints.

A: After some investigation and testing I end with solution below.
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@Testcontainers
class ITApplicationUserService {

    @Container
    private static final PostgreSQLContainer POSTGRE_SQL_CONTAINER = new PostgreSQLContainer()
            .withDatabaseName("someDatabase")
            .withUsername("someUsername")
            .withPassword("somePassword");

    // EMF for integration tests
    private static EntityManagerFactory emf;

    // EM for tested service
    private static EntityManager entityManager;

    // Tested service
    private static ApplicationUserServiceImpl applicationUserService = new ApplicationUserServiceImpl();

    // Object used for testing
    private static ApplicationUser testingApplicationUser;

    @BeforeAll
    static void init() {

        // Properties for our EMF, which will make EM connected to POSTGRE_SQL_CONTAINER
        Map<String,String> properties = new HashMap<>();
        properties.put("javax.persistence.jdbc.url",POSTGRE_SQL_CONTAINER.getJdbcUrl());
        properties.put("javax.persistence.jdbc.user",POSTGRE_SQL_CONTAINER.getUsername());
        properties.put("javax.persistence.jdbc.password",POSTGRE_SQL_CONTAINER.getPassword());
        properties.put("javax.persistence.jdbc.driver",POSTGRE_SQL_CONTAINER.getDriverClassName());
        properties.put("eclipselink.logging.level","FINE");

        // We need create fresh empty schema in POSTGRE_SQL_CONTAINER
        properties.put("javax.persistence.schema-generation.database.action","create");

        // Creation of EMF
        emf = Persistence.createEntityManagerFactory("integrationTesting",properties);

        // Player for testing
        testingApplicationUser = new ApplicationUser();
        testingApplicationUser.setLogin("loginName");
        testingApplicationUser.setEmail("something@somewhere.com");
        testingApplicationUser.setPassword("123456");
    }

    @Test
    @Order(1)
    void saveNewApplicationUserTest() {
        assertTrue(testingApplicationUser.getId()==null);
        ApplicationUser applicationUser = applicationUserService.saveApplicationUser(testingApplicationUser);
        assertTrue(applicationUser.getId()!=null);
    }

    @Test
    @Order(2)
    void getApplicationUsers() {
        assertTrue(applicationUserService.getAllApplicationUsers().size()==1);
    }

    @BeforeEach
    private void startTransaction() throws IllegalAccessException, NoSuchFieldException {
        entityManager = emf.createEntityManager();
        // We will declare field of EM in tested service
        // EM field in tested class is not public and should not be. We will use reflection for population of EM.
        Field emField = applicationUserService.getClass().getDeclaredField("entityManager");
        emField.setAccessible(true);
        emField.set(applicationUserService,entityManager);

        entityManager.getTransaction().begin();
    }

    @AfterEach
    private void commitTransaction() {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().commit();
            entityManager.close();
        }

    }

}


text:
Q: Find the GS of the System of DE's $\begin{cases} x' = x-3y\\ y'=3x+7y \end{cases}$ Find the GS of the following system of DE's where the independent variable is $t$ and $x$ and $y$ are the dependent variables
\begin{cases}
x' = x-3y\\
y'=3x+7y
\end{cases}
I know using eigenvalues and eigenvectors or operators is one way to do this. But I wish to double check my answer using a substitution method.
So my work:
The second DE $y'=3x+7y$ can be rewritten as $x = \cfrac{y'}{3}-\cfrac 73y$
then $x' = \cfrac{y''}{3}-\cfrac73y'$
When we plug these values of $x$ and $x'$ into the first DE ($x' = x -3y)$, we get with some rearranging
$\cfrac{y''}{3}-\cfrac83y'+\cfrac{16}{3}y = 0$
Which has a characteristic equation of
$\cfrac{r^2}{3}-\cfrac83r+\cfrac{16}{3} = 0$
with roots $r_1=4$ and $r_2 = 4$
Then the solution for $y$ is $y$ = $C_1e^{4t}+C_2te^{4t}$
Then we back sub to solve for $x$ using $x = \cfrac{y'}{3}$$-\cfrac73y$ with the solution of y we just found.
We get $x =-C_1e^{4t}-C_2te^{4t} + \cfrac{C_2}{3}e^{4t} =-C_1e^{4t}-C_2te^{4t} + C_3e^{4t}$
so the GS to the homo system is
\begin{cases}
x = -C_1e^{4t}-C_2te^{4t}+C_3e^{4t}\\
y = C_1e^{4t}+C_2te^{4t}
\end{cases}
If this solution is right, then I'm confident that I understand how substitution method works for solving DE systems. (Also it would boost my confidence in using the operator method to solve this as I got the same answer as this using the operator method). I'm a little thrown off on the roots being the same but I still think my methodology is still sound. I would appreciate it if someone could tell me if I've got this right cause then I know I completely understand how to solve a system of DE's.
If more work is necessary to show please let me know.

A: Your method is correct.
Another way is to write the system as $X'=MY$
Where $M$ is the matrix $$\begin{pmatrix} 1 & -3 \\ 3 & 7 \end{pmatrix}$$
its eigen values are $m_1,m_2=4$ (repeated roots), so the solution for $x$ can be written as
$x=(A t+B)e^{4t}$, putting it in first equation one can get $y$. So there will be two
undetermined constants: $A,B$.

A: $$\begin{cases}
x = -C_1e^{4t}-C_2te^{4t}+C_3e^{4t}\\
y = C_1e^{4t}+C_2te^{4t}
\end{cases}$$
You should only end with two constants not three.
$$y=C_1e^{4t}+C_2te^{4t}$$
$$y'=4C_1e^{4t}+C_2e^{4t}+4tC_2e^{4t}$$
$$y'=4C_1e^{4t}+C_2e^{4t}(1+4t)$$
And since:
$$x = \cfrac{y'}{3}-\dfrac 73 y$$
You should only have $C_1$ and $C_2$ constant. You applied the method of substitution correctly.


text:
Q: Rails - pretty URI instead of Restful URI in View
<tr onclick="window.location.href = '<%= url_for :controller => "products", :action => "index", :product => release.product_name, :version => release.version %>'" >

In controller
release  = Release.find_ver_rel(params[:product], params[:version])
respond_to do |format|
  format.html { render :template => 'releases/overview' }
end

It produces URI: /products?product=Atlas&version=0.2
How to get "pretty uri" like  /products/product/Atlas/version/0.2?

A: In your routes file config/routes.rb put
match '/products/product/:name/version/:version' => 'product#index', :as => :something
This way, you can either pass variables directly into something_path(:name => 'Name'), or fetch it from params[:name].


text:
Q: Tesseract gives no recognition results (Android studio; Java) I am making an app on Android Studio with tesseract OCR. I made a code which should recognize text on images taken by phone camera. Problem: tesseract function getUTF8Text() gives no result AT ALL (null, despite picture being with text). Program does not give any errors.
I wondered about possible issues: 1. Maybe I integrated tesseract into my project not properly? (Compilator does not show any issues when using tesseract classes in code) 2. Maybe problem in code? (bad traineddata path??).
Main class:
Code:
private TessOCR Tess;

//after taking picture I call:
PictureCallback pictureCallback = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        String result = Tess.getOCRResult(bitmap);

        if (result != null) Log.i(TAG, result);
        else Log.i(TAG, "NO RESULT");
    }
};

TessOCR class for tesseract traineddata file finding or adding and text recognition (Constructor is only for finding traineddata file):
public class TessOCR {
public static final String PACKAGE_NAME = "com.example.dainius.ocr";
public static final String DATA_PATH = Environment
        .getExternalStorageDirectory().toString() + "/AndroidOCR/";
public static final String lang = "eng";

private static final String TAG = "OCR";
private TessBaseAPI mTess;

public TessOCR(AssetManager assetManager) {

    mTess = new TessBaseAPI();

    String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };

    for (String path : paths) {
        File dir = new File(path);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
                return;
            } else {
                Log.v(TAG, "Created directory " + path + " on sdcard");
            }
        }

    }

    if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
        try {
            InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
            OutputStream out = new FileOutputStream(DATA_PATH
                    + "tessdata/" + lang + ".traineddata");

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();

            Log.v(TAG, "Copied " + lang + " traineddata");
        } catch (IOException e) {
            Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
        }
    }

    mTess.setDebug(true);
    mTess.init(DATA_PATH, lang);
}

public String getOCRResult(Bitmap bitmap) {

    mTess.setImage(bitmap);
    String result = mTess.getUTF8Text();

    return result;
}

public void onDestroy() {
    if (mTess != null)
        mTess.end();
}

*

*If this problem is caused by bad tesseract integration, please post a proper tutorial about how to integrate it, because every tutorial on the internet is different from each other, it's hard to understand how to properly do it.

A: I've worked with Tesseract (tess4j).  Have you tried using an image with very clear text and completely monochrome/grayscale?  I've found that when I'm trying to get Tesseract to read my images it's much more useful to spend time manipulating the image trying to make it easier for Tesseract.
If you still aren't able to get it to produce output and it isn't showing any errors, I'd go here and restart the Tesseract setup with the tutorial and follow all of their tips.  It shouldn't be too difficult, the .dll's are extracted and loaded automatically.  Just make sure your tessdata folder is in the correct spot (root directory) and you have all the .jar's (I think there's only 4 that you need, not all of them, but check the tutorial on tess4j.sourceforge.com) as compile-time libraries.
Taken from their website: "Images intended for OCR should have at least 200 DPI in resolution, typically 300 DPI, 1 bpp (bit per pixel) monochome or 8 bpp grayscale uncompressed TIFF or PNG format."  To be honest, I haven't had much luck with Tesseract besides their PDF tools to scan easy-to-read high-resolution documents.
I didn't get it to work the first time either, for what it's worth.

A: The cause of my problem was that I did not as permission to write external storage. If anyone will try to apply this method to extract file from assets folder (got this method from this github project), make sure you add permission to write external storage code line to your manifest (AndroidManifest.xml file):
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: Uncaught TypeError: Cannot read property 'orientation' of undefined This is the follow up of question Grid For HTML app's based on this answer
I've tried to create the data table using https://www.datatables.net/ the js files coming with this added to my existing project folder
and following is my <head> tag
<head>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>AndRemedy</title>
<link rel="stylesheet" href="css/jquery.mobile-1.0rc1.min.css" />
<link rel="stylesheet" href="css/styles.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.0rc1.min.js"></script>
<script src="jqm.autoComplete-1.5.2-min.js"></script>
<script type="text/javascript" src="js/login.js"></script>
<!-- DataTable reference starts here -->
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="media/css/jquery.dataTables.css">

<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="media/js/jquery.js"></script>

<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="media/js/jquery.dataTables.js"></script>

</head>

But when I run this getting

Uncaught TypeError: Cannot read property 'orientation' of undefined : jquery.mobile-1.0rc1.min.js:45

Note : Am trying to develop a hybrid app using PhoneGap,HTML5

A: As the error says, there's a TypeError in you jquery.mobil script. You can try to update it with the last version. Don't forget the stylesheet.
If you still have an error, try the uncompressed version.

A: You are using referencing two jquery files in your script. Only one is needed. Remove the first one and move the rest of the jquery and it's dependency files to the body tag.


text:
Q: How to do a logical OR operation for integer comparison in shell scripting? I am trying to do a simple condition check, but it doesn't seem to work.
If $# is equal to 0 or is greater than 1 then say hello.
I have tried the following syntax with no success:
if [ "$#" == 0 -o "$#" > 1 ] ; then
 echo "hello"
fi

if [ "$#" == 0 ] || [ "$#" > 1 ] ; then
 echo "hello"
fi

A: have you tried something like this:
if [ $# -eq 0 ] || [ $# -gt 1 ]
then
 echo "$#"
fi

A: This code works for me:
#!/bin/sh

argc=$#
echo $argc
if [ $argc -eq 0 -o $argc -eq 1 ]; then
  echo "foo"
else
  echo "bar"
fi

I don't think sh supports "==". Use "=" to compare strings and -eq to compare ints.
man test

for more details.

A: From Bash Reference Manual → 3.4.2 Special Parameters

#
  ($#) Expands to the number of positional parameters in decimal.

Therefore, $# will always be either 0 or a bigger integer.
So if you want to do something whenever $# is either 0 or bigger than 1, you just have to check if $# is or is not 1:
[ $# -eq 1 ] && echo "1 positional param" || echo "0 or more than 1"

This uses the syntax:
[ condition ] && {things if true} || {things if false}

A: If you are using the bash exit code status $? as variable, it's better to do this:
if [ $? -eq 4 -o $? -eq 8 ] ; then
   echo "..."
fi

Because if you do:
if [ $? -eq 4 ] || [ $? -eq 8 ] ; then

The left part of the OR alters the $? variable, so the right part of the OR doesn't have the original $? value.

A: Sometimes you need to use double brackets, otherwise you get an error like too many arguments
if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
  then
fi

A: If a bash script
If [[ $input -gt number  ||  $input  -lt number  ]]
then
    echo .........
else
    echo .........

fi

exit

A: This should work:
#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
    echo "hello"
fi

I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so:
if (("$#" > 1))
 ...

A: And in Bash
 line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
 vpid=`ps -ef|  grep wowzaDataSync | grep -v grep  | awk '{print $2}'`
 echo "-------->"${line1}
    if [ -z $line1 ] && [ ! -z $vpid ]
    then
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
            "Process Is Working Fine"
    else
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
            "Prcess Hanging Due To Exception With PID :"${pid}
   fi

OR in Bash
line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
vpid=`ps -ef|  grep wowzaDataSync | grep -v grep  | awk '{print $2}'`
echo "-------->"${line1}
   if [ -z $line1 ] || [ ! -z $vpid ]
    then
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
            "Process Is Working Fine"
    else
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
            "Prcess Hanging Due To Exception With PID :"${pid}
  fi


text:
Q: Rotate view from anchor swift In my application, I am calculating BMI of a user based on its height and weight. So based on the BMI value I am animating a needle. The issue is that the needle moves off the center and rotates.
CODE:
ivPointer.layer.anchorPoint = CGPoint(x: 0, y: 0.5)  // i have changed the values still its not working properly
let angle = Double((value * Double.pi)/180)
var transform = CGAffineTransform.identity.rotated(by: CGFloat(angle))


text:
Q: Using C# to create the Twitter authorization header for search I'm writing to write a C# method to generate a authentication header for Twitter. I'm trying to search twitter through this API: https://api.twitter.com/1.1/search/tweets.json.
Here's the URL I call:
https://api.twitter.com/1.1/search/tweets.json?q=%23countryman+OR+%23johncooperworks+OR+%40mini%26since_id%3d24012619984051000%26max_id%3d250126199840518145%26result_type%3dmixed%26count%3d4

Here's my method:
private string GetTwitterAuthHeader()
{
    const string oauthConsumerKey = "";
    const string oauthConsumerSecret = "";
    const string oauthToken = "";
    const string oauthTokenSecret = "";
    const string oauthVersion = "1.0";
    const string oauthSignatureMethod = "HMAC-SHA1";

    var oauthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)));
    var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    var oauthTimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString(CultureInfo.InvariantCulture);

    const string resourceUrl = "https://api.twitter.com/1.1/search/tweets.json";
    const string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                                "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";

    var baseString = string.Format(baseFormat,
                                oauthConsumerKey,
                                oauthNonce,
                                oauthSignatureMethod,
                                oauthTimestamp,
                                oauthToken,
                                oauthVersion
                                );

    baseString = string.Concat("GET&", Uri.EscapeDataString(resourceUrl), "&", Uri.EscapeDataString(baseString));

    var compositeKey = string.Concat(Uri.EscapeDataString(oauthConsumerSecret),
                            "&", Uri.EscapeDataString(oauthTokenSecret));

    string oauthSignature;
    using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey)))
    {
        oauthSignature = Convert.ToBase64String(
            hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString)));
    }

    const string headerFormat = "OAuth oauth_consumer_key=\"{0}\", " +
                                "oauth_nonce=\"{1}\", " +
                                "oauth_signature=\"{2}\", " +
                                "oauth_signature_method=\"{3}\", " +
                                "oauth_timestamp=\"{4}\", " +
                                "oauth_token=\"{5}\", " +
                                "oauth_version=\"{6}\"";

    var authHeader = string.Format(headerFormat,
                            Uri.EscapeDataString(oauthConsumerKey),
                            Uri.EscapeDataString(oauthNonce),
                            Uri.EscapeDataString(oauthSignature),
                            Uri.EscapeDataString(oauthSignatureMethod),
                            Uri.EscapeDataString(oauthTimestamp),
                            Uri.EscapeDataString(oauthToken),
                            Uri.EscapeDataString(oauthVersion)
                    );

    return authHeader;
}

The error I get is:
{
    "errors": [
        {
            "message": "Bad Authentication data",
            "code": 215
        }
    ]
}

Any pointers?
Do I need to account for the actual search query in generating  the auth header? (e.g. the values I append to the search API)?
I'm finding it hard to debug.
Thanks!
EDIT:
Based on feedback, here's an update:
var resourceUrl = "https://api.twitter.com/1.1/search/tweets.json";
const string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                            "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";

var baseString = string.Format(baseFormat,
                            oauthConsumerKey,
                            oauthNonce,
                            oauthSignatureMethod,
                            oauthTimestamp,
                            oauthToken,
                            oauthVersion,
                            query
                            );

baseString = string.Concat("GET&",
    Uri.EscapeDataString(resourceUrl), "&",
    Uri.EscapeDataString(baseString));

Having read https://dev.twitter.com/oauth/overview/creating-signatures closer, this seems to be right. Still, I get the same error.

A: Wrap your "query" in Uri.EscapeDataString().
Your exact code above works for me if I do that. That said, you should really be escaping all of those parameter keys and values, and I'm a bit stumped as to why the nonce is working without escaping, since it's base64 encoded. But perhaps I was just lucky in my testing and never hit a nonce with a slash in it.

A: So, I wrote a class that does this.  Let's see how well I can break it down. Let's start with the entire class.
    public class TwitterAuthTool : IDisposable {
    private const string BASE_AUTH_URL = "https://api.twitter.com/oauth2/token";
    private const string BASE_SEARCH_URL = "https://api.twitter.com/1.1/search/tweets.json";
    private const string BASE_INVALIDATE_URL = "https://api.twitter.com/oauth2/invalidate_token";

    private AccessToken Credentials;
    private string BearerTokenCredentials;

    public TwitterAuthTool( string p_ConsumerKey, string p_ConsumerSecret ) {
        BearerTokenCredentials =
            Convert.ToBase64String(
                Encoding.ASCII.GetBytes(
                    string.Format( "{0}:{1}",
                        Uri.EscapeUriString( p_ConsumerKey ),
                        Uri.EscapeUriString( p_ConsumerSecret ) ) ) );

        HttpWebRequest _Request = HttpWebRequest.Create( BASE_AUTH_URL ) as HttpWebRequest;
        _Request.KeepAlive = false;
        _Request.Method = "POST";
        _Request.Headers.Add( "Authorization", string.Format( "Basic {0}", BearerTokenCredentials ) );
        _Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

        byte[] _Content = Encoding.ASCII.GetBytes( "grant_type=client_credentials" );
        using( Stream _Stream = _Request.GetRequestStream() )
            _Stream.Write( _Content, 0, _Content.Length );

        HttpWebResponse _Response = _Request.GetResponse() as HttpWebResponse;

        DataContractJsonSerializer _AccessTokenJsonSerializer = new DataContractJsonSerializer( typeof( AccessToken ) );
        Credentials = (AccessToken)_AccessTokenJsonSerializer.ReadObject( _Response.GetResponseStream() );
    }

    public List<Tweet> GetLatest( string p_Query, int p_Count = 100 ) {
        TwitterResults _TwitterResults;
        List<Tweet> _ReturnValue = new List<Tweet>();
        DataContractJsonSerializer _JsonSerializer = new DataContractJsonSerializer( typeof( TwitterResults ) );

        HttpWebRequest _Request = WebRequest.Create( string.Format( "{0}?q={1}&result_type=recent&count={2}", BASE_SEARCH_URL, p_Query, p_Count ) ) as HttpWebRequest;
        _Request.Headers.Add( "Authorization", string.Format( "Bearer {0}", Credentials.access_token ) );
        _Request.KeepAlive = false;
        _Request.Method = "GET";

        HttpWebResponse _Response = _Request.GetResponse() as HttpWebResponse;
        _TwitterResults = (TwitterResults)_JsonSerializer.ReadObject( _Response.GetResponseStream() );
        _ReturnValue.AddRange( _TwitterResults.statuses );

        while( !string.IsNullOrWhiteSpace( _TwitterResults.search_metadata.next_results ) ) {
            _Request = WebRequest.Create( string.Format( "{0}{1}", BASE_SEARCH_URL, _TwitterResults.search_metadata.next_results ) ) as HttpWebRequest;
            _Request.Headers.Add( "Authorization", string.Format( "Bearer {0}", Credentials.access_token ) );
            _Request.KeepAlive = false;
            _Request.Method = "GET";

            _Response = _Request.GetResponse() as HttpWebResponse;
            _TwitterResults = (TwitterResults)_JsonSerializer.ReadObject( _Response.GetResponseStream() );
            _ReturnValue.AddRange( _TwitterResults.statuses );
        }

        return _ReturnValue;
    }

    public List<Tweet> GetLatestSince( string p_Query, long p_SinceId, int p_Count = 100 ) {
        TwitterResults _TwitterResults;
        List<Tweet> _ReturnValue = new List<Tweet>();
        DataContractJsonSerializer _JsonSerializer = new DataContractJsonSerializer( typeof( TwitterResults ) );

        HttpWebRequest _Request = WebRequest.Create( string.Format( "{0}?q={1}&result_type=recent&count={2}&since_id={3}", BASE_SEARCH_URL, p_Query, p_Count, p_SinceId ) ) as HttpWebRequest;
        _Request.Headers.Add( "Authorization", string.Format( "Bearer {0}", Credentials.access_token ) );
        _Request.KeepAlive = false;
        _Request.Method = "GET";

        HttpWebResponse _Response = _Request.GetResponse() as HttpWebResponse;
        _TwitterResults = (TwitterResults)_JsonSerializer.ReadObject( _Response.GetResponseStream() );
        _ReturnValue.AddRange( _TwitterResults.statuses );

        while( !string.IsNullOrWhiteSpace( _TwitterResults.search_metadata.next_results ) ) {
            _Request = WebRequest.Create( string.Format( "{0}{1}", BASE_SEARCH_URL, _TwitterResults.search_metadata.next_results ) ) as HttpWebRequest;
            _Request.Headers.Add( "Authorization", string.Format( "Bearer {0}", Credentials.access_token ) );
            _Request.KeepAlive = false;
            _Request.Method = "GET";

            _Response = _Request.GetResponse() as HttpWebResponse;
            _TwitterResults = (TwitterResults)_JsonSerializer.ReadObject( _Response.GetResponseStream() );
            _ReturnValue.AddRange( _TwitterResults.statuses );
        }

        return _ReturnValue;
    }

    public void Dispose() {
        HttpWebRequest _Request = WebRequest.Create( BASE_INVALIDATE_URL ) as HttpWebRequest;
        _Request.KeepAlive = false;
        _Request.Method = "POST";
        _Request.Headers.Add( "Authorization", string.Format( "Basic {0}", BearerTokenCredentials ) );
        _Request.ContentType = "application/x-www-form-urlencoded";

        byte[] _Content = Encoding.ASCII.GetBytes( string.Format( "access_token={0}", Credentials.access_token ) );
        using( Stream _Stream = _Request.GetRequestStream() )
            _Stream.Write( _Content, 0, _Content.Length );

        try {
            _Request.GetResponse();
        } catch {
            // The bearer token will time out if this fails.
        }
    }
}

Twitter uses something OAuth2-ish.  You have to login before you do ANYTHING else. This is what the constructor of the above class does. When you do that, you get back an access token.  It's a simple little JSON object that easily deserializes into the following little class.
    [DataContract]
public class AccessToken {
    [DataMember]
    public string token_type;

    [DataMember]
    public string access_token;
}

Once you have the correct credentials, you use THOSE to access things. Unfortunately, the JSON objects you get back from a query are huge. I had to create 17 different classes to deserialize the entirety of it. I'll look at putting that library up on github.
As you see in the Dispose, I don't care if the auth token fails. The credentials they give you time out after 8 hours.


text:
Q: Url key word argument within CreateView How do I get a URL keyword argument with get() or another method of CreateView? I tried to use self.kwargs['arg_name'], but without result.
Thank you in advance.

A: You can access url keywords in view by using following code
Method one
To access the url parameters in class based views, use self.args or self.kwargs so you would access it by doing self.kwargs['user_id']
url(r'^users/(?P<user_id>[0-9]+)/$',
views.your_view_name.as_view()),

In youe views.py:
class your_class_name(CreateView):
    def view_name(self):
        upk=self.kwargs.get['user_id']
        print user_id
        ...

Method 2
If you are passing keyword in url like this
/your_url?user_id=1

views.py
def view_name(request):
    user_id = request.GET.get('user_id')
    print user_id
    ....

Reference from Stackoverflow Link
hope this helps you

A: Do you mean this ?
class CreateMessageView(LoginRequiredMixin, CreateView):

    def get(self, request, *args, **kwargs):
        ret = super(CreateMessageView, self).get(request, *args, **kwargs)
        upk=self.kwargs['user_id']
        return ret

I have tested it... working ... NIKHILS RANEs answer is somewhat correct. this line  upk=self.kwargs['user_id'] differs from his upk=self.kwargs.get['user_id']. Maybe thats your problem


text:
Q: In plantuml, what does WARNING : CROSSX warn about? In plantuml, I got a strange warning. I have tracked down the source problem to: when creating a sequence diagram with broken arrow from one item back to itself.
The minimal example
@startuml
self ->x self:
@enduml

yields this warning:
$ plantuml minimal.plantuml
WARNING : CROSSX
WARNING : CROSSX

But is still able to generate the image I expect.

What is plantuml complaining about? What is the meaning of this warning?
$ plantuml -version
PlantUML version 1.2018.13 (Tue Nov 27 02:11:51 JST 2018)
(GPL source distribution)
Java Runtime: OpenJDK Runtime Environment
JVM: OpenJDK 64-Bit Server VM
Java Version: 11.0.11+9-Ubuntu-0ubuntu2.20.04
Operating System: Linux
OS Version: 5.8.0-48-generic
Default Encoding: UTF-8
Language: en

A: This warning exists in older versions still included in by major linux distributions.
the warning was generated in src/net/sourceforge/plantuml/sequencediagram/graphic/Step1Message.java
 if (m.getArrowConfiguration().getDressing2().getHead() == ArrowHead.CROSSX) {
            result = result.withHead2(m.getArrowConfiguration().getDressing2().getHead());
            System.err.println("WARNING : CROSSX");
        }
        result = result.withPart(m.getArrowConfiguration().getPart());
 }

Without any clue in the commit message it was removed from upstream in September 2019


text:
Q: Error connecting to SQL Server 2008 R2 Express I have installed SQL Server 2008 R2 Express on Windows 7.
When I run a web project in VS2010 I receive the following error:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

Strange, I am working on the local machine (VS2010, IIS, SQL Server, etc. no network needed).
I googled around and followed many tips. Nothing helps.
I use the correct instance name (e.g. like Data Source=PCName\SQLServer;Initial Catalog=SampleDBName;Integrated Security=True)
Gave the Network Service the right credentials, etc. etc. etc.
I am lost now and having this problem for a week now. Pulling my hair out!
Update:
I got a tip to test my connection string with  SQL Server Management Studio Express. In the Connect popup screen you usually use the Login tab (first and default tab). You can also use the third tab 'Additional Connection Parameters'. I tested my connect string and it just works fine!
So, I think it's something with rights. But I have no idea what or which ...
O yeah. Some extra info.
I changed Application pools default options for IIS 7.5 from 'ApplicationPoolIdentity' to 'NetworkService'. I added the Network Service as login to SQL, gave grant rights, etc.
I turned SQL Browser service on, the service is running (but it is not really necessary because I run local).
Update 2:
It's seems like I found what causes the error, but I have no clue why.
For my website I created a website with some virtual folders and applications. I need an url in my logic. Therefor I use a host header (like http://server.name.tld)
In VS2010 I configured Property pages -> start options -> use custom web server with the url (same as the earlier mentioned host header).
If I do that I get the error.
If I use use Property pages -> start options -> default web server, it seems that I get a connection to the db.
But I need the use of the host header.
What do I need to do, to get the 'custom web server' working?
Update 3:
Tried today also with a test virtual machine with windows server 2008. Still getting the error.
Also made a test web application, without an IIS site an without a host-header. That one works just fine (using the same connectstring). Also on the VM.
I am lost. I really need someone who can exchange some knowledge to me in this field ...

A: Did you try to use SQLExpress  as instance name in the connection string?
PCName\SQLExpress

Moreover check if your server is configured to accept connections via TCP/IP (check Sql Server Configuration Manager). Can you connect to your database using SQL Server Management Studio? Test your connection from Visual Studio, does it work?

A: Named instances that aren't using a TCP binding are usually referenced as .\[instance name], such as .\SQLExpress or perhaps .\SQLServer in your example.

A: red cheeks
Found the problem. Web.config configured with a session db, but no session db created and wasn't planning any longer to do so. Forget to turn it off ...


text:
Q: How do I make my location class send the coordinates via SMS? I'm having difficulties in sending my location coordinates via SMS. I can't frame the sending SMS correctly. Here is my top code:
private static final int REQUEST_CODE = 1000;

FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_CODE:
        {
            if(grantResults.length > 0)
            {
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {

                }
                else if(grantResults[0] == PackageManager.PERMISSION_DENIED)
                {

                }
            }
        }
    }
}

Here in my onCreate the double && sign reads an unexpected token error. I also think I need to add a private void there but don't know which kind corresponds with sending an SMS.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
    {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
    }
    else
    {

        buildLocationRequest();
        buildLocationCallback();
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        {
        if (ActivityCompat.checkSelfPermission(FullscreenActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            && ActivityCompat.checkSelfPermission(FullscreenActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
            ActivityCompat.requestPermissions(FullscreenActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
        return;
    }
    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());

    }

    FusedLocationProviderClient provider = fusedLocationProviderClient;

    Location currentLocation = new Location(String.valueOf(provider));
    location("MY_PHONE_NUMBER", currentLocation);

After the onCreate section is where I'm having the most dificulties at particularly with the location method at the Location currentLocation string which says parameter is never used and I also get an error with the getLongitude closing. It contains an error with the semi-colon and nothing I add there works such as a ). I don't know if I'm doing this location/SMS class correctly.
private void location(String phoneNumber, Location currentLocation) {
    SmsManager smsManager = SmsManager.getDefault();
    String smsBody = "maps.google.com?q=";
    smsManager.sendTextMessage(phoneNumber, null, smsBody, null, null);
}

private void buildLocationCallback() {
    locationCallback = new LocationCallback()
    {

        @Override
        public void onLocationResult(LocationResult locationResult) {
            for(Location location:locationResult.getLocations())
                SmsManager.getDefault(String.valueOf(location.getLatitude())
                        +","
                        +String.valueOf(location.getLongitude());
        }
    };
}

private void buildLocationRequest() {
    locationRequest = new LocationRequest();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(100);
    locationRequest.setFastestInterval(50);
    locationRequest.setSmallestDisplacement(10);
}

A: Add getLastLocation() method after buildLocationCallback
private void getLastLocation() {
    try {
        fusedLocationProviderClient.getLastLocation()
                .addOnCompleteListener(new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful() && task.getResult() != null) {
                            mLocation = task.getResult();
                            location("MY_PHONE_NUMBER", task.getResult());
                        } else {
                            Log.w(TAG, "Failed to get location.");
                        }
                    }
                });
    } catch (SecurityException unlikely) {
        Log.e(TAG, "Lost location permission." + unlikely);
    }
}

update your location method
private void location(String phoneNumber, Location currentLocation) {
    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNumber, null, "maps.google.com?q=" + currentLocation.getLatitude() + "," + currentLocation.getLongitude(), null, null);
        Toast.makeText(getApplicationContext(), "SMS Sent!",
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),
                "SMS faild, please try again later!",
                Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}


text:
Q: $F_X=\lambda F_{X_{d}}+(1-\lambda)F_{X_{c}}$: Conditions on $f_X$ for $F_X$ to be a distribution? Let's suppose we have $I_i=]a_{i-1},a_i[, i\in \{1,...,n\}$, with $a_0=-\infty$ and $a_n=+\infty$.
Let $f$ be continuous on its domain which is $\bigcup_{i \in \{1,...,n\}}I_i$. With $F(x)=\int^x_{a_0}f(u) du$.
Let $F_X=\lambda F_{X_{d}}+(1-\lambda)F_{X_{c}}$, where $X_{d}$ is a discrete r.v. with mass points at the $a_i$'s, and $X_{c}$ is a continuous r.v. and $\lambda \in ]0,1[$?
If I want to be sure that $F_X$ is distribution function, what conditions must $f_X$ satisfy?
Let's assume I'm using Riemann integrals. I'm interested in answers assuming knowledge only of calculus and 1st probability course.
Any help would be appreciated.

A: A cumulative distribution function (CDF) $\Phi$ must have the following properties:

*

*non-decreasing, i.e. $y\geq x\implies \Phi(y)\geq \Phi(x)$;

*right-continuous, i.e. $\displaystyle \lim_{x\to x_0\\ x>x_0}\Phi(x) = \Phi(x_0)$;

*has limit $0$ at $-\infty$;

*has limit $1$ at $+\infty$.

For every pair of CDFs $(F_{X_d}, F_{X_c})$, all properties 1.-4. are satisfied by $F_{X_d}$ and $F_{X_c}$. Using the definitions, one shows that every convex linear combination $\lambda F_{X_d} + (1-\lambda) F_{X_c}$ with $\lambda \in \left[0,1\right]$ of two CDFs $F_{X_d}$ and $F_{X_c}$ is a CDF (independently on the type of variables ${X_d}$ and ${X_c}$). As specified in the comments, the distribution $f_X$ defined by $F_X(x) = \int_{-\infty}^x f_X$ just needs to satisfy the non-negativity and $\int_\Bbb{R} f_X = 1$ properties, since $F_X$ is already a CDF.


text:
Q: Dynamically include files in MSI setup I am trying to deploy a bunch of files in a directory in my MSI setup. As the files will change frequently I don't want to add the files directly but rather have a way of automatically including all files from within a directory and deploy them to a certain location.
I am using a Visual Studio Setup Project.
Anybody know how/if this is possible?

A: I solved the problem by a workaround:

*

*Add a build action of packaging entire directory (could be filtered) to a ZIP file.

*Add a reference to an empty ZIP file to deployment project.

*Add a custom action to deployment project to extract the ZIP to destination folder.

It's simple and stable.

A: Using what????
WiX? InstallShield? Visual Studio? WISE? InstallAware? MSI Factory? Some other Windows Installer tool?

*

*InstallShield - yes. Add a 'dynamic folder' to your setup.

*WiX - kind of. Use heat to generate (partial) WiX sources before calling candle/light.

A: I did this in NSIS by generating part of my NSIS script in Perl and having a master script which included the dynamic script.
Short answer: it's definitely possible.

A: select the folder path and pass to this method.It will create the msi file in the order in which folder hierarchy exists.
public class InstallData
    {
        public void GetWixData(string SourcePath)
        {
         try
            {
                WixEntity[] weDir = new WixEntity[0];
                weDir = BuildDirInfo(SourcePath, weDir);
            var project = new Project("My Product", new Dir("MyDB", weDir), new ManagedAction("MyAction"))
            {
                GUID = Guid.NewGuid(),
                UI = WUI.WixUI_InstallDir,
                Manufacturer = "xxx Inc.",

            };

            try
            {

                Compiler.BuildMsi(project, Application.StartupPath);
            }

            catch (Exception ex)
            {
            }

        }

        catch (Exception Ex)
        {

        }
    }

    private WixEntity[] BuildDirInfo(string sRootDir, WixEntity[] weDir)
    {
        DirectoryInfo RootDirInfo = new DirectoryInfo(sRootDir);
        if (RootDirInfo.Exists)
        {
            DirectoryInfo[] DirInfo = RootDirInfo.GetDirectories();
            List<string> lMainDirs = new List<string>();
            foreach (DirectoryInfo DirInfoSub in DirInfo)
                lMainDirs.Add(DirInfoSub.FullName);
            int cnt = lMainDirs.Count;
            weDir = new WixEntity[cnt + 1];
            if (cnt == 0)
                weDir[0] = new DirFiles(RootDirInfo.FullName + @"\*.*");
            else
            {
                weDir[cnt] = new DirFiles(RootDirInfo.FullName + @"\*.*");
                for (int i = 0; i < cnt; i++)
                {
                    DirectoryInfo RootSubDirInfo = new DirectoryInfo(lMainDirs[i]);
                    if (!RootSubDirInfo.Exists)
                        continue;
                    WixEntity[] weSubDir = new WixEntity[0];
                    weSubDir = BuildDirInfo(RootSubDirInfo.FullName, weSubDir);
                    weDir[i] = new Dir(RootSubDirInfo.Name, weSubDir);
                }
            }
        }

        return weDir;
    }
}

public class CustomActions
   {
       [CustomAction]
       public static ActionResult MyAction(Session session)
       {
           MessageBox.Show("Hello World!", "Embedded Managed CA");
           session.Log("Begin MyAction Hello World");
       return ActionResult.Success;
   }

}


text:
Q: Screenshot of test application in Appium Inspector I have launched an android emulator (avd) with appium using selenium webdriver (python script) on mac os x.
It installs a test application and opens it.
When I open the appium inspector it does not show any screenshots of the application. What should I do to see the application screenshot in Appium Inspector? the avd is of api level 19.

A: I believe you have checked "Emulation Option" "Use Host GPU option"?
If yes; that could be the reason you are not seeing screenshot. Edit/create the AVD without "Emulation Option" "Use Host GPU option" checked as shown in image:


text:
Q: Angular Frontend display Laravel backend stored image I want to display image in frontend (Angular).But that image stored in Laravel(5.5) backend.I already try.What should i do?

This is error

A: If your image stored in Storage folder of Laravel.Then create this route in route route.php (if your using above Laravel 5.4, in web.php)
Route::get('images/{filename}', function ($filename)
{
    $file = \Illuminate\Support\Facades\Storage::get($filename);
    return response($file, 200)->header('Content-Type', 'image/jpeg');
});

Now you can load your image using this route like this.

If image stored in public folder, you can load it directly

You need to run both of your Laravel(Backend) and Angular(Frontend) Application same time (based on your code)

A: The storage_path()
function returns the fully qualified path to the storage directory:
$path = storage_path();

Then:

or

Is probably better practice. You also need the file extension.


text:
Q: Ajustes no CSS do React.JS Estou desenvolvendo um sistema simples no react e estou com dificuldades na parte visual, por exemplo para o mobile:
Preciso deixar meu sistema dessa forma:

Está dessa forma:

O sistema da web precisa ser desse jeito:

O meu, na web, fica assim:

Como posso colocar o conteúdo logo abaixo do ícone e ocupar o espaço restando ao lado do ícone no mobile e mudar a forma do design na web? Caso a solução seja somente no design que preciso do mobile, já está ótimo.
Um exemplo do JS de um widget qualquer:
import React from 'react';

const WidgetOrder = (props) =>(

          {props.title}
          New Orders

);
export default WidgetOrder;

A função render do Home.JS:
  render(){
    return(

          <WidgetOrder title={this.state.data.newOrders} //apos DATA. vai as tags do JSON pra pegar
           />
           <WidgetCom title={this.state.data.comments}
            />
            <WidgetUser title={this.state.data.newUsers}
             />
           <WidgetView title={this.state.data.pageViews}
            />

    );
  }

Html da página em questão retirada do f12 do Chrome:

.logo-Order {
  background-color: #00c3ff;
  color: #fff;
}

.row {
  text-align: center;
}

.info-box-content {
  padding: 5px 22px;
  margin-left: 90px;
}

.info-box {
  display: block;
  min-height: 90px;
  background-color: #FFFFFF;
  width: 100%;
  border-radius: 6px;
  margin-bottom: 15px;
}

.info-box-text {
  display: block;
  font-size: 14px;
}

.info-box-number {
  display: block;
  font-size: 25px;
}

.info-box-icon {
  display: block;
  float: left;
  height: 90px;
  width: 90px;
  font-size: 45px;
  line-height: 90px;
}

            132
            NewOrders

            58
            Comments

            26
            News Users

            18962
            Page Views

Comecei a estudar React recentemente e peguei os modelos prontos.

A: Suas Divs estão com Display: Block; tente usar Display: flex; depois insira o flex-direction: row (Acho que o padrão é Collumn); feito isso é só ajustar as divs que estão por dentro colocando o tamanho fixo na Div que contem a imagem e Width e Height de 100% para a outra div.


text:
Q: How to give an variable inside pmax() in R Suppose if I have a data iris and I want to apply pmax() to a list of dynamic columns.
Ex:
DT <- as.data.table(iris)

example_column <- c("Petal.Width")

DT[, test_flag :=
     ifelse(pmax(substitute(example_column), Petal.Length) > 0, "Exclude", "Consider")]

But I am not able to pass example_column as an dynamic argument to pmax().

A: We can use do.call with .SDcols if you have more than 1 column in example_column.
library(data.table)
DT <- as.data.table(iris)
example_column <- c("Petal.Width")

DT[, test_flag := ifelse(do.call(pmax, .SD) > 0, "Exclude", "Consider"),
                  .SDcols = c(example_column, 'Petal.Length')]

For single column using get is enough.
DT[, test_flag :=
     ifelse(pmax(get(example_column), Petal.Length) > 0, "Exclude", "Consider")]


text:
Q: Cassandra UnavailableException with one node up and replication factor is 1, ordered partitioned
Hello, I got a problem when getting some data from Cassandra.
My cluster had following attributions:
1. Ordered partitioner. The cluster had 10 nodes, and using ByteOrderedPartitioner.
2. Replication was 1. The cluster was in SimpleStrategy with replication factor is 1.
When I started up only a node, and to get some data from that node(I was sure that the desired data was stored in the only started node), UnavailableException throwed.
Anybody could give some suggestions? Thanks a lot.


text:
Q: How to get the file name in iPhone sdk? I stored a pdf file using NSData in my application memory. Now i want that file name each time to add those names into an array. How can i get the pdf file's name from my application memory to use in my app.

A: You can't since you only stored the file as a data object and not it's file name.
You could try to read the PDF meta data to check if there's a file name.

A: The answer here should help:
Getting a list of files in the Resources folder - iOS
It will list all the files in the Documents dir.

A: I suppose by "Application Memory" you mean one of the App's directories like Documents or Library.
You can just use NSFileManager to access the directory and get a list of all files, like if you stored it in your app's library folder:

NSArray* directoryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUSerDomainMask, YES];
NSString* path = [directoryPaths objectAtIndex:0];
NSArray* files = [NSFileManager defaultManager] contentsOfDirectoryAtPath:path];

On top of that you can use a filter predicate to only get files with a .pdf ending.