text:
Q: IllegalArgument exception I am trying hibernate+Spring for the first time and getting this error while trying to insert into DB. The String is coming from the url or a default value :-
    @RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {

    InsertTest test = new InsertTest();
    test.insert(name);
    return new Greeting(counter.incrementAndGet(),
                        String.format(template, name));
}

And the DAO method is :-
    public void insert(String name) {

    Resource r=new ClassPathResource("D:\\work\\Spring\\RestAPI\\src\\main\\java\\db\\app.xml");
    BeanFactory factory=new XmlBeanFactory(r);

    EmployeeDao dao=(EmployeeDao)factory.getBean("d");

    Employee e=new Employee();
    e.setId(114);
    e.setName(name);
    e.setSalary(50000);

    dao.saveEmployee(e);

}

And I am getting error:-
    java.lang.IllegalArgumentException: name
    at sun.misc.URLClassPath$Loader.findResource(Unknown Source) ~[na:1.8.0_131]
    at sun.misc.URLClassPath.findResource(Unknown Source) ~[na:1.8.0_131]
    at java.net.URLClassLoader$2.run(Unknown Source) ~[na:1.8.0_131]
    at java.net.URLClassLoader$2.run(Unknown Source) ~[na:1.8.0_131]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_131]
    at java.net.URLClassLoader.findResource(Unknown Source) ~[na:1.8.0_131]
    at org.springframework.boot.loader.LaunchedURLClassLoader.findResource(LaunchedURLClassLoader.java:58) ~[gs-rest-service-0.1.0.jar:0.1.0]
    at java.lang.ClassLoader.getResource(Unknown Source) ~[na:1.8.0_131]
    at java.net.URLClassLoader.getResourceAsStream(Unknown Source) ~[na:1.8.0_131]
    at org.apache.catalina.loader.WebappClassLoaderBase.getResourceAsStream(WebappClassLoaderBase.java:1055) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:166) ~[spring-core-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330) ~[spring-beans-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304) ~[spring-beans-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
    at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:79) ~[spring-beans-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
    at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:67) ~[spring-beans-4.3.7.RELEASE.jar!/:4.3.7.RELEASE]
    at main.java.db.InsertTest.insert(InsertTest.java:21) ~[classes!/:0.1.0]
    at main.java.hello.GreetingController.greeting(GreetingController.java:23) ~[classes!/:0.1.0]

A: The same problem as in your previous question (next time just ask for clarifications in the comments):
Error thrown file does not exist even though it is there

You need to specify this path:
Resource r = new ClassPathResource("main/java/db/app.xml");

This is not a file system path, but a path that begins from the root package.


text:
Q: A* algorithm - ellipse property of expension Based on the ellipse property of A*, why this algorithm closes
all nodes in a series of expanding ellipses?

A: A* uses the function f(x) = g(x) + h(x) to assess what node to visit next, where g(x) is the actual cost for going from the start to x and h(x) is the estimated cost to go from x to the target (= heuristic).
Let's take a look at this in the continuous case in the Euclidean plane, where we want to go from (0, 0) to (10, 20). Then:
g(x) = Length(x)

The shape of the exploration front depends heavily on the heuristic. Let's start with the perfect heuristic
h(x) = Length(x - (10, 20))

We can plot the value of g(x) + h(x) over the plane and see the order of visited nodes (points with smaller f will be visited first). Doing so, we should be aware that a node cannot be visited if none of its neighbors have been visited before, so the actual value is only an indication of the order. We'll keep this in mind. Using the perfect heuristic, we get the following picture:

All points on the connection between start and target have the same f cost, which is equal to the distance of start and target. And if we inspect f, we see that
f = Length(x - (0, 0)) + Length(x - (10, 20)),

which is exactly the implicit form of an ellipse with the start and target as foci.
I said that the shape depends on the heuristic. A heuristic is valid if it is a lower bound of the actual distance. Let's try
h(x) = 0.5 * Length(x - (10, 20))

Now, the algorithm will start to explore more points surrounding the start before it reaches the target. Especially, all points within the contour before the target point will be visited.
We can even go one step further and set
h(x) = 0

This is the setting for Dijkstra's algorithm, where we cannot say anything about the distance to the target:

Here, the algorithm will visit nodes in disks around the start point.
One common approximation of the distance to the target is the Manhattan distance because it is cheap to compute:
h(x, y) = |x - 10| + |y - 20|

This heuristic is not valid because it is not a lower bound on the actual distance. It gives us:

This is exactly a case where points close to the target have a lower f score than those close to the start. Although they have a lower value in this figure, they will of course not be visited first because their neighbors have not been explored yet. Here is a close-up:

We can make the heuristic valid by introducing a constant factor:
h(x, y) = 1/sqrt(2) * (|x - 10| + |y - 20|)

This will give us a valid heuristic with a proper front shape:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails simple_format and display of 'Read More' link inline with text Should have been very easy but somehow cannot get it to work. I want to display truncated text on my blog home page with a 'read more' link that shows up inline with the text i.e.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ac tortor et felis aliquet vestibulum sed in sem. Aliquam pharetra ultricies nunc, non pellentesque ... Read More
Since I use simple_format for my text, all breaks in the text get wrapped in  tags and I get Read More in a separate line as below
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ac tortor et felis aliquet vestibulum sed in sem. Aliquam pharetra ultricies nunc, non pellentesque ...
Read More
How do I place it inline after a < p > tag. Guess it's more of a CSS question rather than a Rails one. Again, I feel this should be super simple. What am I forgetting?
Here's the code snippet in the view
<%= simple_format truncate(h(feed.description), length: 400, separator: ' ') %><%= link_to "Read More", feed_path(feed)%>

A: I suspect that you can just put your link inside the simple_format content-parameter link this:
<%= simple_format truncate((h(feed.description) + link_to("Read More", feed_path(feed))), length: 400, separator: ' ') %>

(Note: not tested)


text:
Q: How do you completely remove the button border in wpf? I'm trying to create a button that has an image in it and no border - just like the Firefox toolbar buttons before you hover over them and see the full button.
I've tried setting the BorderBrush to Transparent, BorderThickness to 0, and also tried BorderBrush="{x:Null}", but you can still see the outline of the button.

A: You may have to change the button template, this will give you a button with no frame what so ever, but also without any press or disabled effect:
    <Style x:Key="TransparentStyle" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Background="Transparent">
                        <ContentPresenter/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

And the button:
<Button Style="{StaticResource TransparentStyle}"/>

A: You can use Hyperlink instead of Button, like this:
        <TextBlock>
            <Hyperlink TextDecorations="{x:Null}">
            <Image Width="16"
                   Height="16"
                   Margin="3"
                   Source="/YourProjectName;component/Images/close-small.png" />
            </Hyperlink>
        </TextBlock>

A: Try this
<Button BorderThickness="0"
    Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" >...

A: What you have to do is something like this:
<Button Name="MyFlatImageButton"
        Background="Transparent"
        BorderBrush="Transparent"
        BorderThickness="0"
        Padding="-4">
   <Image Source="MyImage.png"/>
</Button>

Hope this is what you were looking for.
Edit: Sorry, forgot to mention that if you want to see the button-border when you hover over the image, all you have to do is skip the Padding="-4".

A: I don't know why others haven't pointed out that this question is duplicated with this one with accepted answer.
I quote here the solution: You need to override the ControlTemplate of the Button:
<Button Content="save" Name="btnSaveEditedText"
                Background="Transparent"
                Foreground="White"
                FontFamily="Tw Cen MT Condensed"
                FontSize="30"
                Margin="-280,0,0,10"
                Width="60"
                BorderBrush="Transparent"
                BorderThickness="0">
    <Button.Template>
        <ControlTemplate TargetType="Button">
             <ContentPresenter Content="{TemplateBinding Content}"/>
        </ControlTemplate>
    </Button.Template>
</Button>

A: You may already know that putting your Button inside of a ToolBar gives you this behavior, but if you want something that will work across ALL current themes with any sort of predictability, you'll need to create a new ControlTemplate.
Prashant's solution does not work with a Button not in a toolbar when the Button has focus.  It also doesn't work 100% with the default theme in XP -- you can still see faint gray borders when your container Background is white.

A: Why don't you set both Background & BorderBrush by same brush
 <Style TargetType="{x:Type Button}" >
        <Setter Property="Background" Value="{StaticResource marginBackGround}"></Setter>
        <Setter Property="BorderBrush" Value="{StaticResource marginBackGround}"></Setter>
 </Style>

<LinearGradientBrush  x:Key="marginBackGround" EndPoint=".5,1" StartPoint="0.5,0">
    <GradientStop Color="#EE82EE" Offset="0"/>
    <GradientStop Color="#7B30B6" Offset="0.5"/>
    <GradientStop Color="#510088" Offset="0.5"/>
    <GradientStop Color="#76209B" Offset="0.9"/>
    <GradientStop Color="#C750B9" Offset="1"/>
</LinearGradientBrush>


text:
Q: Using count function or create specific column for counting in sql I working on groups project. I have those tables :

I can get the number of members for each group by using count function :
SELECT COUNT(1) AS Counts FROM [Groups].[GroupMembers]
WHERE GroupId=Id;

Or I can add another column to Groups table for counting and every time new member join to the group, this field will increase by one. Does it better to use count function or add another column for counting ? in other words, what are the advantages and disadvantages of each method ?

A: Creating a column to store the count's is not recommend at all.
When you want the count of each group you can use a simple Select query to show the count of each group.
SELECT G.groupid,
       Count(userid)
FROM   groups G
       LEFT OUTER JOIN groupmembers GM
                    ON G.groupid = GM.groupid
GROUP  BY G.groupid

In case you want to add a new column then you will require a Trigger on GroupMembers table to update the count column in Groups table  when a new user is added to any group in GroupMembers table

