text:
Q: Some questions of ActionBar on Android I use below code to show action bar:
setTheme(android.R.style.Theme_WithActionBar);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(0x000000));

And it show as below:

And menu.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/a"
        android:icon="@drawable/a"
        android:title="1"
        android:showAsAction="ifRoom|withText" />
    <item android:id="@+id/b"
        android:icon="@drawable/b"
        android:title="2"
        android:showAsAction="ifRoom|withText" />
    <item android:id="@+id/c"
        android:icon="@drawable/c"
        android:title="3"
        android:showAsAction="ifRoom|withText" />
</menu>

*

*I want to set background color list to black.

*I want the order is ActionBar show 1 and 2, and list show 3.
How can I do it?

*I want to change the list icon ob Top-Right.

A: Answer to question 1.
Instead of 0x000000 use android.graphics.Color.BLACK.
See http://developer.android.com/reference/android/graphics/Color.html
Answer to question 2.
Change
<item android:id="@+id/c"
    android:icon="@drawable/c"
    android:title="3"
    android:showAsAction="ifRoom|withText" />

to
<item android:id="@+id/c"
    android:icon="@drawable/c"
    android:title="3"
    android:showAsAction="never" />

See http://developer.android.com/guide/topics/resources/menu-resource.html

A: You can set PopupListView's background using :
<style name="Theme.Play" parent="@style/Theme.Holo.Light">
    <item name="android:popupMenuStyle">@style/PopupMenu.Play</item>
</style>
<style name="PopupMenu.Play" parent="@android:style/Widget.ListPopupWindow">
    <item name="android:popupBackground">@drawable/menu_dropdown_panel_play</item>
</style>

To arrange ActionBar's items you should create your menu like this :
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+id/action_first"
    android:orderInCategory="100"
    android:showAsAction="always"
    android:title="@string/action_first"/>

<item
    android:id="@+id/action_second"
    android:orderInCategory="200"
    android:showAsAction="always"
    android:title="@string/action_secong"/>

<item
    android:id="@+id/action_third"
    android:orderInCategory="300"
    android:showAsAction="collapseActionView"
    android:title="@string/action_third"/>

and to change OverFlow menu's icon you should use this :
<style name="Theme.Play" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionOverflowButtonStyle">@style/OverFlow</item>
</style>

<style name="OverFlow" parent="@android:style/Widget.Holo.Light.ActionButton.Overflow">
    <item name="android:src">@drawable/ic_action_overflow</item>
</style>

A: To set the menu icon try like this one..
public boolean onCreateOptionsMenu(Menu menu) {
         SubMenu sub = menu.addSubMenu(0,Menu.FIRST,1,"Menu").setIcon(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
            sub.add(0, 2, 0, "Settings");
            sub.add(0, 3, 0, "About");
            sub.add(0, 4, 0, "Exit");
            sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
            return true;

    }

Hope it helps


text:
Q: Variable Scope For an Extension Method I have something interesting that I want to understand little deeper.
I have an extension class that extends int:
public static class MyExtension
    {
        public static void GetProp(this int i, MyObject o)
        {
            var val = i;
            o.sum = i;
        }
    }

That uses a class as one of its parameter:
public class MyObject
    {
        public int sum { get; set; }
    }

Now, lets see the unit test class:
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void test()
        {
            int a = 1;
            int b = 2;
            int sum = 0;
            Add(a, b, sum);

//Here, sum=3 but after its execution, sum looses its value and
  retains the value sum = 0

            int test = 4;
            MyObject obj = new MyObject();
            test.GetProp(obj);

But in the above code when I pass the variable using the extension
  method, the obj.sum retains its value obj.sum = 4 . I am not passing any
  value by reference. The first portion of code seems to follow the
  passing ByVal. But the second portion of extension method, the value
  is retained as if its passed as ByRef

            string s = sum.ToString();
            string p = obj.sum.ToString();
        }

        private void Add(int x, int y, int sum)
        {
            sum = x + y;
        }
    }

Can someone explain the mechanism behind this. Thanks

A: All parameters are send by value, unless you specify them with the ref or out keyword. Passing a parameter by value means that the value is copied.
However, when you pass an object by value it's not the object that is copied, it's the reference that is copied. That means that you have two references to the same object, one in the obj variable and one in the o parameter, but only one object.
When the extension method accessed the object, it's the same object as outside the method. Any change to the property made using the o parameter will be visible when you later access it using the obj variable.

A: This is the difference between passing by reference and passing a reference object (class). In GetProp, you aren't modifying the reference obj, you are modifying the MyObject instance that is referred by obj.

A: If I understand your question, you're confused about why the sum variable isn't changed when it is passed by value, but the obj.sum property does retain its value when obj is passed by reference. The other answers do a good job of explaining this.
In your question, you pass a parameter by value as a receiver, and this confuses your question a bit. Your question appears to be, "why is it that when I pass normally, it's treated as by-value, but when I pass as a receiver to an extension method, it's by-reference?"
Ah. Try assigning a new value to the receiver and see what happens at the call site:
    public static void GetProp(this int i, MyObject o)
    {
        o.sum = i;
        i = 5000;
    }

You'll find that the variable test at the call site is not affected by this, since the receiver is also passed by value!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I know if a QWebPage has finished loading? Other than connecting a slot with QWebPage::loadFinished(), is there a way to poll its status? I didn't find a function that returns directly the percentage of it.

A: You could connect to the loadProgress signal on QWebPage like so:
connect(webView, SIGNAL(loadProgress(int)), this, SLOT(loadProgress(int)));

This will report the percentage loaded as progress increases.


text:
Q: How to make copy of Visual Studio 2019 project? I have a Visual Studio 2019 project. Was asked to make trial changes. Do not want to alter current project. Is there any way to copy a project so I do not have to start over from scratch?
Searched here and other forums and documentation and cannot find solution.

A: Short answer: you can very simply copy the directory in which your project reside on disk. Open the new directory and double click on the .csproj file and you are now working in your new copy of the project. But, if you want to do that in a more professional and maintainable way, please read on...

The best way to do that in a more robust way is using Git.
In the bottom right corner of Visual Studio find the "Add to Source Control" command, click it, then choose Git. Now the command says "master", that is your main "copy" of the project: in Git, this is called your main "branch".
Now click on it, choose "New branch", give it a name (e.g.: trial), leave the checkbox "Checkout branch" checked, then click on "Create branch". Now the command in the right bottom has changed to "trial".
Now you have another copy of your project: you can work on it, save your work on local disk. When you are ready to save it in Git, press the pencil icon, that is located in the bottom toolbar, on the right, near the command you used before (the number near it shows how many files you have changed): click it, enter a "commit message", then click on "Commit all". Now you have saved all your work in the trial "branch" of your project in Git.
If you want to come back to your initial copy of the project, click on "trial", then choose "master", and voila... your are now working on the old copy or your project. You can switch between the two branches anytime, only remember that, before switching, you have to "commit" your changes, that is, save them in Git, as I explained above.
At some point, you may want to bring the changes you made in trial to master. To do so, when you are working in master, click on master (always in the bottom toolbar, on the right), then choose "Manage branches", then right click on "trial", click on "Merge from...", then click the Merge button: you have now brought the changes made on trial into master. The only problem can arise if you have changed a file both in master and in trial, and the changes are conflicting: in this case, VS will warn you, show you the conflicting changes, and you will have to choose which version of the conflicting changes you want.

A: If one don't want or can't use git, one can also copy and paste the project folder. Once in the new folder, Here is what I usualy do (I assumed the old project is named "projectOld" and new one "projectNew").
 :

*

*rename projectOld.sln to projectNew.sln

*open projectNew.sln and change the following line in order to set the new project name :

Project("{C9CE8BB8-8B4A-11D0-5E31-C9100A0BC942}") = "projectNew", "projectNew.vcxproj", "{66F6A241-22E1-4941-6DA3-B6D9E7A8AF86}"

*

*rename projectOld.vcxproj to projectNew.vcxproj

*open projectNew.vcxproj and change the lines with the <!-- here --> comments

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  [...]
  <PropertyGroup Label="Globals">
    [...]
    <RootNamespace>projectNew</RootNamespace>                 <!-- here -->
    [...]
    <ProjectName>projectNew</ProjectName>             <!-- here -->
  [...]
  <ItemGroup>
    <ClCompile Include="..\..\..\..\..\IncludePath(1)\ImplementatFile(1).cpp" />  <!-- here -->
    [... up to last]
    <ClCompile Include="..\..\..\..\..\IncludePath(n)\ImplementatFile(n).cpp" />
    [...]
  <ItemGroup>
    [same thing for every ItemGroups]                 <!-- here -->
  [...]

*

*rename projectOld.vcxproj.filters to projectNew.vcxproj.filters

*rename projectOld.vcxproj.user to projectNew.vcxproj.user

*one can delete the Debug and X64 folders, they will be created again by mvsc.

A: Yes, with GIT branching you can create variations of a project easily.
But I think that was not the core of the question asked, because if you create a branch, it is kept separate.
I had a similar scenario where I needed a similar project in the same solution (code first database). A clone of the database project to start with and make some changes for a different database. So in the end I wanted to have 2 databases, not identical but similar, in the same solution.
Adding a new project in the solution and then copying the .CS-Files is possible but cumbersome because of the references and dependencies.
So what I did is:

*

*Close Visual Studio

*Open the file explorer and copy the entire folder (e.g. MyProjectA), rename the copy (e.g. to MyProjectB)

*Rename the .csproj project file of the copied project MyProjectB. Then open it with a text editor of your choice, to see if you need to adapt anything (for example, project references if you moved it to a different directory level; they usually refer to a different project with a relative path, e.g. <ProjectReference Include="..\SomePathOfADifferentProject\SomeProject.csproj"/>)

*Open Visual Studio, load the solution

*In the solution explorer, right click on the solution, select "Add existing project...". Now browse for MyProjectB to add it as existing project

and you're done!
If you're using source control like GIT, make sure to check if the clone was correctly added (i.e. check if the files are tracked by source control).

A: I suggest you go with Project Template inside Visual Studio. You create a project template, store it somewhere, then create a new project by using the stored template. Here are more details
https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/ms247121(v=vs.100)?redirectedfrom=MSDN