A: It depends on your table engine. If your table engine is MyISAM it would be much faster because it would simply read number of rows in the table from stored value, however Innodb engines will need to do a full table scan.
It is not recommended to store a count inside of the table itself, so if this is something you're worried about, use the MyISAM engine if possible.
Storing a value in the table would needlessly require an extra UPDATE query on each new/lost membership.


text:
Q: how to get data from the background to be displayed in popup page i want to display the array data i have in the background when the get data button is clicked but nothing is done when i click the button am very new for chrome ext. thanks.
manifest.json:
{
    "name":"modz",
    "manifest_version":2,
    "version":"1.0",
    "description":"this ext. will help you record all the urls you have visited",

    "background": {
    "scripts": ["background.js"]

  },

    "browser_action":
    {
    "default_icon":"icon.png",
    "default_popup":"popup.html"
    },

    "permissions":[
          "tabs"
        ]

}

background.js:
var data=[];
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    var url = tab.url;
    if (url!=="undefined" && changeInfo.status=="complete")
  {
   data.push (tab.url);
   alert(data.length);
  }
  }

);
chrome.runtime.onMessage.addListener(function(message,sender,sendrespose){
//send the array data back
});

popup.js:
document.addEventListener('DOMContentLoaded', function () {
   document.getElementById('btn').addEventListener('click',function(){
    chrome.runtime.sendMessage("getdata");
   });
});

popup.html
<!DOCTYPE html>

<input  id="btn"  type="button"  value="get data" />

A: The official reference for messaging is here.  In your case, you'd want background.js to have
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
    sendResponse({"dataArray":data});
});

popup.js would have
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('btn').addEventListener('click',function(){
        chrome.runtime.sendMessage({},function(response){
            document.getElementById("data").textContent = response.dataArray.toString();
        });
    });
});

This would also work in a content script.  But if the content script were running at the default document_end, it wouldn't need the DOMContentLoaded event, since document_end happens afterward.
This is actually sending an empty message (the empty object {}).  If there were different messages you wanted to send, you'd want to change that.  This is also why message isn't used in background.js.
Since you're not really sending a message, another approach is to use getBackgroundPage.  background.js wouldn't need the listener, and popup.js would have:
chrome.runtime.getBackgroundPage(function(backgroundWindow){
    document.getElementById("data").textContent = backgroundWindow.data.toString();
});

Two more things:

*

*popup.html can't use the absolute path to popup.js.  Put both in the extension directory, and use a relative path: src="popup.js".

*Google recommends that you transition background pages to event pages.  The biggest difference is that you can't have the global variable data in event pages (you can, but it gets reset when the event page reloads).  If you have trouble getting that working, I'd recommend getting your extension working as a background page, and then posting another question.


text:
Q: Ansible URI not working with until and async I'm trying to do an API call which sometimes timesout the first try but succeeds the second try. So I need the Ansible task to retry a few times until the response status is 200 (OK).
When using the below tasks it works as expected.
---
- hosts: localhost
  gather_facts: no
  vars:
    ip:
      - 10.0.0.1
      - 10.0.0.2

  tasks:
    - name: "Get host by IP"
      uri:
        url: "http://cpi.com/webacs/api/v4/data/Devices.json?.full=true&ipAddress={{ item }}"
        method: GET
        status_code: 200
      register: apiResult
      loop: "{{ ip }}"
      retries: 1
      delay: 5
      until: apiResult.status == 200

However when I want to do this with async due to the high number hosts I need to check it doesn't work as it seems there is no key status. Instead the output is put into a results_file. I have tried several things here like looking up that results_file (which contains the status code in json) but that also does not seem to work.
---
- hosts: localhost
  gather_facts: no
  vars:
    ip:
      - 10.0.0.1
      - 10.0.0.2

  tasks:
    - name: "Get host by IP"
      uri:
        url: "http://cpi.com/webacs/api/v4/data/Devices.json?.full=true&ipAddress={{ item }}"
        method: GET
        status_code: 200
      register: asyncApiResult
      loop: "{{ ip }}"
      retries: 1
      delay: 5
      async: 40
      poll: 0
      # until: asyncApiResult.status == 200 <- does not seem to exist
      # until: asyncApiResult is succeeded <- not working because timeout is also a success
      until: (lookup('file', asyncApiResult.results_file) | from_json).get('status') == '200'

Does anyone have an idea how to get this working?

A: first of all the register variable of the task where you kept async and poll doesn't have status. the next task i.e async_status task contains it so you have to use that task to put the condition on status_code


text:
Q: Performance & memory while saving record locally in device I have a query for saving data locally in the device. I have tableview with itemname on the cell. The user should be able to delete an item from the list by swiping them to the right. These should not reappear subsequently to this action either in the current session or subsequent launches of the app.
I can create an array of deleted items & store them in NSUserDefault, plist or cache. Next time of table load I will exclude these stored records.
What is the best option for doing above operation? Which one is the best (NSUserDefault, plist or cache or anything else) in terms of memory, fast operation, user interaction etc?

A: What you should use

*

*You might want to use CoreData, because it can handle a large amount of data and is also very simple to use. In terms of memory and performance, it works quite well too. It also has the advantage that it can store any type of data.

*On the other hand, a very solid alternative is Swift Realm, because it is very efficient and can also store large amounts of data. Its performance is great, I think you should consider it as an option.

What you should avoid

*

*When it comes to UserDefaults, I think it is the worst thing to use in such a case, because it can only handle small amounts of data. It's performance is not great either, so I strongly recommend you not to use it.

Note: Instead of storing the deleted items, you should consider saving the valid items instead, and remove the unwanted items from the data once the user chooses to delete them. Also, be careful when storing data locally and avoid saving sensitive data unencrypted.


text:
Q: Transparent image overlay Mapbox GL JS I want to draw a circle around an object in Mapbox GL JS, but it does not seem to support drawing something like that. So I tried creating a PNG with a red circle and a transparent background in Photoshop. But when I load the image on the map, the image loses its transparency.

The code I used to generate this is:
var sourceObj = new mapboxgl.ImageSource({
        url: '/img/circle-red.png',
        coordinates: [
            [-80.425, 46.437],
            [-71.516, 46.437],
            [-71.516, 37.936],
            [-80.425, 37.936]
        ]
});

map.addSource('someimage', sourceObj);

map.addLayer({
    "id": "someimage",
    "source": "someimage",
    "type": "raster"
});

Does somebody know how I can achieve an transparent background? Or does someone know an alternative way to draw a circle on the map?
Thanks in advance.

A: I know it's a year late, but if anyone runs into this again, there is a raster-opacity property on the layer. See https://www.mapbox.com/mapbox-gl-js/example/adjust-layer-opacity/.
map.addLayer({
  "id": "current_image",
  "source": "current_image",
  "type": "raster",
  "paint" : {
    "raster-opacity" : 0.5
  }
});

If you're working with an image where you'll know the opacity, that should do the trick!

A: I have the same issue. My current workaround are 8-bit PNGs, but they only have one color that is transparent.


text:
Q: How to write the data in excel file using pandas excel writer? I have some code which gives output through several for loops in the form of multiple lists and I want to write the output in excel or csv file using pandas excel writer.
from pulp import *
from openpyxl import load_workbook
import pandas as pd
import numbers
from pulp import solvers
import xlwt

P=[4.645885257, 4.481959238,    4.160581972,    2.893299763,    2.746552049,    2.762327167,    2.785312466,    2.782704044,\
2.761575576,    2.790301008,    2.826271593,    2.98196142, 3.106517237,    3.049694785,    2.841111886,    2.469119048,\
2.424998603,    2.482937879,    2.541880038,    2.544940077,    2.526766508,    2.539441678,    2.60810043, 2.782490319]
X=[-50, -40, -30, -20, -10, 0, 10, 20, 30, 40]
S=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]

x=10
s=16
n=24

F=[[0 for j in range(x)] for i in range(s)]

def xyz():
    Fbar=list()
    Xbar=list()
    Mega=[22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
    for k in Mega:
        for f in F:
            try:
                FFF=max([x for x in f if isinstance(x, numbers.Number)])
                XXX=X[f.index(max([x for x in f if isinstance(x, numbers.Number)]))]
                Fbar.append(FFF)
                Xbar.append(XXX)
            except ValueError:
                FFF="NA"
                Fbar.append(FFF)
                Xbar.append(FFF)
        for i in range(s):
            for j in range(x):
                if 150>=(S[i]+X[j])>=S[Xbar.index(max([x for x in Xbar if isinstance(x, numbers.Number)]))]:
                    FFFFF=(S[i]+X[j])/10
                    F[i][j]=-X[j]*P[k]+Fbar[int(FFFFF)]
                if 150<(S[i]+X[j])<S[Xbar.index(max([x for x in Xbar if isinstance(x, numbers.Number)]))]:
                    F[i][j]="NA"

        Xbar=list()
        for f in F:
            try:
                FFF=max([x for x in f if isinstance(x, numbers.Number)])
                XXX=X[f.index(max([x for x in f if isinstance(x, numbers.Number)]))]
                Fbar.append(FFF)
                Xbar.append(XXX)
            except ValueError:
                FFF="NA"
                Fbar.append(FFF)
                Xbar.append(FFF)
        print(Xbar)

        df= pd.DataFrame(Xbar)
        writer= pd.ExcelWriter('C:\Fourth Term @ Dal\Project\Directive studies\output.xlsx', engine='xlsxwriter')
        df.to_excel(writer, sheet_name='Sheet1', startcol=0, startrow=1, header=False, index=True)
        workbook= writer.book
        writer.save()

xyz()

This is how print output look like:
[-50, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50]
[40, 40, 30, 20, 10, -50, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50]
[40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0, -10, -20, -30, -40, -50]
[0, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50]
[40, 40, 30, 20, 10, 0, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50]
[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0]
[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0]
[40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0, -10, -20, -30, -40]
[0, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50]
[0, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50]
[0, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50]
[40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0, -10, -20, -30, -40, -50]
[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0]
[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0]
[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0]
[40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0, -10, -20, -30, -40]
[40, 40, 40, 40, 30, 20, 10, 0, -10, -20, -30, -40, -50, -50, -50, -50]
[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0]
[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 30, 20, 10, 0]
[0, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50]
[0, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50]
[0, -10, -20, -30, -40, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50, -50]

And this is what I got in excel (output.xlsx):
0   0
1   -10
2   -20
3   -30
4   -40
5   -50
6   -50
7   -50
8   -50
9   -50
10  -50
11  -50
12  -50
13  -50
14  -50
15  -50

I just got the last list out of several lists from the print output copied in the excel file but what I want is the complete output (Xbar in above code) to be copied in the excel file. Thanks in advance. :)

A: I haven't been able to reproduce the same output on my computer. But here isn't the question.
The reason why you only have the last row is that you're writing the csv file in the for loop. So you only get the last row because you overwrite all of them each time.
On solution (I think the simplest here), is to save your results over each iteration in a results dataframe (here output_df) and then export this dataframe in a csv file.
In the code below, I save the results of each mega loop as a new column of output_df.
Here the code:
from pulp import *
from openpyxl import load_workbook
import pandas as pd
import numbers
from pulp import solvers
import xlwt

P = [4.645885257, 4.481959238,    4.160581972,    2.893299763,    2.746552049,    2.762327167,    2.785312466,    2.782704044,
     2.761575576,    2.790301008,    2.826271593,    2.98196142, 3.106517237,    3.049694785,    2.841111886,    2.469119048,
     2.424998603,    2.482937879,    2.541880038,    2.544940077,    2.526766508,    2.539441678,    2.60810043, 2.782490319]
X = [-50, -40, -30, -20, -10, 0, 10, 20, 30, 40]
S = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]

x = 10
s = 16
n = 24

F = [[0 for j in range(x)] for i in range(s)]

def xyz():
    Fbar = list()
    Xbar = list()
    Mega = [22, 21, 20, 19, 18, 17, 16, 15, 14,
            13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

    df_output = pd.DataFrame()

    for count, k in enumerate(Mega):
        for f in F:
            try:
                FFF = max([x for x in f if isinstance(x, numbers.Number)])
                XXX = X[f.index(
                    max([x for x in f if isinstance(x, numbers.Number)]))]
                Fbar.append(FFF)
                Xbar.append(XXX)
            except ValueError:
                FFF = "NA"
                Fbar.append(FFF)
                Xbar.append(FFF)
        for i in range(s):
            for j in range(x):
                if 150 >= (S[i]+X[j]) >= S[Xbar.index(max([x for x in Xbar if isinstance(x, numbers.Number)]))]:
                    FFFFF = (S[i]+X[j])/10
                    F[i][j] = -X[j]*P[k]+Fbar[int(FFFFF)]
                if 150 < (S[i]+X[j]) < S[Xbar.index(max([x for x in Xbar if isinstance(x, numbers.Number)]))]:
                    F[i][j] = "NA"

        Xbar = list()
        for f in F:
            try:
                FFF = max([x for x in f if isinstance(x, numbers.Number)])
                XXX = X[f.index(
                    max([x for x in f if isinstance(x, numbers.Number)]))]
                Fbar.append(FFF)
                Xbar.append(XXX)
            except ValueError:
                FFF = "NA"
                Fbar.append(FFF)
                Xbar.append(FFF)
        print(Xbar)

        df_output["Mega_{0}".format(k)] = Xbar

    print(df_output)
    writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter')
    df_output.to_excel(writer, sheet_name='Sheet1', startcol=0, header=True, index=True)
    writer.save()

xyz()

Output printed:
#     Mega_22  Mega_21  Mega_20  Mega_19  Mega_18  Mega_17  Mega_16  ...  Mega_7  Mega_6  Mega_5  Mega_4  Mega_3  Mega_2  Mega_1
# 0       -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 1       -10      -10      -10      -10      -10      -10      -10  ...     -10     -10     -10     -10     -10     -10     -10
# 2       -20      -20      -20      -20      -20      -20      -20  ...     -20     -20     -20     -20     -20     -20     -20
# 3       -30      -30      -30      -30      -30      -30      -30  ...     -30     -30     -30     -30     -30     -20     -20
# 4       -40      -40      -40      -40      -40      -40      -40  ...     -40     -40     -40     -40     -40     -30     -30
# 5       -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -40     -40
# 6       -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 7       -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 8       -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 9       -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 10      -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 11      -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 12      -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 13      -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 14      -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50
# 15      -50      -50      -50      -50      -50      -50      -50  ...     -50     -50     -50     -50     -50     -50     -50

# [16 rows x 22 columns]

The csv file:


text:
Q: ColdFusion JDBC Connection String Issue I'm trying to setup a 3rd party JDBC driver as a datasource, but it appears to not matter what I put in the Connection String field in CFAdmin, it doesn't seem to use it at all.
User=user@account.com;Password=!password;

Errors out with Login failed: You must provide a user and password to login.
I tried putting random text into the Connection String field expecting it to error out, but nothing happened either.
I was wondering if I was entering the data wrong (I also tried the entire connection string with the jdbc:, but that did not work either) or if there was some way to verify the entire connection string that ColdFusion was trying to use.
I'm not trying anything special inside of my cfquery tag: <cfquery name="output" datasource="mySource"> so that should not be the issue. I can get around the user/password issue by hard-coding these values in the cfquery tag, but there is a 3rd key that I need to provide as a connection value as well.
The issue shouldn't be with my connection string, because the following worked with pure Java:
conn = DriverManager.getConnection("jdbc:mydriver:User=user;Password=password;AccessToken=accessToken;");
.
An interesting addition...ColdFusion appears to not care at ALL what is at the end of my URL as long as the beginning is correct...
jdbc:mydriverrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr:
gives the username/password error. Whereas:
jdbc:mydriveer:
gives me an "unable to find driver" error.
.
edit: I also experience this issue in CF9, so it isn't just an issue with CF10
.
edit: I'm able to set the username/password inside of the CF datasource settings, but it still appears to be ignoring anything I put at the end of the URL or in the connection strings (AccessToken is still needed).
.
edit: I tried a DSNless connection: http://www.hostmysite.com/support/cfusion/dsnless/ but it behaves similarly to CFAdmin, whereas it is ignoring the connection string portion.
Login failed: You must provide a user and password to login.
..

A: I don't know what DataSource implementation you are using, but DataSources have their own javabeans-style properties, including user and password. You will probably need to use those instead of providing a properties with the URL.


text:
Q: Must a new Document in MongoDB be exactly the same as the Schema? I am facing problems in the creation of new Documents in MongoDB using Mongoose.
Must the new Documents be exactly the same as the Schemas?
I mean I have the following Schema:
ar userSchema = new Schema({

        userID: Number,
        userName: String,
        userEmail: String,
        teams:Array,
        fbUID: String,
        googleUID: String,
        twitter: String

});

But to create a new user Document I dont have all the fields, so my Document will not contain all the field as the Schema above.
For example, I am adding a new document based on the Schema above. My Doc is:
var users = mongoose.model('users',userSchema);

 var user = new users({
        userID: id, //give the id of the next user in Dbase
        userName: userName,
        userEmail: 'userEmail',
        teams:[],
        fbUID: '1234'
     });

user.save(function(err, user){
        if(err) return console.error(err);
        log.d("user salved", user);
     });

So, I dont have all the fields, and I could not save any Doc so far.
Does it matter if I don't have all the fields in the Schema in  the new Document?
UPDATE:
and the second problem is that I am getting one of these :
 fbUID,
        googleUID,
        twitter

through a function, and I don't know which of those I am receiving, so I am trying to save the Document this way:
function salveUser(userName, socialMediaType, socialMediaID){

    var id;

      users.count(function(err, count){
        if(err){
            log.d("Err in counting files")
        }
        id = count;

      });

     var user = new users({
        userID: id, //give the id of the next user in Dbase
        userName: userName,
        userEmail: 'userEmail',
        teams:[],
        socialMediaType : socialMediaID
     });

     user.save(function(err, user){
        if(err) return console.error(err);
        log.d("user salved", user);
     });

     currentSession =  sessionOBJ.login(id, socialMediaID);

     return currentSession;
}

}
That is why I would like to know if Mongoose switch the key in the Document by the word I am receiving in my function or if it uses the exactly word I am putting there, in this case "socialMediaType".
Does someone know?

A: It looks like you're code is fine as Leonid said in the comments
I would try saving a user with all direct values to rule out any variable not being set....
So try this:
var user = new users({
    userID: 11, //give the id of the next user in Dbase
    userName: 'John',
    userEmail: 'John@john.com',
    teams:['Blue', 'Green'],
    fbUID: '1234'
 });

If that works then the problem is probably that the id or userName variables haven't been set before actually hitting this message.
You don't have to put values for all fields just because they are in the model.
Best of luck!

A: Answering your main question: no, new Documents shouldn't be exactly the same as the Schemas.
Actually, none of the document's fields defined in its schema are required in order to save it, unless you explicitly marked some of them as required.
But you made several mistakes in your salveUser function.

First, your id = count assignment will take place long after user document will be created and saved, because  users.count is asynchronous. It means that userID in your example will always be udefined.
To fix it you should wait for users.count to finish before trying to use it's results:
users.count(function(err, count){
  if(err){
    return log.d("Err in counting files")
  }

  var user = new users({
    userID: count, //give the id of the next user in Dbase
    userName: userName
    /* other  fields */
  });

  user.save(/* your callback */);
});