text:
Q: Which HTTP code to use, in a REST API, for a subresource if the parent resource doesn't exist? My team and I are coding a REST API, but some concepts are still not fully understood.
In a given resource: objective/{id}/goal where goal is collection
If the consumer tries to reach an objective that doesn't exist, the API will return status code 404, pretty simple.
ex: objective/999 returns 404
For some reason the consumer tries to fetch the goals from this non existing resource:
ex: objective/999/goal returns ?
Which is the most suitable code to return? I have a feeling that this should be a 404 too. Some people are considering another error code, because the API should somehow inform that the parent resource doesn't exist in the first place.

A: Use 404. Keep in mind that a 404 response may contain a response body. So you could respond with something like the following:
Request
GET /objective/7/goal

Response
404 Not Found
{
    "type": "ParentNotFound",
    "description": "The parent resource was not found.",
    "parent_uri": "/objective/7"
}

In general, it's a good idea to include some kind of response body for error status codes.  Even when the error status code is being used in a standard way, it's still nice as the API client to see a human message about why I'm seeing the error. The benefit is even greater when the error status code is being used in an almost standard yet slightly off way.


text:
Q: python scrapy only pulling first row but repeating for the correct amount of items in the table like the title says. my scrapy code seems to be running correctly except it is pulling only the first row of table and repeating it for the amount of rows in the table.

import scrapy

class FightersSpider(scrapy.Spider):
    name = "fighters"

    start_urls = [
        'http://www.ufcstats.com/statistics/fighters?char=a&page=all'
    ]

    def start_requests(self):
        urls = [
            'http://www.ufcstats.com/statistics/fighters?char=a&page=all'
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response, **kwargs):
        for fighter in response.xpath('//*[@class="b-statistics__table"]//tbody/tr'):
            yield {
                'first': fighter.xpath('//td[1]/a//text()').extract_first(),
                'last': fighter.xpath('//td[2]/a//text()').extract_first(),
                'nickname': fighter.xpath('//td[3]/a//text()').extract_first(),
                'height': fighter.xpath('//td[4]//text()').extract_first().strip(),
                'weight': fighter.xpath('//td[5]//text()').extract_first().strip(),
                'reach': fighter.xpath('//td[6]//text()').extract_first().strip(),
                'stance': fighter.xpath('//td[7]//text()').extract_first().strip(),
                'wins': fighter.xpath('//td[8]//text()').extract_first().strip(),
                'losses': fighter.xpath('//td[9]//text()').extract_first().strip(),
                'draws': fighter.xpath('//td[10]//text()').extract_first().strip(),
            }

if i take out the _first it pulls all of the data but puts it in the same cell and repeats the same way.

first   last    nickname    height  weight  reach   stance  wins    losses
Tom Aaron   The Assassin    --  155 lbs.    --      5   3
Tom Aaron   The Assassin    --  155 lbs.    --      5   3
Tom Aaron   The Assassin    --  155 lbs.    --      5   3
Tom Aaron   The Assassin    --  155 lbs.    --      5   3
Tom Aaron   The Assassin    --  155 lbs.    --      5   3
Tom Aaron   The Assassin    --  155 lbs.    --      5   3
Tom Aaron   The Assassin    --  155 lbs.    --      5   3
Tom Aaron   The Assassin    --  155 lbs.    --      5   3
....

A: You have to use relative xpath to search only inside fighter - it has to start with dot
fighter.xpath('.//td[1]/a//text()')

Without dot it is absolute xpath and it searchs in all HTML and it always finds first row.

But then you will have other problem.
You get all rows in table - even header which doesn't have td - and you have to skip it. You can slice it with [1:]
for fighter in response.xpath(...)[1:]:

Minimal working code.
You can copy all to file and start it as normal script python script.py without creating project in scrapy
import scrapy

class FightersSpider(scrapy.Spider):
    name = "fighters"

    start_urls = [
        'http://www.ufcstats.com/statistics/fighters?char=a&page=all'
    ]

    def start_requests(self):
        urls = [
            'http://www.ufcstats.com/statistics/fighters?char=a&page=all'
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response, **kwargs):
        for fighter in response.xpath('//*[@class="b-statistics__table"]//tbody/tr')[1:]:
            print(fighter.xpath('.//td[4]'))
            yield {
                'first': fighter.xpath('.//td[1]/a//text()').extract_first(),
                'last': fighter.xpath('.//td[2]/a//text()').extract_first(),
                'nickname': fighter.xpath('.//td[3]/a//text()').extract_first(),
                'height': fighter.xpath('.//td[4]//text()').extract_first().strip(),
                'weight': fighter.xpath('.//td[5]//text()').extract_first().strip(),
                'reach': fighter.xpath('.//td[6]//text()').extract_first().strip(),
                'stance': fighter.xpath('.//td[7]//text()').extract_first().strip(),
                'wins': fighter.xpath('.//td[8]//text()').extract_first().strip(),
                'losses': fighter.xpath('.//td[9]//text()').extract_first().strip(),
                'draws': fighter.xpath('.//td[10]//text()').extract_first().strip(),
            }

# --- run without project and save in `output.csv` ---

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',
    # save in file CSV, JSON or XML
    'FEEDS': {'output.csv': {'format': 'csv'}},  # new in 2.1
})
c.crawl(FightersSpider)
c.start()


text:
Q: iOS: Using vector data in MKOverlay in MapKit I'd like to overlay a custom map using MapKit. I've currently implemented the TileMap sample from WWDC10. However, my overlay map is in vector form (pdf) and it seems like a terrible waste to rasterise it and convert it to tiles (also takes up about 10megs as opposed to 300KB).
Is there a way to either:
a) overlay a pdf using MKOverlay, or
b) easily convert a vector graphic into MKPolygons, lines etc., so I can recreate my overlay map in MapKit?
Notes: The map I'm trying to overlay is pretty simple but geographically huge. It does need to work offline.

A: You can overlay a PDF using MKOverlay. In the drawMapRect:zoomScale:inContext: method of your MKOverlayView just use standard PDF drawing functions. You can find those functions here.
The problem with this approach is that for each maprect that is sent to that drawing method you will have to draw the entire PDF each time. This will be really slow. I think you will see the best performance by rasterizing the PDF and converting it to tiles. 10 MB is not too large of a dataset to ship with an iOS app.


text:
Q: Cava Packger executable (made from perl) not working in 64 bit Ubuntu 14.04 I have prepared executable from my perl code for distribution
It works fine on my own ubuntu 12.04 where it was created
It should work without perl on any system
But After execution of executable on Ubuntu 14.04 LTS, (64 bit) it gives
Error:
Can't load '/home/osboxes/Version-1/lib/vrt/16e8aba612e215bf6a5195289f1a16d8/Prima.so' for module Prima: libgif.so.4: cannot open shared object file: No such file or directory at <content>/DynaLoader.pm line 157.

After installing libgif4 it gave error
libtiff.so.4: cannot open shared object file: No such file or directory

What may be the cause for this and solution for this.

A: Ubuntu 14.04 LTS includes libtiff5 by default. Versions up to 13.04 had libtiff4. I made the executable compatible with libtiff4. also just installing libtiff4 by Ubuntu Software Center did not help so I installed it manually.
Downloaded it from here and installed by command:
sudo dpkg -i ./libtiff4_3.9.7-2ubuntu1_amd64.deb


text:
Q: Insert list into MySQL database using Python I am doing a classification using k-nearest neighbor with python. The data I am using is float type, latitude and longitude and get the output from it like this:
prediction
preds2 = model.predict(new_list)
print(type(preds2))
print(preds2)
print("-----------")
print(new_list)
print(type(new_list))
print("-----------")

Output prediction not merged
<class 'numpy.ndarray'>
['Taman Suaka Margasatwa Angke' 'Taman Suaka Margasatwa Angke']
-----------
[[-6.1676580997222, 106.9042428], [-6.1676580997222, 106.9042428]]
<class 'list'>

Merge them together
mergedata = [[*new_list, preds2] for new_list, preds2 in zip(new_list, preds2)]
print(mergedata)

output from mergedata
[[-6.1676580997222, 106.9042428, 'Taman Suaka Margasatwa Angke'], [-6.1676580997222, 106.9042428, 'Taman Suaka Margasatwa Angke']]

I want to store the output from mergedata to database mysql so this is the code that I've tried
import mysql.connector

connection = mysql.connector.connect(host='localhost',
                                         database='destinasi',
                                         user='root',
                                         password='')

mycursor = connection.cursor()
myArray = mergedata
arraySize = len(myArray)
for r in range(0,arraySize):
    try:
        mycursor.execute(
       """INSERT INTO hasilclass (Latitude,Longitude,Class) VALUES (%s,%s,%s)""",
            (",".myArray[r], )
        )
        connection.commit()
    except:
        print("Error")
        connection.rollback()

The output is:
Error
Error

This is the display of database in mysql
CREATE TABLE `hasilclass` (
  `Latitude` float(15,11) NOT NULL,
  `Longitude` float(15,11) NOT NULL,
  `Class` varchar(55) NOT NULL
)

It seems that mycursor.execute is not executing the mysql statement, i don't know the correct way to do it. Any Suggestions how to correct it? is the statement is false? all the data is from mysql as well but im using pymysql to call all the data and do all the work untill i need to store them to database.
The reference in the internet i found is using mysql.connector to store 2 dimensional list in python so i follow it and it goes error like this.

A: You are trying to build a tuple with a single element. However, it doesn't work the way you want because ",".myArray tries to get a property named myArray from the string ",", but this doesn't exist. Instead, myArray is a global variable that you want to access.
To do this, change
            (",".myArray[r], )

to
            myArray[r]

Also, in Python, we prefer to iterate over the elements of an array directly rather than counting the indexes. This means you can change
arraySize = len(myArray)
for r in range(0,arraySize):

to
for row in myArray:

And now you can simplify your SQL command further:
        mycursor.execute(
            "INSERT INTO hasilclass (Latitude,Longitude,Class) VALUES (%s,%s,%s)",
            row
        )

Finally, a warning that assigning
myArray = mergedata

does not make a copy. This doesn't look like it does much of anything for you so I suggest removing it. Instead, just use mergedata directly:
for row in mergedata:


text:
Q: calling multiple array from subroutines I am only able to print 1st section when I am calling array from subroutine.
Within subroutine I am able to print all the records but when I call same array on top of the script I am only getting below output.
@array = test();
DEBUG(Dumper(\@array);

2014/07/04 1:28:38 $VAR1 = [
          [
            'Router1',
            'Router2',
            'Router3',
          ]
        ];

sub test {
    my @array;
    for my $record (@array) {
        for my $value (@$record) {
            DEBUG("DEBUG: Value of array $value ");
        }
    }
    return (@array);
}

Dumper output is like below:
2014/07/04 1:28:38 $VAR1 = [
          [
            'Router1',
            'Router2',
            'Router3',
          ]
        ];
2014/07/04 1:28:38 $VAR1 = [
          [
            'Switch1',
            'Switch2',
            'Switch3',
          ]
        ];

2014/07/04 1:28:38 $VAR1 = [
          [
            'Switch11',
            'Switch21',
            'Switch31',
          ]
        ];

Expected output:
Router1
Router2
Router3
Switch1
Switch2
Switch3
Switch11
Switch21
Switch31

Thanks.

A: Your subroutine test declares an empty array @array and dumps it. You will get no output because it is empty. The array you are dumping at the start of the program is a different array


text:
Q: can we create a CDN without domain name? I want to create a CDN network without purchasing any domain name, I have Amazon server and i 've installed S3 on that server.
Please tell me is it possible to create CDN without domain name, can we create on IP address?

A: If you create distribution using Amazon CloudFront, you can:

*

*Store objects in one Amazon S3 bucket.

*Distribute download content such as text or graphics.

*Make your objects accessible to everyone.

*Using Amazon CloudFront domain name in URLs for your objects (for example, http://d111111abcdef8.cloudfront.net/image.jpg) instead of your own domain name (for example, http://www.example.com/image.jpg).

*CloudFront edge locations, keep your objects into the default duration of 24 hours for fast content delivery.

If you want to access data using your own domain name (http://www.example.com) then :

*

*You add a CNAME for www.example.com to your distribution, you also need to create (or update) a CNAME record with your DNS service to route queries for www.example.com to d111111abcdef8.cloudfront.net.

*You must have permission to create a CNAME record with the DNS service provider for the domain. Typically, this means that you own the domain, but you may also be developing an application for the domain owner.

Reference : Amazon CloudFront and CloudFront Introduction


text:
Q: Kafka Consumer instances are not reading from partition when the instance which were consuming got crashed I have 3 Consumer instances linked with one Consumer Group. As far as i understood and found we can't have Consumer instances more than no. of Partition in a topic.
I have only one partition in the Topic. So Only one Kafka Consumer instance is consuming messages in three instances of a group. But my worry is when that Consumer gets crashed then the other consumer instances should start reading from that partition, but its not happening.

A: Below things you can check to debug further -

*

*After the crash , new messages are published to be consumed

*After the crash consumer rebalance should get triggered (check the
server logs) and the new partition assignment should happen


text:
Q: explode function in custom function I am trying to create custom function for Main Nav menu where I can only write menu item name and it will automatically wrap with
*my content
Also I want variable where I can define url for each menu item.
below is my code and giving me Parse error: syntax error, unexpected T_VARIABLE
function the_main_nav($navlinks){
        echo '';
        echo '
';

        $menuitem = $navlinks;
        $pieces = explode("," $menuitem);
        echo $pieces[0];
        echo $pieces[1];

        echo $menuitem;
        echo '
';
        return $pieces;
    }

------------------[Modified code]----------------------
function the_main_nav($navlinks){
echo '';
echo '
';

$menuitem = $navlinks;
$pieces = explode(" ",$menuitem);
echo '
';
    echo $pieces[0];
    echo '
';
echo '
';
    echo $pieces[1];
    echo '
';

echo '
';
    echo '';
}

Now I want to make it dynamic like instead of getting value from [0] [1]..so on i want it will automatic generate as per the input character and create list with li

A: You are missing the ,. You have to separate the argument of explode using comma.
$pieces = explode(",", $menuitem);

A: The explode() function breaks a string into an array.
explode(separator, string)
so in your code comma is missing.


text:
Q: Proof that any line segment has exact one midpoint. The line segment $\overline{AB}$ is defined as $\{x \in U;X=A, or X=B, or A-X-B\}$ such that $U$ is the universal set of all points.
Now consider two distinct midpoints $C$ and $D$ that are elements of the segment $AB$ such that $C$ and $D$ are between $\overline{AB}$ By the definition of midpoint you have that $\overline{AC}=\overline{CB}$ and that $\overline{AD}=\overline{DB}$. Also  $\overline{AC}+\overline{BC}=\overline{AB}$ and $\overline{AD}+\overline{DB}= \overline{AB}$
Then $\overline{AC}+\overline{BC}=\overline{AD}+\overline{DB}$
Then $2\overline{AC}=2\overline{AD}$
Therefore $\overline{AC}=\overline{AD}$
So I want to thus conclude that $C=D$ which is a contradiction so therefore there exists only one midpoint for every line segment.
I need to show existence and uniqueness I don't believe I showed existence very well.


text:
Q: How do I save adapter content in a recycler view so when I close the app and restart the adapter is the same This is my main activity so far
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private List<userTask>  tasklist= new ArrayList<>();
private userTaskAdapter adapter;
//private Context context;
private static Bundle mBundleState;
private final String KEY_RECYCLER_STATE = "recycler_state";
private Parcelable listState;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.recycleOne);

    recyclerView.setHasFixedSize(true);

    adapter = new userTaskAdapter(tasklist);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);
    preparetestdata();

}

private void preparetestdata()
{
    String data = "";

    try {

        InputStream fis = MainActivity.this.getResources().getAssets().open("task.txt");
        DataInputStream in = new DataInputStream(fis);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        while ((data = br.readLine()) != null)
        {
            String delims = "[:]+";
            String[] temp = data.split(delims);
            String tempTask = new String();
            String tempDescription = new String();
            for (int i=0; i < temp.length; i++)
            {
                if(i == 0)
                    tempTask = temp[i];
                else
                    tempDescription = temp[i];
            }
            userTask tempUser = new userTask(tempTask, tempDescription);
            tasklist.add(tempUser);
        }

    } catch (IOException e)
    {
        e.printStackTrace();
    }
}

/**
 * This function will add new task to task list
 * @param v
 */
public void onAdd(View v)
{
    EditText editTaskTitle = (EditText) findViewById(R.id.taskTitle);
    EditText editDescription = (EditText) findViewById(R.id.taskDescription);
    String tname = editTaskTitle.getText().toString();
    String tdescrip = editDescription.getText().toString();
    userTask task = new userTask(tname, tdescrip);
    tasklist.add(task);
    Log.d("Tname :", tname);
    Log.d("tdescription :", tdescrip);
    try {
        FileOutputStream stream = new FileOutputStream(new File(getFilesDir(), "task.txt"));

        int counter =0;
        for (int i =0; i < tasklist.size(); i++)
        {

            String total = tasklist.get(i).getTName() + " : " + tasklist.get(i).getTDescrip() + "\n";
            stream.write(total.getBytes());
            counter++;
        }
        Toast.makeText(this, "got here", Toast.LENGTH_SHORT).show();
        stream.close();
        adapter.notifyDataSetChanged();
        //recyclerView
        Log.d("UpList", String.valueOf(counter));
    }catch(IOException e) {
        e.printStackTrace();
    }
}

/**
@Override
protected void onSaveInstanceState(Bundle state)
{
    super.onSaveInstanceState(state);
    //state.putSerializable("listdata", adapter.);
}**/

@Override
public void onStop()
{
    super.onStop();
    mBundleState = new Bundle();
    listState = recyclerView.getLayoutManager().onSaveInstanceState();
    mBundleState.putParcelable(KEY_RECYCLER_STATE, listState);

}

@Override
public void onResume()
{
    super.onResume();
    if (mBundleState != null)
    {
        listState = mBundleState.getParcelable(KEY_RECYCLER_STATE);
        recyclerView.getLayoutManager().onRestoreInstanceState(listState);
    }
}

When I add a new task and exits the app that new task will still be in the recycler view. But when I close the app that new task will not still be in the recycler view. I was thinking of saving the state of the adapter but am not really sure how to do this. I tried to do the serializable method but adapters are not serialable


text:
Q: d3.js hierarchical edge bundling: embed json data in variable I would like to read the json data directly in a variable, for instance
var HEBdata = [
{"name":"test.cluster1.item1","imports":["test.cluster1.item2","test.cluster1.item3"]},
{"name":"test.cluster1.item2","imports":["test.cluster1.item3"]},
{"name":"test.cluster1.item3"}
];