Second, it looks like you're trying to assign a value socialMediaID to a field with a name equal to socialMediaType value. But you can't do it the way you're trying ti do it. So, instead of setting fbUID/googleUID field you're trying to set an unexisting socialMediaType field.
To fix it you should use [] assignment:
var user = new users({
  userID: id, //give the id of the next user in Dbase
  userName: userName,
  userEmail: 'userEmail'
});
user[socialMediaType] = socialMediaID;

Since you don't have a unique index on userID field an since MongoDB automatically assigns an unique _id to all documents, you should be able to successfully .save() your document.

But in your question you said that you're unable to do it, meaning you have some other problem in your code. Please, post an exact exception you're getting from mongoose in .save() callback.


text:
Q: How to improve the HTML Table Styling that is to be converted into a PDF File I have a Python code that is creating HTML Tables and then turning it into a PDF file. This is the output that I am currently getting

This image is taken from PDF File that is being generated as result (and it is zoomed out at 55%)
I want to make this look better. Something similar to this, if I may

This image has 13 columns, I don't want that. I want to keep 5 columns but my major concern is the size of the td in my HTML files. It is too small in width and that is why, the text is also very stacked up in each td. But if you look at the other image, text is much more visible and boxes are much more bigger width wise. Moreover, it doesn't suffer from height problems either (the height of the box is in such a way that it covers the whole of the PDF Page and all the tds don't look like stretched down)
I have tried to play around the height and width of my td in the HTML File, but unfortunately, nothing really seemed to work for me.
Edit: Using the code provided by onkar ruikar, I was able to achieve very good results. However, it created the same problem that I was facing previously. The question was asked here: Horizontally merge and divide cells in an HTML Table for Timetable based on the Data in Python File
I changed up the template.html file of mine and then ran the same code. But I got this result,

As you can see, that there were more than one lectures in the First Slot of Monday, and due to that, it overlapped both the courses. It is not reading the
 command properly in this HTML file now.
The modified template.html file has this code,
<!DOCTYPE html>

{{name}}

      Day/Period
      I
      II
      III
      1:15-1:45
      IV
      V

                Monday

            {% for course in monday %}
                {% if loop.index == 4 %}

L

U

N

C

H

                {% endif %}
                {% if course[1] != 0 %}

                        {% set count = [] %}
                        {%- for y in range(0, 5) -%}
                            {%- if count|length < course[0]|length -%}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                                    {% set __ = count.append(1) %}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                            {% set __ = count.append(1) %}

                        {%- for z in range(count|length, course[0]|length) -%}
                            {%- if course[0][count|length] == '@' -%}
                            {%- else -%}
                                {% set __ = count.append(1) %}
                                {%- if course[0][count|length-1] == '_' -%}
                                    {{' '}}
                                {%- else -%}
                                    {{course[0][count|length-1]}}
                                {%- endif -%}
                            {%- endif -%}
                        {%- endfor -%}

                       {%- endif -%}
                      {%- endfor -%}

                {% endif %}
            {% endfor %}

                Tuesday

            {% for course in tuesday %}
                {% if course[1] != 0 %}

                        {% set count = [] %}
                        {%- for y in range(0, 5) -%}
                            {%- if count|length < course[0]|length -%}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                                    {% set __ = count.append(1) %}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                            {% set __ = count.append(1) %}

                        {%- for z in range(count|length, course[0]|length) -%}
                            {%- if course[0][count|length] == '@' -%}
                            {%- else -%}
                                {% set __ = count.append(1) %}
                                {%- if course[0][count|length-1] == '_' -%}
                                    {{' '}}
                                {%- else -%}
                                    {{course[0][count|length-1]}}
                                {%- endif -%}
                            {%- endif -%}
                        {%- endfor -%}

                       {%- endif -%}
                      {%- endfor -%}

                {% endif %}
            {% endfor %}

                Wednesday

            {% for course in wednesday %}
                {% if course[1] != 0 %}

                        {% set count = [] %}
                        {%- for y in range(0, 5) -%}
                            {%- if count|length < course[0]|length -%}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                                    {% set __ = count.append(1) %}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                            {% set __ = count.append(1) %}

                        {%- for z in range(count|length, course[0]|length) -%}
                            {%- if course[0][count|length] == '@' -%}
                            {%- else -%}
                                {% set __ = count.append(1) %}
                                {%- if course[0][count|length-1] == '_' -%}
                                    {{' '}}
                                {%- else -%}
                                    {{course[0][count|length-1]}}
                                {%- endif -%}
                            {%- endif -%}
                        {%- endfor -%}

                       {%- endif -%}
                      {%- endfor -%}

                {% endif %}
            {% endfor %}

                Thursday

            {% for course in thursday %}
                {% if course[1] != 0 %}

                        {% set count = [] %}
                        {%- for y in range(0, 5) -%}
                            {%- if count|length < course[0]|length -%}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                                    {% set __ = count.append(1) %}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                            {% set __ = count.append(1) %}

                        {%- for z in range(count|length, course[0]|length) -%}
                            {%- if course[0][count|length] == '@' -%}
                            {%- else -%}
                                {% set __ = count.append(1) %}
                                {%- if course[0][count|length-1] == '_' -%}
                                    {{' '}}
                                {%- else -%}
                                    {{course[0][count|length-1]}}
                                {%- endif -%}
                            {%- endif -%}
                        {%- endfor -%}

                       {%- endif -%}
                      {%- endfor -%}

                {% endif %}
            {% endfor %}

                Friday

            {% for course in friday %}
                {% if course[1] != 0 %}

                        {% set count = [] %}
                        {%- for y in range(0, 5) -%}
                            {%- if count|length < course[0]|length -%}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                                    {% set __ = count.append(1) %}

                                    {%- for z in range(count|length, course[0]|length) -%}
                                        {%- if course[0][count|length] == '@' -%}
                                        {%- else -%}
                                            {% set __ = count.append(1) %}
                                            {%- if course[0][count|length-1] == '_' -%}
                                                {{' '}}
                                            {%- else -%}
                                                {{course[0][count|length-1]}}
                                            {%- endif -%}
                                        {%- endif -%}
                                    {%- endfor -%}

                            {% set __ = count.append(1) %}

                        {%- for z in range(count|length, course[0]|length) -%}
                            {%- if course[0][count|length] == '@' -%}
                            {%- else -%}
                                {% set __ = count.append(1) %}
                                {%- if course[0][count|length-1] == '_' -%}
                                    {{' '}}
                                {%- else -%}
                                    {{course[0][count|length-1]}}
                                {%- endif -%}
                            {%- endif -%}
                        {%- endfor -%}

                       {%- endif -%}
                      {%- endfor -%}

                {% endif %}
            {% endfor %}

And the python file that I am running has the following code,
from typing import List
import pdfkit
from pdfkit.api import configuration
from jinja2 import FileSystemLoader, Environment
wkhtml_path = pdfkit.configuration(wkhtmltopdf = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe")  #by using configuration you can add path value.

class section:
    def __init__(self, id, course, section, instructor, room):
        self.id = id
        self.course = course
        self.section = section
        self.instructor = instructor
        self.room = room

def generate_data():
    data = {}

    # For CS-1A
    data["CS-1A"] = [["" for i in range(5)] for j in range(5)]
    data["CS-1A"][0][0] += "Advance_Programming@Mr.Ashas@Room_#2 "
    data["CS-1A"][0][0] += "Applied_Physics@Bilal@Room_#1 "
    data["CS-1A"][0][1] += "Programming_Fundamentals@Muhammad_Bilal@Room_#1 "
    data["CS-1A"][0][3] += "Programming_Fundamentals_Lab@Mr._Abid@Lab_#01 "
    data["CS-1A"][0][4] += "Programming_Fundamentals_Lab@Mr._Abid@Lab_#01 "

    # You may change all these for testing purposes.
    # data["CS-1A"][0][0].append(section(2, "Programming Fundamentals", "CS-1A", "Bilal", "Room #1"))
    # data["CS-1A"][0][1].append(section(3, "Applied Physics", "CS-1A", "Muhammad Bilal", "Room #5"))
    # obj = section(4, "Programming Lab", "CS-1A", "Mr. Abid", "Lab #01")
    # data["CS-1A"][0][1].append(obj)
    # data["CS-1A"][0][2].append(obj)
    # data["CS-1A"][0][4].append(section(5, "English Communication", "CS-1A1", "Ms. Ayeza", "Cal Lab"))
    # data["CS-1A"][0][4].append(section(6, "English Communication", "CS-1A2", "Ms. Ayesha", "GP Lab"))
    # data["CS-1A"][1][1].append(section(7, "Linear Algebra", "CS-1A", "Ms. Zain", "Romm #2"))
    # obj = section(8, "English Lab", "CS-1A", "Ms. Abida", "Lab #04")
    # data["CS-1A"][1][3].append(obj)
    # data["CS-1A"][1][4].append(obj)
    # data["CS-1A"][2][0].append(section(9, "Social Studies", "CS-1A", "Mr. Zain Iqbal", "Room #14"))
    # data["CS-1A"][2][4].append(section(10, "Programming Fundamentals", "CS-1A", "Bilal", "Room #15"))
    # # No lectures on Thursday i.e. 3rd index
    # obj = section(11, "English Lab", "CS-1A", "Ms. Abida", "Lab #03")
    # data["CS-1A"][4][1].append(obj)
    # data["CS-1A"][4][2].append(obj)
    # data["CS-1A"][4][2].append(section(12, "English Communication", "CS-1A1", "Ms. Ayeza", "Room #3"))
    # data["CS-1A"][4][2].append(section(13, "English Communication", "CS-1A2", "Ms. Ayesha", "GP Lab"))
    #
    #
    #
    # # For CS-1B
    # data["CS-1B"] = [[[] for i in range(5)] for j in range(5)]
    #
    # data["CS-1B"][0][1].append(section(14, "Advance Programming", "CS-1B", "Mr. Ali Hassan", "Room #2"))
    # data["CS-1B"][0][2].append(section(15, "English Comprehension and Communication", "CS-1B", "Mr. Bilal", "Room #1"))
    # obj = section(15, "Software for Mobile and Devices", "CS-1B", "Mr. Jacob", "Room #5")
    # data["CS-1B"][1][1].append(obj)
    # data["CS-1B"][1][2].append(obj)
    # data["CS-1B"][1][3].append(section(17, "Calculus and Geometrical Analytics", "CS-1B", "Ms. Nomi Khan", "Room #06"))
    # data["CS-1B"][2][3].append(section(18, "Introduction to Information and Communication Technology - Lab", "CS-1B1", "Ms. Sarah Niaz", "Lab #01"))
    # data["CS-1B"][2][3].append(section(19, "Introduction to Information and Communication Technology - Lab", "CS-1B2", "Ms. Julia John", "Lab #06"))
    # data["CS-1B"][2][4].append(section(20, "English Comprehenseion and Communication", "Cs-1B", "Mr. Lionel Boyle", "Room #02"))
    # data["CS-1B"][3][3].append(section(21, "Programming Fundamentals", "CS-1B", "Mr. Alex Niles", "Room #3"))
    # data["CS-1B"][4][2].append(section(22, "Linear Algebra", "CS-1B", "Ms. Ayesha", "GP Lab"))

    return data

def organise_input_data(elements: List[List[str]]) -> List[list]:
    """
    Organises the input data to find double courses for easier use in templates
    """
    new_elements = []
    for day in elements:
        last_course = None
        course_list = []
        index = 0
        for course in day:
            # cleanup data
            course = course.strip().replace(" ", "
")
            # check if long course (and not lunch time)
            if course != "" and course == last_course and index != 3:
                course_list.remove((course, 1))
                course_list.append((course, 2))
                course_list.append(("none", 0))
            else:
                course_list.append((course.replace(" ", "
"), 1))
            last_course = course
            index += 1
        new_elements.append(course_list)

    return new_elements

def generate_html(template, name: str, elements: List[list]) -> str:

    new_elements = organise_input_data(elements=elements)

    rendered = template.render(
        name=name,
        monday=new_elements[0],
        tuesday=new_elements[1],
        wednesday=new_elements[2],
        thursday=new_elements[3],
        friday=new_elements[4]
    )

    with open(f"out_{name}.html", "w+") as file:
        file.write(rendered)

    return rendered

def run(input_data):
    # Init jinja
    file_loader = FileSystemLoader('.')
    env = Environment(loader=file_loader)
    template = env.get_template('template.html')

    full_text = ""
    for name, elements in input_data.items():
        full_text += generate_html(template=template, name=name, elements=elements)

    pdfkit.from_string(full_text, "out.pdf", configuration = wkhtml_path)

if __name__ == '__main__':
    data = generate_data()
    run(data)

A: If you are targeting print media then you need to specify absolute dimensions in mm, cm, inch. If you are printing on A4 page then your page is 210x297mm and you need to print it in landscape mode.
For printing/pdf the page needs to be styled like this:

:root {
  --border-strong: 3px solid #777;
  --border-normal: 1px solid gray;
}

body {
  font-family: Georgia, 'Times New Roman', Times, serif;
}

table>caption {
  font-size: 6mm;
  font-weight: bolder;
  letter-spacing: 1mm;
}

/* 210 x 297 mm */

table {
  width: 297mm;
  height: 210mm;
  border-collapse: collapse;
}

td {
  padding: 1mm;
  border: var(--border-normal);
  position: relative;
  font-size: 2.1mm;
  font-weight: bold;
}

tbody tr:nth-child(odd) {
  background: #eee;
}

tbody tr:last-child {
  border-bottom: var(--border-strong);
}

tbody tr> :last-child {
  border-right: var(--border-strong);
}

/* top header */

.top_head>th {
  width: 54mm;
  height: 10mm;
  vertical-align: bottom;
  border-top: var(--border-strong);
  border-bottom: var(--border-strong);
  border-right: 1px solid gray;
}

.top_head :first-child {
  width: 27mm;
  border: var(--border-strong);
}

.top_head :last-child {
  border-right: var(--border-strong);
}

/* left header */

tbody th {
  border-left: var(--border-strong);
  border-right: var(--border-strong);
  border-bottom: 1px solid gray;
}

tbody>tr:last-child th {
  border-bottom: var(--border-strong);
}

/* row */

tbody td>div {
  height: 34mm;
  overflow: hidden;
}

.vertical_span_all {
  font-size: 5mm;
  font-weight: bolder;
  text-align: center;
  border-bottom: var(--border-strong);
}

.vertical_span_all div {
  height: 10mm;
}

/* td contents */

.left {
  width: 95%;
  position: absolute;
  top: 1mm;
  left: 1mm;
}

.left>div {
  width: 100%;
  margin-bottom: 3mm;
  border-bottom: 1px dashed;
}

.right {
  position: absolute;
  left: 1mm;
  bottom: 1mm;
}

.teacher {
  position: absolute;
  right: 1mm;
  bottom: 1mm;
}

.note {
  font-size: 3mm;
}

.note :last-child {
  float: right;
}

@page {
  margin: 5mm;
}

CS-1A

      Day/Period
      I
      II
      III
      1:15-1:45
      IV
      V

        Monday

Digital Logic Design

Applied Physics

Advanced Programming

Mirza Waqar Baig

CS-1A

English Composition and Comprehension

Applied Physics

Muhammad Ammar

CS-1A2

L

U

N

C

H

English Composition and Comprehension

Junaid Shahid

CS-1A1

Programming Fundamentals

Rizwan ul Haq

CS-1A

        Tuesday

Programming Fundamentals

Rizwan ul Haq

CS-1A

Programming Fundamentals - Lab

Mughees Ismail

CS-1A

Islamic Studies/Ethics

Rizwanullah

CS-1A

English Composition and Comprehension

Junaid Shahid

CS-1A1

        Wednesday

Digital Logic Design

Mirza Waqar Baig

CS-1A

Digital Logic Design - Lab

Muhammad Arslan

CS-1A

Introduction to Information and Communication Technology - Lab

Muiz Qadir

CS-1A

        Thursday

Linear Algebra

Amjad Hussain

CS-1A

English Composition and Comprehension - Lab

Muhammad Iqbal

CS-1A2

English Composition and Comprehension - Lab

Sadia Ashfaq

CS-1A1

        Friday

English Composition and Comprehension

Muhammad Ammar

CS-1A2

Islamic Studies/Ethics

Rizwanullah

CS-1A

Linear Algebra

Amjad Hussain

CS-1A

w.e.f. Monday, September 13, 2021 aSc Timetables

This is how it looks while printing pdf:

To have multiple courses in one cell use structure like this:

Digital Logic Design

Applied Physics

Advanced Programming

Mirza Waqar Baig

CS-1A

Also look at the modified style.

A: What I've done here is remove the borders from the table and collapsed the space for them.
I've then used more semantic elements for both table headings and your actual content with semantic class names. This included adding a new element for the elements you want at the bottom of the cell. Finally, the teacher and codes are floated left and right respectively.

h1 {
  text-align: center;
}

.lunch {
  text-align: center;
  writing-mode: vertical-rl;
  text-orientation: upright;
}

.lunch h2 {
  margin: 0 30px;
}

/*remove borders*/
table {
  border-collapse: collapse;
}

.footer {
  position: absolute;
  bottom: 0;
  padding: 4px;
  width: calc(100% - 8px);
}

.code {
  float: right;
}

.teacher {
  float: left;
}

td,
th {
  height: 175px;
  width: 150px;
  border-bottom: solid 1px black;
  border-right: solid 1px black;
  border-right: solid 1px black;
  position: relative;
}

th:first-child {
  border-left: solid 1px black
}

thead th {
  border-top: solid 1px black;
  border-bottom-width: 2px;
}

td {
  vertical-align: top;
}

CS-1A

        Day/Period
        I
        II
        III
        1:15-1:45
        IV
        V

        Monday

Digital Logic Design

Mirza Waqar Baig

CS-1A

English Composition and Comprehension

Muhammad Ammar

CS-1A2

LUNCH

English Composition and Comprehension

Junaid Shahid

CS-1A1

Programming Fundamentals

Rizwan ul Haq

CS-1A

        Tuesday

Programming Fundamentals

Rizwan ul Haq

CS-1A

Programming Fundamentals - Lab

Mughees Ismail

CS-1A

Islamic Studies/Ethics

Rizwanullah

CS-1A

English Composition and Comprehension

Junaid Shahid

CS-1A1

        Wednesday

Digital Logic Design

Mirza Waqar Baig

CS-1A

Digital Logic Design - Lab

Muhammad Arslan

CS-1A

Introduction to Information and Communication Technology - Lab

Muiz Qadir

CS-1A

        Thursday

Linear Algebra

Amjad Hussain

CS-1A

English Composition and Comprehension - Lab

Muhammad Iqbal

CS-1A2

English Composition and Comprehension - Lab

Sadia Ashfaq

CS-1A1

        Friday

English Composition and Comprehension

Muhammad Ammar

CS-1A2

Islamic Studies/Ethics

Rizwanullah

CS-1A

Linear Algebra

Amjad Hussain

CS-1A


text:
Q: Specific URL Jquery append issue I have a tabbed layout page where each tab is assigned an #id that can be called at the end of the URL: https://example.com/#tab1/
I then added a "start screen" on the main permalink and added some jQuery to basically hide the tab pages content when no hash is found in the URL and show the start screen, and show the tab content when a hash is found and hide the start screen. So far works completely fine.
I now have a search bar inside one of the tabs for searching the content inside the page. My issue is that when a search takes place, the URL changes and removes the hash, which hides the tab and goes back to the start screen again. I can solve this by simply adding the "/#tab1" to the end of the search query, but have not found a way of achieving this yet.
The search query adds "?frm_search=" to the end of the URL, so I'm trying to add a little code to say "when you see "/frm_search=" in the URL, add "/#tab1" to the end of the URL.
This is how far I've gotten:
jQuery(document).ready( function() {
    if( pathname.includes('?frm_search') ) {
        var target="/#tab1";
        jQuery('a').attr('href', function(i, currentAttribute){
            return currentAttribute + target;
        });
    }
});

It is not working. What ends up happening is the following events:

*

*Currently on URL "https://example.com/#tab1/"

*Add search term and click search

*URL changes to "https://example.com/?frm_search=search+term

*When I click back to tab1, the URL changes to "https://example.com/#tab1//#tab1"

So the code is technically adding the correct target to the end of the URL when it sees the correct URL pathname, but the order of when it adds it is incorrect.
Let me know if you have thoughts on how to fix this, and thanks in advance!


text:
Q: Uniform distribution with random support I have a uniform distribution $ X \sim U(A,B) $ where the limits themselves are random: $A \sim N(\mu_A,\sigma_A^2)$ and $B \sim N(\mu_B,\sigma_B^2)$. Hence the support of $X$ is random.
$A$, $B$ are independent. Also consider $\mu_B-\mu_A \gg \sigma_A+\sigma_B$
Any clues on the probability density function of this one?

A: The pdfs of A and B are known since they are normal distributions
The pdf of X given A and B is
$$
f_{X|A,B}(x|a,b)=1_{x \ge a} 1_{x \le b} \frac{1}{|a-b|}
$$
The joint pdf of X, A and B is
$$
f_{X,A,B}(x,a,b)=f_{X|A,B}(x|a,b) f_A(a) f_B(b)
$$
And the pdf of X is given as a marginal distribution from the latter
$$
f_X(x)= \int_{D_B} \int_{D_A} \! f_{X,A,B}(x,a,b) \, \mathrm{d}a \mathrm{d}b.
$$
where $D_A$ and $D_B$ the domains of A and B respectively.

A: So, let's be a bit more specific. The idea is that you first draw the samples for A and B. Then, you draw the sample for X.
I am assuming that if it turns out to be A>B, then X is set to an undefined value. In that case $\int_{\mathbb{R}} \mathbb{P}(X=x) dx < 1 $, ie. you are losing some probability mass, but since this event is rare (under your assumption), I would say this is ok. Also, A and B are independent.
However, X can't be independent of A,B or I am missing something (here comes my comment on that you should start stating your question by first defining what the underlying $\sigma$-algebras are).
So, using total probability:
$ \mathbb{P}(X=x) = \int_{\mathbb{R}} \int_{\mathbb{R}} \mathbb{P}(X=x|A=a,B=b) \cdot \mathbb{P}(A=a) \cdot\mathbb{P}(B=b) \cdot da \cdot db $
where:
$\mathbb{P}(X=x|A=a,B=b) = 1_{x\geq a} 1_{x\leq b} \frac{1}{|a-b|} $
$\mathbb{P}(A=a) = \frac{1}{\sigma_{A}\sqrt{2\pi}} exp\left(-\frac{(a-\mu_{A})^{2}}{\sigma_{A}^{2}}\right) $
$\mathbb{P}(B=b) = \frac{1}{\sigma_{B}\sqrt{2\pi}} exp\left(-\frac{(b-\mu_{B})^{2}}{\sigma_{B}^{2}}\right) $
I realize that computing the integral might be non-trivial.
I hope this sheds some light, or, again, I might miss something on the statement.


text:
Q: react-native init specify react version and react-native version I basically want to init a react-native project with react@15.6.0 and react-native@0.45.0 because dependency problems. However react-native command only allows me to specify react-native version:
react-native init sample --version react-native@0.45.0

This command not works:
react-native init diskful --version react-native@0.45.0 --version react@15.6.0

This, too:
react-native init diskful --version react-native@0.45.0 react@15.6.0

And this, too:
react-native init diskful --version react@15.6.0 react-native@0.45.0

Install globally react@15.6.0 or react-native@0.45.0 does not affect.
Please, someone help me!

A: Create a project :
react-native init MyNewApp --version 0.45.0

If you want do change version then try with this:
npm install --save react-native@0.44.0
npm install --save react@16.0.0-alpha.6

A: *

*delete node_modules folder

*Edit Package.json
"dependencies": {
    "react": "15.6.0",
    "react-native": "0.45.0",
 },

*run command 'npm install'

A: You could initiate the app using
react-native init --version="0.45.0" yourapp,

If further changes are needed, make changes in package.json in react or react-native fields and simply do npm install


text:
Q: Moving a Django Foreign Key to another model while preserving data? I have a Django application where I have a basic user model and user profile model.
class Office(models.Model):
    name = models.CharField()

class User(models.Model):
    email = models.EmailField()
    offices = models.ManyToManyField(Office)

class Profile(models.Model):
    user = models.OneToOneField(User)

Each user has a profile and can be assigned to many different offices.
What I am looking to do is have it so that a User can have many profiles, but the profiles can be assigned to different offices.
At the moment, this isn't possible as the Office field is assigned at the User level and not the Profile level. I envision 2 ways to solve this:

*

*Find some way to move the offices field over to the Profile field.

*Create a new model something along the lines of ProfileNoUser that has a foreign key to the user model as well as have an offices foreign key within it.
Which option do you think is best? If #1, how can I do that?

A: Is your question about data migration?
If so you should read the linked documentation.
It is indeed your first proposal that is the best in my opinion.
Here's how to do it.
Step 1: make the changes to the model
You change your model to match your target:
# models.py

from django.db import models

class Office(models.Model):
    name = models.CharField(max_length=1000)

class User(models.Model):
    email = models.EmailField()

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    offices = models.ManyToManyField(Office)

Run makemigrations:
(.venv) ~/c/s/m/mysite> ./manage.py makemigrations
Migrations for 'so':
  so/migrations/0002_auto_20200825_1311.py
    - Remove field offices from user
    - Add field offices to profile

Step 2: edit the migration file to migrate existing data
Open the file created the previous step. It will look something like:
# Generated by Django 3.1 on 2020-08-25 13:11

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('so', '0001_initial'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='user',
            name='offices',
        ),
        migrations.AddField(
            model_name='profile',
            name='offices',
            field=models.ManyToManyField(to='so.Office'),
        ),
    ]

You need to do two things here:

*

*You can see that with the order generated by Django it will first remove the old FK and then add the new one. You should change that so it is the other way around.

*Then you will have to write some python code that the migration will execute at the right time
The right time is just after the new FK has been created and before the old one gets deleted so you have access to both to migrate data:
# Generated by Django 3.1 on 2020-08-25 13:11

from django.db import migrations, models

def migrate_office_to_profile(apps, schema_editor):
    User = apps.get_model('so', 'User')
    for user in User.objects.all():
        for office in user.office_set:
            user.profile.add(office)

def migrate_office_to_user(apps, schema_editor):
    Profile = apps.get_model('so', 'Profile')
    for profile in Profile.objects.all():
        profile.user.add(profile.offices)
        for office in profile.office_set:
            profile.user.add(office)

class Migration(migrations.Migration):
    dependencies = [
        ('so', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='profile',
            name='offices',
            field=models.ManyToManyField(to='so.Office'),
        ),
        # This is where your python code will be called
        migrations.RunPython(
            # This is called in the forward migration
            migrate_office_to_profile,
            # This is called in the backward migration
            reverse_code=migrate_office_to_user
        ),
        migrations.RemoveField(
            model_name='user',
            name='offices',
        ),
    ]

I haven't tested this on real data. This is your part.
Step 3: run and debug your migration
Make a copy of your database, run the migration and see how it does:
(.venv) ~/c/s/m/mysite> ./manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, so
Running migrations:
  Applying so.0002_auto_20200825_1311... OK

When dealing with data migration you should always write and debug the reverse migration:
(.venv) ~/c/s/m/mysite> ./manage.py migrate so 0001
Operations to perform:
  Target specific migration: 0001_initial, from so
Running migrations:
  Rendering model states... DONE
  Unapplying so.0002_auto_20200825_1311... OK

Remember that migration files are added to version control and part of your software.
=== EDIT ===
Clarifying the idea of reverse or backwards migration.
Your Django migrations are usually run only one way: going up the migration numbers.
But for all the testing and careful thinking that you might apply during development, you can't always account for production data. The code is "easy" because it's the same in production as it is on your dev server. But the production data is usually different.
It can happen that a Django migration fails during deployment. For example, because you are adding an explicit unique constraint that you thought could only be true. But somehow with production data the migration will raise an integrity error.
You are then stuck with a half finished migration and new code that cannot run without the migration. If you took the time to make sure your migration can be run foward and backward without loss of data, you can safely undo the migration and revert back to the previous code and go back to figure out what went wrong, instead of having to fix it on the spot.
The forward and backward migration are automatically handled by Django for the model structure, but for data migration you have to write the functions given to migrations.RunPython.


text:
Q: Disabling certain fields if a record exists in the database I'm writing an application to rate posts, and the first few fields of the submission form contains basic information about the post. Right now, the first field autocompletes using jQuery UI from a MySQL db table.
I want to get to a point where if the user selects one of the autocomplete options instead of typing everything manually, the database is queried, the basic information is filled in, and the fields are disabled (to prevent duplicate entries).
I'm at a bit of a loss about the appropriate approach here. Any advice?
Thanks, Rob.

A: You can use the select event of autocomplete to trigger an AJAX call to server.
$( ".selector" ).autocomplete({
    select: function( event, ui ) {
        /* data used for autocomplete is contained in ui.item... will assume you have an ID included in data object */

       $.post( url, { id:  ui.item.id), function(response){
          /* do something if needed with response from server*/
       })
   }
});

At server end receive the data as you would a form with a named field id.  $_POST['id']
This is very loose since not much detail has been provided in question.
API refrences:
http://api.jqueryui.com/autocomplete/#event-select
http://api.jquery.com/jQuery.post/


text:
Q: Connection Problem in mongodb 4.2.8 on AWS ec2 I have created new Instance on AWS ec2 and installed the mongodb 4.2.8 on server but I'm unable to connect with mongodb using local terminal of Ubuntu 18.0.2. I'm hitting a command which will import a mongodb dump database into the server database the command is given below
mongorestore --host IPv4_Public_IP --port 27017 --db db_name dump/dataDb/

The error I'm facing is
error connecting to host: could not connect to server: server selection error: server selection timeout, current topology: { Type: Single, Servers: [{ Addr: IPv4_Public_IP:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : dial tcp IPv4_Public_IP:27017: connect: connection refused }, ] }

And how to set the Inboud rules for that instance. For now these are
SSH    TCP       22    0.0.0.0/0   -
Custom TCP       27017 my_ip   -


text:
Q: How to put array values to specific column in listview in C#? I created a two listview column 'Sample' and 'Quantity' in the design view mode. Now I want to add array data to mysample to 'Sample' column and myquantity to 'Quantity' column. But I am not how to specific which column the data the should go to. Please help. Here is my code -
str[] mysample = somedata;
str[] myquantity = somedata;

for (int i = 0,  i < mysample; i++)
    {
      ListViewItems item1 = new ListViewItem();
      item1.Subitems.Add(mysample[i].ToString());
      listview1.Items.add(item1);

      ListViewItems item2 = new ListViewItem();
      item1.Subitems.Add(myquantity[i].ToString());
      listview1.Items.add(item2);

     }

A: You need only one ListViewItem per row.
string[] mysample = { "Sample A", "Sample B", "Sample C"};
string[] myquantity = { "1", "2", "3"};

for (int i = 0; i < mysample.Length; i++)
{
    string[] subitems = new string[] { mysample[i], myquantity[i] };
    ListViewItem item = new ListViewItem(subitems);
    listView1.Items.Add(item);
}

Also note that to display columns, you should set the View to Details.

A: First of all make sure the List View's View property is set to Details otherwise the columns wont show up.
You can either do it in the properties window or programmatically
listView1.View = View.Details;

Then you can add data to multiple columns by passing them to one of ListViewItem Class' Initializer Overloads as an Array (with desired sequence) and add it to Your ListView's Items
listView1.Items.Add(new ListViewItem(new[] {"column 1" , "column 2", ... }));

BTW your code will look like something Like This :
listView1.View = View.Details;
            String[] mySample =
            {
                "item 1",
                "item 2",
                "item 3"
            };
            String[] myQuantity =
            {
                "1",
                "2",
                "3"
            };
            for (var i = 0; i < mySample.Count(); i++)
            {
                listView1.Items.Add(new ListViewItem(new[] {mySample[i],myQuantity[i]}));
            }

also a piece of advise , Stop using WindowsForms and Learn WPF instead ;)


text:
Q: Backbone / Dropzone : How to properly dispose a Dropzone instance My application instanciates lots of dropzone elements. Through the navigation, I instanciate Dropzone, but when users leaves to an other page, I need to properly dispose the Dropzones to keep my document events / DOM clean.
I use amd version of Dropzone within a backbone / requirejs application.
The documentation says to call disable() method to remove all dropzone event listeners. I call disable method, then I remove the element from the DOM. Is this a safe way to properly clean the Dropzone? Does Dropzone module still keep references to this removed Dropzone element?
Here is the code I use to render a dropzone element "as a view" in my backbone application. I need to make "remove" function properly clean the Dropzone instance :
define(['backbone','dropzone-amd-module'], function(Backbone, Dropzone){
    // Prevent Dropzone from auto discovering this element:
    Dropzone.options.myAwesomeDropzone = false;
    // This is useful when you want to create the
    // Dropzone programmatically later
    // Disable auto discover for all elements:
    Dropzone.autoDiscover = false;

    return Backbone.View.extend({
        tagName: 'div',
        className: 'dropzone',
        dropzone_reference: null,
        render: function(){
            this.initDropzone();
            return this;
        },
        initDropzone: function(){
            // init dropzone (avoid to init more than once!)
            if( !this.dropzone_reference)this.dropzone_reference = new Dropzone(this.el, this.options);
        },
        remove: function(){
            // remove dropzone instance
            this.dropzone_reference.disable();
            Backbone.View.prototype.remove.apply(this, arguments);
        }

    });
}

A: Backbones view.remove():
remove: function() {
  this._removeElement();
  this.stopListening();
  return this;
},

removes the view's element from DOM.
As you said, the drop method does remove event handlers:

If you do not need a dropzone anymore, just call .disable() on the object. This will remove all event listeners on the element

Since view.remove() removes the element itself from DOM, even .disable() doesn't seem necessary.
The only thing having a reference to your dropzone module is the view's dropzone_reference property. When there are no references to the view, it'll be garbage collected, leaving the dropzone module with no references, which will in turn get garbage collected.
Just make sure you don't keep any references to the destroyed view.


text:
Q: How to insert current date in database mysql hello i am using insert query with a different pattern so i just want to
insert the current date in database but i can't find a place to put $date in insert query
$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id)
         SELECT  `product_id`,`pr_name`,`pr_price`,`pr_size`, `userid`
         FROM `shopping_cart` WHERE `userid` = $uid";

A: You dont need to do the date capture in PHP, as long as you want the date to be the date as at time of execution of the query. You can use the MySQL NOW() function, just add it to the inner query in the correct column to match the outer queries columns.
$sql="INSERT INTO `delivery` (product_id,pr_name,pr_price,pr_size,user_id, PR_DATE)
     SELECT  `product_id`,`pr_name`,`pr_price`,`pr_size`, `userid`, NOW()
     FROM `shopping_cart` WHERE `userid` = $uid";

A: You should not pass date or datetime from PHP if you want the date/datetime at the time of yours query's execution, instead you can use built-in MySQL functions to do so
To insert current date & time use NOW()
$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id, dt)
    SELECT  `product_id`,`pr_name`,`pr_price`,`pr_size`,
        `userid`, NOW()
    FROM `shopping_cart` WHERE `userid` = $uid";

To insert current date only use CURRENT_DATE()
$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id, dt)
    SELECT  `product_id`,`pr_name`,`pr_price`,`pr_size`,
        `userid`, CURRENT_DATE()
    FROM `shopping_cart` WHERE `userid` = $uid";

These queries assume you have a column named dt in your delivery table. Please change column name if different in your schema, or add a date or datetime column in your table if you do not have any yet

A: If you want to insert your own date then use as per below-
$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id, your_date_column)
         SELECT  `product_id`,`pr_name`,`pr_price`,`pr_size`,
                 `userid`, '$date'
         FROM `shopping_cart` WHERE `userid` = $uid";

If you want to put current date then use as per below-
$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id, your_date_column)
         SELECT  `product_id`,`pr_name`,`pr_price`,`pr_size`,
                 `userid`, CURDATE()
         FROM `shopping_cart` WHERE `userid` = $uid";

Note: If you want to insert with time then use now().

A: I cant understand your clearly. Normally, we insert current date like

*

*curdate()

*sysdate()

A: Use now() in your query to get the current date.

A: First of you have to check whether you have column for current date  or not in your database table. If not then you have to add a column to store current date and use that column in your query.
You can use timestamp /datetime / now() function to store current date(choose one according to your  requirement)
$sql="INSERT INTO `delivery` (product_id,pr_name,pr_price,pr_size,user_id, curr_date)
 SELECT  `product_id`,`pr_name`,`pr_price`,`pr_size`,
         `userid`, timestamp
 FROM `shopping_cart` WHERE `userid` = $uid";


text:
Q: 64 registers using MIPS architecture with 15 bits length I am having an assignment to make and it asks the following things :
We have 64 registers where all of their commands they have 15bits length.
It also states that we got the following after we compile them(turn them into machine language). 7 commands with reference of 2 registers and 60 commands with reference of 1 register. It asks how many commands without register reference can we have..
This is what i though of but it appears i am having something wrong.
Since this is mips architecture each of the commands we use (add,all etc) will be using 32bits where for the r instructor we have:
opcode(6bits),rs(6bits),rt(6bits),rd(6bit),shamt(5bit),func(3bit)
because it says that we have 64 registers so we need 6 bits for each and the func is 3 due to the fact that we have max 7 functions.So in the case for example of all we have the following
000000->opcode
000000->rs
6bit-> rt
6bit-> rd
5bit-> shame
3bit-> the function.