I would then use this variable here
d3.json(HEBdata, function(error, classes) {
  if (error) throw error;

Instead of
d3.json("https://gist.githubusercontent.com/mbostock/1044242/raw/8f22cf2264e1f6ec6cb233c4b49333fb8f75bb99/readme-flare-imports.json", function(error, classes) {
  if (error) throw error;

Here is a fiddle with the code that you may change: https://fiddle.jshell.net/d1766z4r/ (the URL has been commented and replaced by the HEBdata variable)
I would like to do this to be able to use custom data to make it simple for another question that I want to ask later on.

A: Don't use d3.json. instead just assign the object to your var classes.
d3.json essentially does this:

loads data into the browser using an XMLHttpRequest, or XHR. This allows data to be loaded asynchronously (so the rest of the page can display while data is loading), and is safer than JSONP. D3's xhr module simplifies loading and parsing data. When loading data asynchronously, code that depends on the loaded data should generally exist within the callback function. Code that doesn't depend on data can run immediately when the page loads.

https://github.com/d3/d3-3.x-api-reference/blob/master/Requests.md
Since you already have your data ready, you don't have to wait to use it. So any code that would normally have to wait to run until the Http response is received can be run straight away like so:

var classes = [
{"name":"test.cluster1.item1","imports":["test.cluster1.item2","test.cluster1.item3"]},
{"name":"test.cluster1.item2","imports":["test.cluster1.item3"]},
{"name":"test.cluster1.item3"}
];

var diameter = 960,
    radius = diameter / 2,
    innerRadius = radius - 120;

var cluster = d3.layout.cluster()
    .size([360, innerRadius])
    .sort(null)
    .value(function(d) { return d.size; });

var bundle = d3.layout.bundle();

var line = d3.svg.line.radial()
    .interpolate("bundle")
    .tension(.85)
    .radius(function(d) { return d.y; })
    .angle(function(d) { return d.x / 180 * Math.PI; });

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
  .append("g")
    .attr("transform", "translate(" + radius + "," + radius + ")");

var link = svg.append("g").selectAll(".link"),
    node = svg.append("g").selectAll(".node");

//d3.json("https://gist.githubusercontent.com/mbostock/1044242/raw/8f22cf2264e1f6ec6cb233c4b49333fb8f75bb99/readme-flare-imports.json", function(error, classes) {
  //if (error) throw error;

  var nodes = cluster.nodes(packageHierarchy(classes)),
      links = packageImports(nodes);

  link = link
      .data(bundle(links))
    .enter().append("path")
      .each(function(d) { d.source = d[0], d.target = d[d.length - 1]; })
      .attr("class", "link")
      .attr("d", line);

  node = node
      .data(nodes.filter(function(n) { return !n.children; }))
    .enter().append("text")
      .attr("class", "node")
      .attr("dy", ".31em")
      .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + 8) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
      .style("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
      .text(function(d) { return d.key; })
      .on("mouseover", mouseovered)
      .on("mouseout", mouseouted);
//});

function mouseovered(d) {
  node
      .each(function(n) { n.target = n.source = false; });

  link
      .classed("link--target", function(l) { if (l.target === d) return l.source.source = true; })
      .classed("link--source", function(l) { if (l.source === d) return l.target.target = true; })
    .filter(function(l) { return l.target === d || l.source === d; })
      .each(function() { this.parentNode.appendChild(this); });

  node
      .classed("node--target", function(n) { return n.target; })
      .classed("node--source", function(n) { return n.source; });
}

function mouseouted(d) {
  link
      .classed("link--target", false)
      .classed("link--source", false);

  node
      .classed("node--target", false)
      .classed("node--source", false);
}

d3.select(self.frameElement).style("height", diameter + "px");

// Lazily construct the package hierarchy from class names.
function packageHierarchy(classes) {
  var map = {};

  function find(name, data) {
    var node = map[name], i;
    if (!node) {
      node = map[name] = data || {name: name, children: []};
      if (name.length) {
        node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
        node.parent.children.push(node);
        node.key = name.substring(i + 1);
      }
    }
    return node;
  }

  classes.forEach(function(d) {
    find(d.name, d);
  });

  return map[""];
}

// Return a list of imports for the given array of nodes.
function packageImports(nodes) {
  var map = {},
      imports = [];

  // Compute a map from name to node.
  nodes.forEach(function(d) {
    map[d.name] = d;
  });

  // For each import, construct a link from the source to target node.
  nodes.forEach(function(d) {
    if (d.imports) d.imports.forEach(function(i) {
      imports.push({source: map[d.name], target: map[i]});
    });
  });

  return imports;
}
.node {
  font: 300 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
  fill: #bbb;
}

.node:hover {
  fill: #000;
}

.link {
  stroke: steelblue;
  stroke-opacity: .4;
  fill: none;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Fiddle:https://fiddle.jshell.net/ga1s8bn7/


text:
Q: Cannot convert value type to expected argument type error? working on my swift app here.
Below is the code I have,
struct WebView: UIViewRepresentable {
    @State var allowsInLineMediaPlayback = true
    let request: URLRequest//pass the website to webkit

    func makeUIView(context: Context) -> WKWebView {
        let configuration = WKWebViewConfiguration()
        configuration.allowsInlineMediaPlayback = true
        configuration.mediaTypesRequiringUserActionForPlayback = []
        let webView = WKWebView(frame: .zero, configuration: configuration)
        return webView

    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)

    }
}

class ViewController: UIViewController {

var webView = WKWebView()
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive),
                                               name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(willResignActive),
                                               name: UIApplication.willResignActiveNotification, object: nil)
    }
    @objc func willResignActive(){
        disableIgnoreSilentSwitch(webView)

    }

    @objc func didBecomeActive() {
        //Always creates new js Audio object to ensure the audio session behaves correctly
        forceIgnoreSilentHardwareSwitch(webView, initialSetup: false)
    }

and I am getting an error with this part with webView,
disableIgnoreSilentSwitch(webView)

The error states
Cannot convert value of type '(WKWebView, WKNavigation?) -> ()' to expected argument type 'WKWebView'
Thanks in advance.
If it helps, I am using the code from here as reference. How to force WKWebView to ignore hardware silent switch on iOS?


text:
Q: Use Zabbix web scenario status for notification I've created a web scenario with three steps within my zabbix installation.
In case of an error I want to get a more detailed information about the error in the notification.
I'm getting this:
PROBLEM: www.mywebsite.tld.Fail : Failed step of scenario www.mywebsite.tld.

In the status window of the web scenarios I'm getting the information:
step "Product Page" [3 of 3] failed: required pattern not found

How can I send the text of the web scenario status into the notification?
Normally it shouldn't be such a big problem, the text is already available in the status text.
Is there a macro for this text?

A: The correct way to implement the notifications is to configure triggers on the items created from web scenarios and relative steps. The item that holds the "required pattern not found" string is "Last error message of scenario" : web.test.error[Scenario].

A: You can't see web output in web check.
But you can create new Zabbix item web.page.get[host,,] and then you will see web output in item history.


text:
Q: Django - Type Error Matching query does not exist Currently experiencing something very strange.
Though, I've got a plain-vanilla function & template, I receive a TypeError that refers to a line in my views.py belonging to a different function / template...
views.py:
def shopping(request):
 shops = Shop.objects.all()
 return render(request, 'home/shops.html', {'shops':shops})

shops.html:
{% extends 'base_template.html' %}

{% block content%}

<h2> Welcome </h2>

{{ shops }}

{% endblock%}

Error:
DoesNotExist at /home/shops/

Shop matching query does not exist.
shopdetail = Shop.objects.get(slug=shopslug)  ---> belongs to a different function


text:
Q: How to get timezone daylight saving rules from Noda Time in POSIX time zone format As answered in Getting Daylight Savings Time Start and End in NodaTime daylight saving start and end dates can be solved for given year.
How to get the actual rules for calculating start and end date preferably in POSIX time zone format?
Project is currently using Noda Time but any other .NET solution can be considered.

A: The POSIX format only seems to cater for a single rule - whereas in reality, the rules change over time. It's also not clear to me whether POSIX rules allow for 24:00 as a transition time, and the expectation that all transitions are specified in local time seems unfortunate. (In TZDB, some rules are expressed in terms of UTC, some in terms of wall time, and some in terms of standard time. Performing a "simple" conversion from that to "everything is local" could cause some very subtle errors.) In short - I would expect a conversion from TZDB to POSIX to be potentially lossy.
The "actual rules" aren't exposed via the Noda Time API, as they're rarely useful to clients (compared with simply getting at the computed data) - but you could look at the NodaTime.TzdbCompiler code to see how the TZDB rules are parsed, stored in memory, and serialized to disk. The serialized format doesn't have enough information to always recover the original rules - but you could create your own serialization format in a fork, of course.
For the original ("raw") source data, the IANA time zone database is your best starting point.


text:
Q: Is there a analytical formula for Super- and Sub-Poissonian distributions? I'm currently wrtiting my Bachelors thesis on photon statistics. The way different sources of light can be classified is by Poissonian (coherent light), Super-Poissonian (thermal light) and Sub-Poissonian (n-Photon-states). However, both books that I'm using as primary sources (Rodney Loudon, The Quantum theory of light and Mark Fox, Quantum Optics - An introduction) don't mention explicitly a formula for Sub and Super-Poisson distribution, just that for Sub-Poissonian light the variance $\Delta n$ falls below the expectation $\langle n \rangle$ (that is, $\Delta n < \langle n \rangle$), and for Super-Poissonian $\Delta n > \langle n \rangle$.
For my work, I want to plot three plots with varying $\Delta n$, but same $\langle n  \rangle$. However, I can't do this with the standard Poisson distribution
$$
P(n)=\frac{\mu^n e^{-n}}{n!}
$$
However, I've read that for large expectation values $\mu$, I can approximate the Poisson distribution with a normal distribution. Given that my expectation values usually don't exceed 10, this doesn't seem to be an option.
So I'm here, looking for help from mathematicians and hope that someone can help me.

A: Unlike Poisson distribution, sub-Poissonian and super-Poissonian are not distributions, but rather properties of distributions (properties to have larger or smaller variance than the Poisson distribution with the same mean). An example of super-Poissonian distribution is negative binomial distribution, which has two parameters, $r \in \mathbb{Z}_{+}$ and $p \in (0, 1)$, for which $P(n) = \begin{pmatrix}n + r - 1\\ n\end{pmatrix} (1 - p)^r p^n$, the mean $\langle n \rangle = \frac{p r}{1-p}$ and variance $\langle (\Delta n)^2 \rangle = \frac{p r}{(1 - p)^2}$.
Another option is to multiply the parameter of Poisson distribution and the resulting random variable by a factor $\alpha$. For this distribution, $P(x) = \frac{(\alpha \mu)^{\alpha x}}{(\alpha x)!} e^{-\mu \alpha}$ if $\alpha x$ is integer and $0$ otherwise, the mean is $\langle x \rangle = \mu$ and variance is $\langle (\Delta x)^2 \rangle = \frac{\mu}{\alpha}$, so for $\alpha > 1$ the distribution will be sub-Poissonian and for $\alpha < 1$ super-Poissonian.
Edit: correction of the distribution, thanks to @Alex


text:
Q: Tomcat deletes uploaded files when undeployment Firstly my topic seems like duplicated, but other solutions didn't help me. I'm also having interesting situation. Antoher computer I have all the same configurations and it works good. But another one it doesn't work good.
I'm uploading file as multipart file via Spring MVC. If I don't undeploy everything works good I saw files in target directory. I also debugged and I can see paths correctly.(Actually when it had been working good a month ago I saw path as src directory, not tomcat's root exploded directory.)
When I undeploy tomcat deletes all uploaded images, so then as you guess I can't see images on my jsp.
That function I wrote
 MultipartFile urunResim = urun.getUrunResim();
    String rootDir = request.getSession().getServletContext().getRealPath("/");
    path = Paths.get(rootDir + "\\WEB-INF\\resources\\urun_resimler\\" + urun.getUrunId() + ".png");
    if (urunResim != null && !urunResim.isEmpty()) {
        try {
            urunResim.transferTo(new File(path.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Urun resmi kaydedilemedi!");
        }

Thanks in advance.


text:
Q: Space between bar chart in Matplotlib I have some difficulties understanding the bar chart in matplotlib.
I need to have some space every 4 bars because they represent a specific condition.
I cannot put the space after 4th bar.
So far I am stuck here:
largbar = 0.25

X = np.arange(6)

plt.bar(X ,              arr2i,  width=largbar,color='y',label="2irg")
plt.bar(X + largbar,     arrBC,  width=largbar,color='b',label="BC")
plt.bar(X + largbar*2,   arr_min,width=largbar,color='g',label="min")
plt.bar(X + largbar*3,   arr_max,width=largbar,color='r',label="Max")

plt.xticks([(r+ largbar + largbar/2) for r in range(len(arr2i))],sf_name)
plt.legend()
plt.show()

Should I change something?


text:
Q: How to pll out live code methods like 'has_man' to a lib Following code works just fine.
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :bad_record
def bad_record
   redirect_to root_url
end

end
However I wanted to refactor the code and put this functionality in a lib since my application controller has grown large.
This is what I came up with and it works.
class ApplicationController < ActionController::Base
 include RescueFromRecordNotFound
end
\#lib/rescue_from_record_not_found.rb
module RescueFromRecordNotFound
 def self.included(base)
  tmp = "rescue_from ActiveRecord::RecordNotFound, :with => :bad_record"
  base.send(:eval,tmp)
  base.send(:include, InstanceMethods)
end
module InstanceMethods
  def bad_record
     redirect_to root_url
  end

end
  end
The solution works. However I do not really like dong eval. I was wondering if there is a better way to achieve the same goal.

A: Have you tried:
base.send(:rescue_from, ...)


text:
Q: Decrypting AES encrypted string in C# I am trying to decrypt an AES encrypted string from Java, in C#. When I decrypt, it returns gibberish and does not match the original plain text, which was encrypted via Java code. Pls guide me on what is going wrong here.
Attached the Java code for encryption and the C# code for decryption. Pls let me know if you need more details.
I tried AesCryptoServiceProvider as well and it did not work either. You can see the code tried in the commented code in C#.
Pls  note that I can make changes on my C# code only to match the Java code and can not make any edits to Java side.
Java code for Encryption:
/** encrypt cipher */
private static final Cipher ENCRYPT_CIPHER = generateCipher(Cipher.ENCRYPT_MODE);

private static String ENCRYPT_KEY = "key";

/**
 * @param val
 * @return encrypted value
 * @throws Exception
 */
public String encrypt(final String val) throws Exception {
    return new String(Base64.encodeBase64(ENCRYPT_CIPHER.doFinal(val.getBytes()), true)).toString();
}

/**
 * @param encrypt
 * @return cipher
 */
protected static Cipher generateCipher(final int encrypt) {
    try {
        final Cipher cipher = Cipher.getInstance("AES");
        cipher.init(encrypt, SecretKeyFactory.getInstance("AES").generateSecret(new IBMAESKeySpec(Base64.decodeBase64(ENCRYPT_KEY.getBytes()))));
        return cipher;
    } catch (final Exception e) {
        return null;
    }
}

C# code for decryption:
private static String ENCRYPT_KEY = "key";
public String decodeString (String encodedStr)
{

/*using (var aesCryptoProvider = new AesCryptoServiceProvider())
    {
    aesCryptoProvider.BlockSize = 128;
    aesCryptoProvider.KeySize = 256;
    aesCryptoProvider.Key = Convert.FromBase64String(ENCRYPT_KEY.ToString());
    aesCryptoProvider.Padding = PaddingMode.Zeros;
    aesCryptoProvider.Mode = CipherMode.ECB;

    using (var decryptor = aesCryptoProvider.CreateDecryptor())
    using (var memoryStream = new MemoryStream(Convert.FromBase64String(encodedStr)))
    using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
    using (var streamReader = new StreamReader(cryptoStream, Encoding.UTF8))
    {
        decodedStr = streamReader.ReadToEnd();
    }
    }
 */
    using (AesManaged aesAlg = new AesManaged())
        {
        aesAlg.Key = Convert.FromBase64String(ENCRYPT_KEY.ToString()); ;
        aesAlg.BlockSize = 128;
        aesAlg.KeySize = 256;
        aesAlg.Mode = CipherMode.ECB;
        aesAlg.Padding = PaddingMode.Zeros;
        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = aesAlg.CreateDecryptor();

        // Create the streams used for decryption.
        using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encodedStr)))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
            {

                // Read the decrypted bytes from the decrypting stream
                // and place them in a string.
                decodedStr = srDecrypt.ReadToEnd();
            }
            }
        }

     }
}

A: This is just a quick answer. Haven't done a ton of research into it, but have you checked to see if the endian-ness matches? It looks like C# (.NET) is little-endian, but the JVM is big-endian. I'm not sure if it swaps it for network transmission, however (then it would just match the hardware). Just an idea. If I find anything additional, I'll update my answer.


text:
Q: Jquery plugin to Sort a table made of  I want to make sortable a table made with div and diplay table using some jquery plugin.
I can modify my table but i can't use html  tags.

A: You should use a table made out of a table. Tables have their place in HTML, which is to show tabular data.
Check out http://tablesorter.com for an easy plugin:
HTML Example:

    Last Name
    First Name
    Email
    Due
    Web Site

    Smith
    John
    jsmith@gmail.com
    $50.00
    http://www.jsmith.com

    Bach
    Frank
    fbach@yahoo.com
    $50.00
    http://www.frank.com

    Doe
    Jason
    jdoe@hotmail.com
    $100.00
    http://www.jdoe.com

    Conway
    Tim
    tconway@earthlink.net
    $50.00
    http://www.timconway.com

jQuery Example:
$(function(){
    $("#myTable").tablesorter();
});


text:
Q: CSS  width on percentage online shrinks on window resize (left - right) I have this page (for practicing webprogramming) witch has a footer at the bottom.
http://i333180.iris.fhict.nl/melissa/index.html
Because the site probably got to opened on different window sizes I use margin-top in percentage.
margin-top: 38%

The problem I got is the footer stays on his place by shrinking the window from bottom to top. But by shrinking the window from left to right, the footer position changes.
I google around and what is said the html, body and surrounded div's has to got
height:100%;

So added this but the footer won't change position on window resize (bottom-top). Is this only possible to fix with
position:absolute;
left: somevalue;
top: somevalue;

A: Add this css to the .p-footer :
position: absolute;
bottom: 0px;
left: 25%;
right: 25%;

And you should take off the margin property.


text:
Q: How to detect and implement wireless drivers on Gateway MX6446 Laptop? I recently installed Ubuntu on my friend's laptop because Windows wasn't running well, but the wireless hardware may not be detected, or I may not have the appropriate drivers(?). I tried these instructions but it didn't seem to have any effect after rebooting. Let me know what additional information might help to figure out what's wrong.
EDIT:
lspci -nn | grep 0280
05:00.0 Network controller [0280]: Broadcom Corporation BCM4311 802.11b/g WLAN [14e4:4311] (rev 01)

sudo modprobe b43 dmesg | grep -e wlan -e b43 has given no response. I recently restarted after what's been done; there's no noticeable change. Rfkill list also gives no output.
firmware-b43-installer is already the newest version.

I found this tutorial, and an answer in it revealed this output related to the blacklist:
b43-fwcutter is already the newest version.
b43-fwcutter set to manually installed.
firmware-b43-installer is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 16 not upgraded.
timmy@timmy-MX6446:~$ cat /etc/modprobe.d/* | egrep 'bcm'
blacklist bcm43xx
timmy@timmy-MX6446:~$ # blacklist bcm43xx
timmy@timmy-MX6446:~$ sudo gedit blacklist.conf

** (gedit:3368): WARNING **: Can't load fallback CSS resource: Failed to import: The resource at '/org/gnome/adwaita/gtk-fallback.css' does not exist

** (gedit:3368): WARNING **: Can't load fallback CSS resource: Failed to import: The resource at '/org/gnome/adwaita/gtk-fallback.css' does not exist

(gedit:3368): Gt-WARNING **: Calling Inhibit failed: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.SessionManager was not provided by any .service files

Not sure if that helps at all. Thanks for the help so far.

A: Your Broadcom device requires non-free firmware to work correctly. If you followed the instructions you linked and installed firmware-b43-installer and rebooted, your wireless should be working. If it is not, I suggest you check the wireless switch or key combination. You can see if the device is being turned off by the switch with:
rfkill list all

If there is no hard- or soft-block, check the logs for clues; first load the driver and look for any errors or warnings:
sudo apt-get purge bcmwl-kernel-source
sudo modprobe b43
dmesg | grep -e wlan -e b43

Once I have more information, I will edit this answer to suggest a solution.

A: If wl driver does not work well for you, you can install b43.
sudo apt-get purge bcmwl-kernel-source
sudo apt-get install firmware-b43-installer
sudo modprobe -r wl
sudo modprobe b43

You need to uninstall wl driver because it blacklists b43.

A: Solved through this guide and following it with cat /etc/modprobe.d/* | egrep 'bcm' then cd /etc/modprobe.d/ , sudo gedit blacklist.conf and placing a # in front of blacklist bcm43xx, as according to KiLLeRfriend. Thanks for helping.


text:
Q: GCP MS SQL Server 2017 how to bulk load csvs from local machine I have a Microsoft SQL Server 2017 database on Google Cloud. I'm trying to bulk load CSV files from my local machine to the database, using the following command
BULK INSERT umls.mrxw_spa
FROM 'C:\data\umls\2020AA\META\MRXW_SPA.RRF'
WITH (FIELDTERMINATOR = '|', BATCHSIZE = 10000);

but I get an error message

Cannot bulk load. The file "C:\data\umls\2020AA\META\MRXW_SPA.RRF" does not exist or you don't have file access rights.

I don't know how to give the GCP SQL Server permissions to my local folder. This database used to be on Azure and it was quite easy to load, but the company changed its licensed and moved to Google Cloud. I know I could create a python script to load the data - but using the above command is a lot easier.
Has anyone been able to use the Bulk Insert in the GCP?

A: You do not. The standard approach for bulk load is to move the data onto the server and load from there. IF you would have a proper network in place.... you would still have to use a UNC form (\machine\fileshare\path\file).
Basically your bulk insert command is sent to the server. THe server then looks for the file at c:\data.... (basically the path). This command is NOT EXECUTED ON YOUR COMPUTER. No SQL is. They all are sent to the server.
Giving the server permissions on your local machine is not an option. Besides that being tricky without domain - the server will likely NOT BE ABLE TO REACH YOUR MACHINE because it is behind NAT. So, your question is akin to "how can I bypass he secretary on (whatever ceo) office?" and then not even having the phone number of his office. Unless you have a network setup that allows the server to reach you (99.9% chance you do not have that in place) the permissions are useless to start with.


text:
Q: SpringBoot : Connection has already been closed I am getting exception below in my business flow very frequently.
Technical specifications are SprinBoot, Java8, SAP Hana as DB, Restful.
        org.springframework.transaction.TransactionSystemException: Could not roll back JDBC transaction;
        nested exception is java.sql.SQLException: Connection has already been closed. at org.springframework.jdbc.datasource.DataSourceTransactionManager.doRollback(DataSourceTransactionManager.java:331) at
            org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:853) at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:830) at
            org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:536) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:286) at
            org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at
            org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at
            org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) at

application.properties for data source
    SAPHanaViewDataSource.datasource.driver-class-name=com.sap.db.jdbc.Driver
    SAPHanaViewDataSource.datasource.validation-query=select 1 from DUMMY
    SAPHanaViewDataSource.datasource.test-on-borrow=true
    SAPHanaViewDataSource.datasource.test-while-idle=false
    SAPHanaViewDataSource.datasource.test-on-return=false
    SAPHanaViewDataSource.datasource.validation-interval=300000
    SAPHanaViewDataSource.datasource.time-between-eviction-runs-millis=300000
    SAPHanaViewDataSource.datasource.max-active=120
    SAPHanaViewDataSource.datasource.max-idle=40
    SAPHanaViewDataSource.datasource.initial-size=40
    SAPHanaViewDataSource.datasource.max-wait=600000
    SAPHanaViewDataSource.datasource.max-age=5000
    SAPHanaViewDataSource.datasource.min-evictable-idle-time-millis=600000
    SAPHanaViewDataSource.datasource.min-idle=40
    SAPHanaViewDataSource.datasource.log-abandoned=true
    SAPHanaViewDataSource.datasource.remove-abandoned-timeout=600
    SAPHanaViewDataSource.datasource.remove-abandoned=true

Am I doing some wrong configuration as per standards? Can anyone please help me to resolve this issue.


text:
Q: React Router params returning empty object In my App.js file where I render all my routes I have this code:
import LiveMatch from "../containers/LiveMatch";

const routes = [
  //removed other routes for simplicity of post
  {
    path: "/livematch/:matchid", <--- here is the param I want
    exact: true,
    component: () => <LiveMatch />
  }
];

class App extends Component {

  render() {
    return (

        <BrowserRouter>

            {routes.map((route, index) =>
              <Route
                key={index}
                path={route.path}
                exact={route.exact}
                component={route.component}
              />
            )}

        </BrowserRouter>

    );
  }
}

Now that I have the component set up, I try to print out the :matchid parameter but I keep getting an empty object.
class LiveMatch extends Component {
  constructor(props) {
    super(props)
    this.state = {...}

    console.log(this.props) // returns { }
  }

  componentDidMount() {
     console.log(this.props) // returns { }
  }

}

Whether I try to access props in constructor or after mounting the props is always empty. From other posts I've searched up apparently the answer should be as simple as this.props.params.matchid or this.props.match.params.matchid.
Question: How do I get access to the :matchid param. Am I doing anything incorrectly?

A:
Why it is not available inside LiveMatch component?

Because you are not passing the default props (means props passed by router into component) into LiveMatch component. You are overriding the props values.
Solution is, With arrow function receive the props and pass down into component it will work.
Write it like this:
component: (props) => <LiveMatch {...props}/>

Or remove the arrow function:
component: LiveMatch


text:
Q: Middleware between Languages Let's say I have written a library containing many classes in C++. Obviously, I can call this library from C++ client programs.
But, now let's say I want to use another language for my client programs. Since my C++ library contains many classes, I don't want to redevelop them in the client language.
So, I would like to be able to call my C++ library classes from other languages.
Also, I want the solution to be portable across platforms. I don't want to be tied to one platform (such as .NET where any .NET language can call any other .NET language).
In the extreme case, this inter-language call feature would be required even from "managed" languages such as Java.
So, my question is: Is it possible to call a library function written in one language, from a program written in another language? If so, how?

A: My understanding of the general use of "Middleware" is a little different to your description as it is not primarily about allowing libraries written in one language to be called from another.
I think that what you are looking for is tools that allow cross language bindings to be generate so as to allow libraries written in one language C++ in this case to be used in multiple other languages. A couple of examples of such tools are Boost and Swig.
In both of the above tools you need to build your C++ libraries to run on your target platform and build an interface layer for the language(s) that you wish to provide bindings for but in the case of Boost as far as I can see you need to pay a lot of attention to how your library is constructed. SWIG on the other hand parses your interface (.h) files and produces bindings for the supported target language(s) which include Tcl, Python, Perl, Guile, Java, Ruby, PHP, C#, R, Go, etc.


text:
Q: How to set Dictionary as Dictionary value in Excel VBA? I want to set a dictionary as dictionary value?
But it throws an error like

'Wrong number of arguments or invalid property assignment'.

How to fix this issue?
sub test()
Dim Dict As Scripting.Dictionary
Set Dict = New Scripting.Dictionary
Dim rows As Scripting.Dictionary
Set rows = New Scripting.Dictionary

dict("name") = "Sarah"
dict("surname") = "Jones"

rows(dict("name")) = dict

end sub

A: Dictionary is an object type, with a default member.
rows(dict("name")) = dict

The RHS of this assignment is really a call to dict.Item, but invoked without any parameters... but the Key parameter is required - hence the error.

The Set keyword disambiguates default member calls from "yes I really mean the object reference itself"
Set rows(dict("name")) = dict


text:
Q: What is the difference between controlling for a variable in a regression model vs. controlling for a variable in your study design? I imagine that controlling for a variable in your study design is more effective at reducing error than controlling for it post-hoc in your regression model.
Would someone mind explaining formally how these two instances of "controlling" differ?  How comparatively effective are they at reducing error and yielding more precise predictions?

A: By "controlling for a variable in your study design", I assume you mean causing a variable to be constant across all study units or manipulating a variable so that the level of that variable is independently set for each study unit.  That is, controlling for a variable in your study design means that you are conducting a true experiment.  The benefit of this is that it can help with inferring causality.
In theory, controlling for a variable in your regression model can also help with inferring causality.  However, this is only the case if you control for every variable that has a direct causal connection to the response.  If you omit such a variable (perhaps you didn't know to include it), and it is correlated with any of the other variables, then your causal inferences will be biased and incorrect.  In practice, we don't know all the relevant variables, so statistical control is a fairly dicey endeavor that relies on big assumptions you can't check.
However, your question asks about "reducing error and yielding more precise predictions", not inferring causality.  This is a different issue.  If you were to make a given variable constant through your study design, all of the variability in the response due to that variable would be eliminated.  On the other hand, if you simply control for a variable, you are estimating its effect which is subject to sampling error at a minimum.  In other words, statistical control wouldn't be quite as good, in the long run, at reducing residual variance in your sample.
But if you are interested in reducing error and getting more precise predictions, presumably you primarily care about out of sample properties, not the precision within your sample.  And therein lies the rub.  When you control for a variable by manipulating it in some form (holding it constant, etc.), you create a situation that is more artificial than the original, natural observation.  That is, experiments tend to have less external validity / generalizability than observational studies.

In case it's not clear, an example of a true experiment that holds something constant might be assessing a treatment in a mouse model using inbred mice that are all genetically identical. On the other hand, an example of controlling for a variable might be representing family history of disease by a dummy code and including that variable in a multiple regression model (cf., How exactly does one "control for other variables"?, and How can adding a 2nd IV make the 1st IV significant?).


text:
Q: $\epsilon$ function of a tubular neighborhood I´m reading some notes about differential topology. In some point it says the following: if $Y\subset\mathbb{R}^N$ is a embedded submanifold and $U$ is a tubular neighborhood of $Y$, then there exist a positive function $\epsilon:Y\to\mathbb{R}$ such that $U_\epsilon=\{w\in\mathbb{R}^N\;|\;|w-y|<\epsilon(y)\;\text{for some $y\in Y$}\}$ is contained in $U$.
To prove this assertion, it defines $\epsilon(y)=\sup\{r\;|\;B(y,r)\subset U\}$ and proofs it is continuous in this way: let $\epsilon>0$, there is some $x\in U$ such that $\epsilon(y)\leq|x-y|+\epsilon$. For any other $y'\in Y$, this is $\epsilon(y)\leq|x-y'|+|y'-y|+\epsilon$. Since $|x-y'|\leq\epsilon(y')$, we have $|\epsilon(y)-\epsilon(y')|\leq|y-y'|+\epsilon$.
I can't understand why $|x-y'|\leq\epsilon(y')$.

A: Remember that $U$ is a tubular neighborhood of $Y$ (not just an arbitrary open set containing $Y$). So if $|x-y'|=r$ and $x\in U$, then $B(y',r)\subset U$. It follows that if $\epsilon(y')<|x-y'|=r$, then $x\notin U$.


text:
Q: Adding a 3rd button and have date picker for time NEW CODE
DatePickerViewController.h
#import <UIKit/UIKit.h>

@protocol DatePickerViewControllerDelegate;

@interface DatePickerViewController : UIViewController {
    IBOutlet UIDatePicker *datePicker;
    id<DatePickerViewControllerDelegate> delegate;
}

@property (retain) IBOutlet UIDatePicker *datePicker;
@property (assign) id<DatePickerViewControllerDelegate> delegate;

NSInteger buttonPressed;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;

- (IBAction)doneButtonPressed:(id)sender;
@end

@protocol DatePickerViewControllerDelegate <NSObject>

@optional
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;

@end

DatePickerViewController.m

#import "DatePickerViewController.h"

@implementation DatePickerViewController

@synthesize datePicker, delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
        self.title = @"Date Picker";
    }
    return self;
}

- (void)viewDidLoad {
    NSLog(@"Date Picker. viewDidLoad");
    [super viewDidLoad];
    double days = 2.0f;
    datePicker.date = [NSDate dateWithTimeIntervalSinceNow:60.0f * 60.0f * 24.0f * days];

}

//-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;

- (IBAction)doneButtonPressed:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(datePickerViewController:didChooseDate:)]) {
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

        NSString *dateString = [dateFormatter stringFromDate:[datePicker date]];

        [self.delegate datePickerViewController:self didChooseDate:dateString];
        [self dismissModalViewControllerAnimated:YES];

    }

}

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

@end

DatePickerViewController2.h
#import <UIKit/UIKit.h>

@protocol DatePickerViewController2Delegate;

@interface DatePickerViewController2 : UIViewController {
    IBOutlet UIDatePicker *datePicker2;
    id<DatePickerViewController2Delegate> delegate;
}

@property (retain) IBOutlet UIDatePicker *datePicker2;
@property (assign) id<DatePickerViewController2Delegate> delegate;

NSInteger buttonPressed2;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;

- (IBAction)doneButtonPressed2:(id)sender;
@end

@protocol DatePickerViewController2Delegate <NSObject>

@optional
-(void)datePickerViewController2:(DatePickerViewController2 *)controller didChooseDate:(NSString *)chosenDate;

@end

DatePickerViewController2.m

#import "DatePickerViewController2.h"

@implementation DatePickerViewController2

@synthesize datePicker2, delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
        self.title = @"Date Picker2";
    }
    return self;
}

- (void)viewDidLoad {
    NSLog(@"Date Picker2. viewDidLoad");
    [super viewDidLoad];
    double days = 2.0f;
    datePicker2.date = [NSDate dateWithTimeIntervalSinceNow:60.0f * 60.0f * 24.0f * days];

}

//-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;

- (IBAction)doneButtonPressed2:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(datePickerViewController2:didChooseDate:)]) {
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

        NSString *dateString = [dateFormatter stringFromDate:[datePicker2 date]];

        [self.delegate datePickerViewController2:self didChooseDate:dateString];
        [self dismissModalViewControllerAnimated:YES];

    }

}

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

@end

DatePickerModalExampleAppDelegate.h
#import <UIKit/UIKit.h>

@class DatePickerModalExampleViewController;

@interface DatePickerModalExampleAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    DatePickerModalExampleViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet DatePickerModalExampleViewController *viewController;

@end
DatePickerModalExampleAppDelegate.m
#import "DatePickerModalExampleAppDelegate.h"
#import "DatePickerModalExampleViewController.h"

@implementation DatePickerModalExampleAppDelegate

@synthesize window;
@synthesize viewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Override point for customization after app launch
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}

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

@end

DatePickerModalExampleViewController.h

#import <UIKit/UIKit.h>
#import "DatePickerViewController.h"
#import "DatePickerViewController2.h"

@interface DatePickerModalExampleViewController : UIViewController <DatePickerViewControllerDelegate> {
    IBOutlet UIButton *button;
    IBOutlet UIButton *button2;
    IBOutlet UIButton *button3;

}

@property(nonatomic, retain) IBOutlet UIButton *button;
@property(nonatomic, retain) IBOutlet UIButton *button2;
@property(nonatomic, retain) IBOutlet UIButton *button3;

-(IBAction)buttonPressed:(id)sender;
-(IBAction)buttonPressed2:(id)sender;
@end

DatePickerModalExampleViewController.m

#import "DatePickerModalExampleViewController.h"

@implementation DatePickerModalExampleViewController
@synthesize button;
@synthesize button2;
@synthesize button3;

/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

-(IBAction)buttonPressed:(id)sender{
    NSLog(@"I was pressed");
    buttonPressed = ((UIButton *)sender).tag;

    DatePickerViewController *datePickerViewController = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:nil];
    datePickerViewController.delegate = self;
    [self presentModalViewController:datePickerViewController animated:YES];
    [datePickerViewController release];

switch (((UIButton*)sender).tag)
    {

        case 100001:
        NSLog(@"Button 1 was pressed");

            //some code
        break;
        case 100002:
        NSLog(@"Button 2 was pressed");

            //some code
        break;

    }
}

-(IBAction)buttonPressed2:(id)sender{
    NSLog(@"I was pressed2");
    buttonPressed2 = ((UIButton *)sender).tag;

    DatePickerViewController2 *datePickerViewController2 = [[DatePickerViewController2 alloc] initWithNibName:@"DatePickerViewController2" bundle:nil];
    datePickerViewController2.delegate = self;
    [self presentModalViewController:datePickerViewController2 animated:YES];
    [datePickerViewController2 release];

    switch (((UIButton*)sender).tag)
    {

        case 100003:
            NSLog(@"Button 3 was pressed");

            //some code
            break;

    }
}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.button.tag = 100001;
    self.button2.tag = 100002;
    self.button3.tag = 100003;
    buttonPressed = -1;
    buttonPressed2 = -1;

}

-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate{
    NSLog(@"Chosen Date as String: %@", chosenDate );

    if (buttonPressed == -1)
        return;
    UIButton *buttonToSet = (UIButton*)[self.view viewWithTag:buttonPressed];
    buttonPressed = -1;
    [buttonToSet setTitle: chosenDate forState: UIControlStateNormal];
    [self dismissModalViewControllerAnimated:YES];
}

-(void)datePickerViewController2:(DatePickerViewController2 *)controller didChooseDate:(NSString *)chosenDate{
    NSLog(@"Chosen Date as String: %@", chosenDate );

    if (buttonPressed2 == -1)
        return;
    UIButton *buttonToSet = (UIButton*)[self.view viewWithTag:buttonPressed2];
    buttonPressed2 = -1;
    [buttonToSet setTitle: chosenDate forState: UIControlStateNormal];
    [self dismissModalViewControllerAnimated:YES];
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [button3 release];
    [button2 release];
    [button release];
    [super dealloc];
}

@end

A: Use tag for both buttons and check the condition accordingly...

A: Hello you can set the property "tag" on button to identify it
Uncomment
- (void)viewDidLoad {
[super viewDidLoad];
}

And type :
- (void)viewDidLoad {
[super viewDidLoad];
self.button.tag = 100001;
self.button2.tag = 100002;

}

then
turn in DatePickerModalExampleViewController.h
(IBAction)buttonPressed to (IBAction)buttonPressed:(id)sender;
Then turn in DatePickerModalExampleViewController.m
-(IBAction)buttonPressed to -(IBAction)buttonPressed:(id)sender
and in DatePickerModalExampleViewController.m this method could be like that :
    -(IBAction)buttonPressed:(id)sender
    {
        switch(((UIButton*)sender).tag)
        {
         case 100001
               NSLog(@"Button 1 was pressed");
               DatePickerViewController *datePickerViewController =[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:nil];
               datePickerViewController.delegate = self;
               [self presentModalViewController:datePickerViewController animated:YES];
               [datePickerViewController release];
            break;
         case 100002 :
               NSLog(@"Button 2 was pressed");
               // some code
             break;
        }
    }

As you use the interfacebuilder I'm not friend with it but you must relink your actions
I'm writting from my PC so without xcode some code can contains syntax error be carreful. but it's the main idea.


text:
Q: Why won't my pygame images load I'm relatively new to python and pygame, so this is most certainly just my own inexperience.  However, in my game loop, every time an image or shape is blitted to the screen, it doesn't disappear until another image or shape is blitzed over it.
game_loop function
def game_loop():

road
carImg

pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('Rally-X.mp3')
pygame.mixer.music.play()

x = (display_width * 0.45)
y = (display_height * 0.8)

x_change = 0

road_starty = -23
road_speed = 4

thing_starty = -600
thing_speed = 4
thing_width = 100
thing_height = 100
thing_startx = random.randrange(0, display_width)

carImgCount = 1

dodged = 0

gameExit = False

pygame.display.update()

while not gameExit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
            pygame.display.update()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                x_change = -5
            if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                x_change = 5
            if event.key == pygame.K_p:
                paused()
            pygame.display.update()

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_d or event.key == pygame.K_a:
                x_change = 0
            pygame.display.update()
    x += x_change

    gameDisplay.blit(road,(0,road_starty))

    car(x,y)
    #things(thingx, thingy, thingw, thingh, color)
    things(thing_startx, thing_starty, thing_width, thing_height)

    road_starty += road_speed

    thing_starty += thing_speed
    things_dodged(dodged)

    if x > display_width - car_width or x < 0:
        crash()

    if thing_starty > display_height:
        thing_starty = 0 - thing_height
        thing_startx = random.randrange(0,display_width)
        dodged += 1
        if thing_speed <= 10:
            thing_speed += 1
        pygame.display.update()

    if y < thing_starty+thing_height:
        #print('y crossover')

        if x > thing_startx and x < thing_startx + thing_width or x+car_width > thing_startx and x + car_width < thing_startx+thing_width:
            #print('x crossover')
            crash()
        pygame.display.update()
    if road_starty == 0:
        road_starty = -23

    if dodged > 9:
        things(thing_startx, thing_starty, thing_width, thing_height)

    pygame.display.update()
    clock.tick(60)

I started just calling the pygame.display.update() function just about everywhere in the game_loop function to try and fix it, but it still doesn't seem to help.
Here is a picture of the code acting up in action:

Those red lines are supposed to be squares, and the car... isn't supposed to look like that.  If someone could tell me what I'm doing wrong, that'd be awesome.

A: You have to clear screen before you draw new frame.
 gameDisplay.fill((0,0,0))

And after clearing screen you have to draw all elements again.
You will have to reorganize you code to fill, draw and update in one place
You can organize mainloop this way (simple example)
# --- mainloop ---

clock = pygame.time.Clock()
is_running = True

while is_running:

    # --- events ---

    for event in pygame.event.get():

        # --- global events ---

        if event.type == pygame.QUIT:
            is_running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                is_running = False

        # --- objects events (without draws)---

        '''
        player.handle_event(event)
        '''

    # --- updates (without draws)---

    '''
    player.update()
    '''

    # --- draws (without updates) ---

    screen.fill(BLACK) # only once in loop

    '''
    player.draw(screen)
    '''

    pygame.display.update() # only once in loop

    # --- FPS ---

    clock.tick(25)

full example: PyGame simple template and other templates

A: there is an easy, cheap way of getting the image off the screen...
 say the screen is 400 x 400 just change the coordinates of the picture to where the x is like 500 and the y is like 600 so that it is placed outside of the pygame canvas


text:
Q: Segmentation of a geometrical shapes I am trying to segment a QFN package on the x-ray image of the PCB. The general description of QNF package is that it's square or rectangle in the centre with the rectangular pins on the edge. The example is on this image:
I can segment the rectangles on the x-ray image quite good but I dont know how to write the condition to segment only the QFN package. The package can be square or rectangle and can have different number of pins on the edge. My idea is to check the close neighborhood of each rectangle filter out rectangles that are too big and somehow check if the remaining rectangles are all around. Is there a better approach? Or how would you check if the big rectangle is surrounded by the small ones?
I am using python 3.5 and OpenCV 3.1

A: This is going to be a bit long, I would give you some basic techniques and guidelines along with some advanced suggestions to increase the accuracy of QNF package detection.
Assuming that you already have the red marked contours stored in a variable contours.
First of all define the upper and lower limit of contour area you want to filter. As per the given image, the area range of central region comes out to be:
CHIP_CENTER_AREA_LOWER, CHIP_CENTER_AREA_UPPER = 20*1000, 25*1000

So we iterate over all contours and filter the contour which have area in above range, it would eliminate the smaller contours, and we would be examining only the larger contours.
probable_chip_center_contour_idx = []
for i in xrange(len(contours)):
    cnt = contours[i]
    area = cv2.contourArea(cnt)
    if CHIP_CENTER_AREA_LOWER < area < CHIP_CENTER_AREA_UPPER:
        probable_chip_center_contour_idx.append(i)

Now after filtering out probable contours on basis of area, we would check the number of neighbouring contours(pins). Those central contours which would have expected number of neighbouring contours within a given radius would be out final result.
radius = 80
EXPECTED_NEIGHBOURING_PINS = 28
for i in probable_chip_center_contour_idx:
    cnt = contours[i]
    cnt_bounding_rect = cv2.boundingRect(cnt)
    extended_cnt_bounding_rect = [cnt_bounding_rect[0] - radius, cnt_bounding_rect[1] - radius,
                                  cnt_bounding_rect[2] + 2*radius, cnt_bounding_rect[3] + 2*radius]
    neighbouring_contours = 0
    for probable_neighbouring_contour in contours:
        probable_bounding_rect = cv2.boundingRect(probable_neighbouring_contour)
        if is_rect_inside(probable_bounding_rect, extended_cnt_bounding_rect):
            neighbouring_contours += 1
    if neighbouring_contours > EXPECTED_NEIGHBOURING_PINS:
        print "QFN Found"


text:
Q: When do two positive braids represent the same link? Let $B_n$ be the braid group on $n$ strands, with the usual generators: $s_1, \ldots, s_{n-1}$ and their inverses, where $s_i$ is a positive half-twist interchanging the strands labelled $i$ and $i+1$.  Markov's theorem says that two elements of the braid group have closures giving the same knot in $S^3$ when they are related by a sequence of moves, each of which is either a conjugation $\beta \to s_i^{\pm} \beta s_i^{\mp}$ or the inclusion $B_n \to B_{n+1}$ taking $\beta \to \beta s_n^{\pm}$.
Recall a braid is positive if it can be written as $s_{i_1} \cdots s_{i_k}$.  Conjugation does not generally preserve positive braids, but it can: $s_1^{-1} (s_1 \beta) s_1$ is of course positive when $\beta$ is.

If two positive braids represent the same knot, can they be related by a sequence of Markov moves in which only positive braids appear?

A: I'll make some comments on this question.
First of all, two positive braids which are conjugate (equivalently represented by the same labelled oriented 2-component link when taken with the braid axis) will be equivalent by a sequence of positive braid type III Reidemeister moves. This follows from Garside's solution to the conjugacy problem in the braid group (see also Theorem 9.4.2 by Thurston).
For closures of 3-strand braids, the complete classification was given by Birman-Menasco. They show that most 3-strand braids which represent the same link are conjugate, except for braids which are braid index 1 or 2, and a special class of braids $s_1^ps_2^qs_1^rs_2$, where $p,q,r \geq 2$ (restricting to the positive case) which are equivalent to $s_1^ps_2s_1^rs_2^q$. One sees directly from their classification that the braid index 1 and 2 cases have a unique positive representative up to conjugacy. For the exceptional case, they show (or refer to a result of Fein which is given on p. 100 of Birman's book) that these exceptional cases are conjugate after a single stabilization. In fact, one may check directly that the stabilization may be taken to be positive, so this answers your question in the case of pairs of positive 3-strand braids. Also, note that these two examples are related by flypes, and the equivalence by one positive stabilization holds for any pair of braids which are locally related by the same type of flype given in Figure 1.2 (but which are not necessarily conjugate).
If the answer to your question is true, then I think it might give an efficient algorithm to test if two positive braids are equivalent. For positive braids, the Seifert genus is determined by the braid index and number of crossings. When one does several positive Markov stabilizations, one sees that in the positive conjugacy class of the stabilized braid, most braid generators will occur only once. So I think one ought to be able to get a bound on the number of stabilizations needed, which would then lead to an algorithm to tell them apart. One could try to apply the techniques of Birman-Menasco (after Bennequin) to attempt to understand your conjecture.

A: This was proven in the Paper "Fibered Transverse Knots and the Bennequin Bound" by John B. Etnyre, Jeremy Van Horn-Morris (https://arxiv.org/abs/0803.0758):

Corollary 1.8. Any two positive braids representing a link L are related by positive Markov
  moves and braid isotopy.

A: The answer is "No". Consider two braids
$$
\beta_1 = s_1^3 s_2^3 s_3,\qquad \beta_2 = s_1 s_2^3 s_3^3
$$
They obviously represent the same knot. Moreover, they are conjugate. But
Claim 1: $\beta_2$ cannot be transformed to $\beta_1$ by successive conjugations by $s_i^{\pm 1}$ preserving positivity. I.e. you need to conjugate by longer braids. This I checked on a computer. Since there are only finitely many positive braids of given length this is a finite calculation.
Claim 2: $\beta_2$ cannot be transformed to $\beta_1$ by a sequence of Markov moves preserving positivity. This is conjectural. I checked it on a computer by going through all possible stabilizations with up to 10 strands.
On the other hand, if you allow conjugations by arbitrary short braids (=lifts of permutations) instead of only conjugations by Artin generators, the statement is true by the above cited paper "Fibered Transverse Knots and the Bennequin Bound" by John B. Etnyre, Jeremy Van Horn-Morris (https://arxiv.org/abs/0803.0758) and Lemma 6.7 from Kassel, Turaev - "Braid Groups" (thanks to Vera Vertesi for the latter reference).


text:
Q: How to put Article inside WebPage element? So I have a WebPage and inside that WebPage I have an Article.
Now I know it is not a problem, but when I use this tool:
https://developers.google.com/webmasters/structured-data/testing-tool/
I get some note that the WebPage has no elements such as name and description, in that case what should I do? Should ignore it? Because even if I set meta tags for name and description it will be 100% the same as the Article one and then it might double content or doubled values, what should I do?
Example of my page:

<title></title>

     HERE COME THE NAVIGATION CODE

Name

Description

 Cat Overview

 Cat Breeds

 Cat Articles

 Cat Adoption

A: Your WebPage is not empty. It has 5 relatedLink properties. But even if it were empty, it would not be a problem.
The name for WebPage could be the value of your title element (e.g., typically including the page and the site name), while the name of the Article could be the value of the page heading (e.g., typically without site name).
You could link the SiteNavigationElement with the WebPage item (currently both are top-level items, not related to each other), for example with the hasPart property:

I guess the same property could be used to link the WebPage with the Article. Unfortunately, Schema.org lacks a property for denoting the main content/item of a WebPage (mainContentOfPage can't be used).

A: Like this:

        <meta itemscope itemprop="mainEntityOfPage"  itemType="https://schema.org/WebPage" itemid="https://google.com/article"/>

Article headline

            By John Doe

        A most wonderful article

            <meta itemprop="url" content="https://google.com/thumbnail1.jpg">
            <meta itemprop="width" content="800">
            <meta itemprop="height" content="800">

                <meta itemprop="url" content="https://google.com/logo.jpg">
                <meta itemprop="width" content="600">
                <meta itemprop="height" content="60">

            <meta itemprop="name" content="Google">

        <meta itemprop="datePublished" content="2015-02-05T08:00:00+08:00"/>
        <meta itemprop="dateModified" content="2015-02-05T09:20:00+08:00"/>

source one, two


text:
Q: How to only lowercase quoted string in VIM Say I have a file with the following content:
Apple 'BANANA' ORANGE 'PEACH'

What is the regex to convert all quoted uppercase to lowercase?
The expected output file should look like:
Apple 'banana' ORANGE 'peach'

A: Try
:%s/'\w\+'/\=tolower(submatch(0))/g

'\w\+' match any word that is inside quotes. and replace it with the lowercase version of the match. \= tells substitute to evaluate the expression tolower(submatch(0)) where tolower() switches the string found in submatch(0) (the whole match) to lower case.

You can also use the \L atom to turn the string after it to lower case and \0 is the same as submatch(0)
:%s/'\w\+'/\L\0/g

Take a look at :h s/\L