Is this correct or am i missing something? perhaps we are not supposed to use the r instructor but the i?What happens for the second operation when we have 60 commands and 1 register reference? what instructor can actually take only one register as an argument? Some help would be really appreciated and thanks

A: I doubt this is talking about mips, it's talking about a fictious architecture that you are about to design :)
7 commands with 2 registers needs 3+6+6=15 bits so uses all the bits available. It does leave 1 opcode free to encode the other instructions luckily :) Let's say 000b is used for those.
This means, for the rest of the instructions we only have 12 bits remaining (since the first 3 are 000). To encode 60 instructions we need 6 bits, and another 6 for the register, so that again uses up all the space.
However, we still have 4 opcodes free, we can use all of them for instructions without operands, and of course in we still have the 6 bits previously used for the registers, so we can encode 4*64=256 instructions that take no operands.
000 000000 xxxxxx = no operand block #1 with 64 instructions
000 000001 xxxxxx = no operand block #2 with 64 instructions
000 000010 xxxxxx = no operand block #3 with 64 instructions
000 000011 xxxxxx = no operand block #4 with 64 instructions
000 000100 rrrrrr = first instruction with 1 operand
000 111111 rrrrrr = last instructon with 1 operand (60 total)
001 ssssss tttttt = first instruction with 2 operands
111 ssssss tttttt = last instruction with 2 operands (7 total)


text:
Q: In PHP :how can I use include() Function which parameter is variable? I need to use include Function with variable.
but,when I try to do it I faced some errors .
Code :
$year=$_POST['year'];

$month=$_POST['month'];

$day=$_POST['day'];

include "Event.php?year=".$year."&month=".$month."&day=".$day;

so,can U help me ? : )

A: When you include files, you can't pass them any arguments. However they DO inherit any variables in the current scope (global or method).
I'm guessing at what your code does, but I assume you can just do this:
include "Event.php";

A: You dont need to use that kind of sintax.
The $year, $month and $day variables will be perfectly visible and accessible on the Event.php file.
To get along with what you want, check PHP manual on http://php.net/manual/en/function.include.php to see some examples.

A: I'm not sure what you're trying to achieve, but I have a couple of guesses handy.
1 - You are trying to redirect the user, with those parameters appended to the url, in which case you will probably need to utilise header:
header("Location: http://example.com/Event.php?year=$year&month=$month&day=$day");

2 - You are trying to capture the output of that page given the presence of certain GET parameters, in which case you can utilise file_get_contents:
$output = file_get_contents("http://localhost/Event.php?year=$year&month=$month&day=$day");

A: Include the Event.php directly and access the $_POST or $_GET variables from there.

include('Event.php');

// Event.php:
echo $_POST['year']; // works


text:
Q: How to calculate Integral error from MCMC I've recently started using Markov Chain Monte Carlo to calculate integrals, but I can't seem to find how to calculate the error for such an integral. In the standard case of importance sampling, the integral is defined as,
$$ I = \int f(x) dx \approx \mathbb{E}\left[f(x)\right]_{x \sim p(x)} = \frac{1}{N}\sum_{i=1}^{N} \frac{f(x)}{p(x)} \iff x \sim p(x) $$
and, its associated error is defined by,
$$\frac{N}{N-1}\left( \mathbb{E}\left[f(x)^{2}\right]_{x \sim p(x)} - \mathbb{E\left[f(x)\right]_{x \sim p(x)}^{2}} \right)$$
However, these definitions are only valid because the sampling of $x \sim p(x)$ is independent and identically distributed; however, by definition of a Markov chain samples are dependent on the previous sample, and hence this doesn't apply.
How exactly can an error be calculated if samples are dependent? I've tried searching for an answer but yet to find one. I did see one solution which involved the autocorrelation time of the chain, although I can't find it anymore.
Thank you in advance!


text:
Q: CTMessageCenter in iOS 9 and Above There once existed and may still exist a part of the private iOS API, in CoreTelephony, called CTMessageCenter, which was a class that could be used to programmatically send SMS.
I've struggled for a while now trying to figure out if it is possible to use this class on iOS 9, even going so far as to download these iOS runtime headers and attempt to include the framework in my project... it appears as empty after the import. In any case, CTMessageCenter seems to have vanished... surely it still exists or has an alternative.
I've tried using selectors, just importing CTMessageCenter.h, and probably other things I can't remember... any help with this would be appreciated.


text:
Q: Proxy-ing a SOAP server I need to communicate with a httpS SOAP server on a different port than the standard 443. The client app doesn't work (because of restrictions) with different ports than the standard ones for HTTP and HTTPS
How can I setup my linux server running Apache to tunnel all these requests coming in at soap.domain.com to https://soapserver.otherdomain.com:1234/Service.asmx ?

A: A reverse proxy will help you.
You can use apache mod_proxy to help you. By using mod_proxy apache will receive the request on the standard HTTP/HTTPS ports and then internally redirect it to the SOAP server.
http://httpd.apache.org/docs/2.0/mod/mod_proxy.html
Read up on reverse proxy. It will help you understand better.

A: I'd use a reverse proxy such as haproxy or nginx with proxy_pass option.
Both will allow you to proxy requests to upstream servers and both will allow HTTPS to soap.domain.com and allow proxying to an encrypted HTTPS upstream server in your case: https://soapserver.otherdomain.com:1234/Service.asmx
In my experience nginx is the somewhat easier to setup and configure.
An appropriate nginx configuration may resemble the following:
listen       443 ssl;
server_name  soap.domain.com;
ssl_certificate     soap.domain.com.crt;
ssl_certificate_key soap.domain.com.key;
ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers         HIGH:!aNULL:!MD5;

location / {
    proxy_pass https://soapserver.otherdomain.com:1234;
}

And yes, you can use a self signed certificate

A: I'm not clear where you need to do this - on the SOAP client? On the SOAP server? somewhere in between? The approach is the same regardless - there are multiple ways of doing this.

*

*You could use iptables to rewrite the packet addresses.

*Run a packet proxy daemon (e.g. netcat) to listen on port 443 and connect to port XXX

*Configure [x]inetd to listen on port 443 and run a generic socket client (e.g. netcat again) connecting to port XXX

The first method would allow you to preserve the client address seen by the server.


text:
Q: Clearing DIV with float I have a div (navigation) that is "float:left;".
After this div main content comes. And second divs comes over the first one.
If I add style="clear:both;" after the first dif, then it works.
However, i wonder if this is the right way to do this, this is my only question.

text
...

.nav{
    width: 100%;
    float: left;
    margin: 0 0 3em 0;
    padding: 0;
    list-style: none;
}

.nav li{
    float: left;
    margin: 0 2px;
}

.nav li a{
    display: block;
    padding: 8px 15px;
    text-decoration: none;
    font-weight: bold;
    color: #fff;
    border-right: 1px solid #ccc;
    background-color: #3b3d49;
    -webkit-border-radius: 7px 7px 0px 0px;
    border-radius: 7px 7px 0px 0px;
 }

A: Yes, that works fine. However, you don't need another element to clear the content, you can add the style to the content wrapper.
In your style sheet:
#content-wrapper { clear: both; }

Another approach is to add a container around the floating element, and make it contain its children using the overflow style:

text
...

Then in your style sheet add:
.nav-container { overflow: hidden; }

A: The main use of the above mentioned "clear:both"
The clear property specifies which sides of an element where other floating elements are not allowed.
"clear:both"

means No floating elements allowed on either the left or the right side.

A: In answer to your question, cleaning floats with clear:both; is a pretty standard way of doing this, yes.

A: this is the best way, just add class .group to your container
.group:before,
.group:after {
    content: "";
    display: table;
}
.group:after {
    clear: both;
}
.group {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

A: yes it is correct to see this example from the creators of html
http://www.w3schools.com/cssref/pr_class_clear.asp

A: You could use
 for short hand. And another way is that you could use clearfix method, you could search it on google for the best. this is the method that @conner explained it.


text:
Q: Add the alternative of "delisting" questions; deletion is usually harmful overkill There has been a lot of debate about deleted posts over the years. The classic example is the old discussion about handling old popular posts, upon which consensus has never been reached and the opinion of the majority has varied over time (deletion is currently favoured). More recent is Pekka's request that a meta thread be undeleted and the related discussion about the appropriateness of deleting such meta posts (this suggestion wouldn't resolve that situation, but it would improve it).
Much unnecessary conflict comes from the fact that deletion is not the optimal solution in most cases, but the Stack Exchange software doesn't provide a better alternative.
How often is it actually necessary that content be made entirely inaccessible to most people? Occasionally there will be an genuine need for deletion, such as when copyrighted content is posted illegally. However in most cases posts are just deleted not because they're inherently harmful, but just because it's either useless or misrepresentative of the site, and someone wants to get it out of the way.
We're currently forced to choose between deletion, which wipes content of the site and breaks links, and locking, which preserves broken windows in question listings and inappropriate reputation gains.
I request the alternative of delisting questions. Delisted questions would behave like locked-and-deleted questions except that they would be visible to anybody with a direct link. A background color and notice would make it clear that they're not meant to represent the site. If you wanted to absolutely minimize their impact they could even be noindexed and removed from search2.

This might seem like a lot of trouble and complexity1 but, as was discussed in podcast 27, it's important to preserve the web when possible. Stack Overflow shouldn't be breaking links and taking content off the web without a good reason.
(Partially a repost of my answer here.)
1 If deletion were modified, instead of replaced then it wouldn't really increase complexity, but I thought people might prefer this.
2 An isdelisted option would be nice.

A: Because you don't use an absolute (deleting is always harmful overkill), I can't absolutely oppose your premise. I am sure that sometimes, something is deleted which I would think should not be deleted. I advocate careful application of delete votes. I like the weighted system that requires more delete votes on popular questions. No two people will agree if the weight applied is "correct", but I think it's a good principle.
But I do disagree with your solution, because I believe that many questions which get deleted do very much need to be deleted. Offensive posts, for instance. Outright spam. Defacement. Etc.
But I further believe that plain-old "bad posts" also should be deleted sometimes, and why is simple: they dilute the content on the site. Even if they are not linked from anywhere (which makes me wonder why you even want this...), there will be already-saved links to some of these posts.
That is: I suggest to you that the 'breaking of links' is exactly what is intended in these cases.

A: I agree that it would be nice to preserve old content rather than let it vanish from the face of the web. But I disagree with that content staying in place. Questions are closed because they do not belong here. So they should not appear as being on Stack Exchange. I don't think it's a good idea to preserve the old link, either, because this doesn't make it apparent that the question is no longer really on Stack Exchange. On the other hand, they should be found via Google, so they must be listed somewhere. Web pages that you can only find if you have the link are so 1994. Hence deleted questions should be visible outside the Stack Exchange platform. Like… on StackPrinter (only more complete).

A: This is now completed.  Questions locked for historical significance will no longer show up in question lists.

A: Delisting is an excellent idea.
Kind of like youtube's "private videos" -- it exists on the Internet, just you need the specific link.  In this case the URL is a form of password.  I like it.