答:
```<code>def opening(data: DataFrame, group_fields: List[Union[str, Grouper]], today: datetime) -> DataFrame:
    # Variant A
    copy_fields = group_fields.copy()
    copy_fields[-1] = 'NUMBER'
    row_list = []
    for i, row in data.iterrows():
        new_row = {f: row[f] for f in copy_fields}
        start_d = row['OPEN_TIME']
        end_d = row['RESOLVED_TIME']
        if not end_d:
            end_d = today
        for d in pandas.date_range(start=start_d, end=end_d):
            new_row['LAST_DATE'] = d
            row_list.append(new_row.copy())
    r = DataFrame(row_list)
    copy_fields[-1] = 'LAST_DATE'
    # print(r)
    # print(copy_fields)
    r = r.groupby(copy_fields).agg({'NUMBER': 'size'}).reset_index()
    r.rename({'NUMBER': 'OPENING', }, axis=1, inplace=True)
    # Variant B
    copy_fields = group_fields.copy()
    copy_fields.pop(-1)  # = 'LAST_DATE'
    min_d = data['OPEN_TIME'].min()
    to_date = data['OPEN_TIME'].max()
    print(min_d, to_date)
    r = None
    for d in pandas.date_range(start=min_d, end=to_date):
        x = data[(data['OPEN_TIME'].dt.date <= d) & (data['RESOLVED_TIME'].dt.date >= d)]
        z = x.groupby(copy_fields).agg({'NUMBER': 'count'}).reset_index()
        z['LAST_DATE'] = d
        if r is not None:
            r = r.append(z, ignore_index=True)
        else:
            r = z
    z.rename({'NUMBER': 'OPENING', }, axis=1, inplace=True)
    return r

def test_opening(self):
    values = [{'A': 3,
               'B': 14,
               'NUMBER': 1,
               'OPEN_TIME': datetime(2000, 1, 31),
               'RESOLVED_TIME': datetime(2000, 2, 2)},
              {'A': 3,
               'B': 14,
               'NUMBER': 2,
               'OPEN_TIME': datetime(2000, 1, 29),
               'RESOLVED_TIME': datetime(2000, 2, 3)},
              {'A': 4,
               'B': 8,
               'NUMBER': 3,
               'OPEN_TIME': datetime(2000, 1, 31),
               'RESOLVED_TIME': datetime(2000, 2, 5)},
              {'A': 4,
               'B': 9,
               'NUMBER': 4,
               'OPEN_TIME': datetime(2000, 1, 30),
               'RESOLVED_TIME': datetime(2000, 2, 6)},
              {'A': 5,
               'B': 3,
               'NUMBER': 5,
               'OPEN_TIME': datetime(2000, 2, 17),
               'RESOLVED_TIME': datetime(2000, 2, 17)}]
    df = DataFrame(values)
    # df[0] = df[0].astype('datetime64[ns]')
    # df = df.set_index([0])
    r = opening(df, ['A', 'B', Grouper(freq='W-MON')], datetime(2000, 2, 17))
    self.assertEqual(len(r), 21, r)
</code>```

Body:
i have data:
a b sum start_time end_time:

  [{'A': 3,
  'B': 14,
  'C': 1.0978855136176695,
  'd1': Timestamp('2000-01-31 00:00:00'),
  'd2': datetime.date(2000, 2, 17)},
 {'A': 7,
  'B': 36,
  'C': -1.6854456807259401,
  'd1': Timestamp('2000-02-29 00:00:00'),
  'd2': datetime.date(2000, 3, 17)},
 {'A': 2,
  'B': 8,
  'C': -0.4443999007021714,
  'd1': Timestamp('2000-03-31 00:00:00'),
  'd2': datetime.date(2000, 4, 17)},
 {'A': 6,
  'B': -5,
  'C': -0.5522614635020895,
  'd1': Timestamp('2000-04-30 00:00:00'),
  'd2': datetime.date(2000, 5, 17)},
 {'A': -7,
  'B': -4,
  'C': -0.37221963217375853,
  'd1': Timestamp('2000-05-31 00:00:00'),
  'd2': datetime.date(2000, 6, 17)}]

if i want sum by week, i do:

y.reset_index().set_index("d1").groupby(['A', 'B', Grouper(freq='W-MON')]).agg({'C': 'sum'})

How to get the balance in the queue at the end of the week?
If i do:

y["LAST_DATE"] = y["D1"] + Week(weekday=6)

data['OPENING'] = [self.opening(i) for i in data["LAST_DATE"].dt.date]

def opening(d: date) -> int:
        x = y[(y['d1'].dt.date < d) & (y['d2'].dt.date > d)]
        return len(x)

i does not count grouping


来源: stackexchange

问:
React Navigation: best way to implement logout navigation?
I'm using react-navigation@4.0.10 in my React Native app, and have a Login screen and two TabNavigator screens. Logging in from the Login screen takes me to TabNavigator_1, and if I log out from TabNavigator_1 I just use this.props.navigation.goBack(). The problem is, to get to TabNavigator_2 I click a button in TabNavigator_1 which triggers this.props.navigation.navigate('TabNavigator_2'), so TabNavigator_2 is now on top of the stack, and calling this.props.navigation.goBack() would just take me back to TabNavigator_1 instead of Login.

What's the best way to approach this, so that clicking Log out from TabNavigator_1 and TabNavigator_2 takes me back to Login?

答:
First create TabNavigator_1 like this:-

```<code>const TabNavigator1 = createBottomTabNavigator({
 Home: HomeScreen,
Settings: SettingsScreen,
});
</code>```

create second TabNavigator_2 like this:-

```<code>const TabNavigator2 = createBottomTabNavigator({
 Home: HomeScreen,
 Settings: SettingsScreen,
});
</code>```

Then Stack Navigator :-

```<code>  const StackNavigator = createStackNavigator(
{
  Login: LoginScreen,
  Tab1: TabNavigator1,
  Tab2: TabNavigator2,
},
{
  initialRouteName: 'Login',
}
);
</code>```

A main Main Navigator: -

```<code>{this.state.isLogin ? <StackNavigator/> : <TabNavigator1/>}
</code>```

on LogOut you can go like:-

```<code>onPress=()=>{this.props.navigation.navigate('Login')}
</code>```

OR

```<code>onPress=()=>{this.props.navigation.push('Login')}
</code>```

Hope it help!!!

ContentLicense: CC BY-SA 4.0

Body:
First create TabNavigator_1 like this:-

const TabNavigator1 = createBottomTabNavigator({
 Home: HomeScreen,
Settings: SettingsScreen,
});

create second TabNavigator_2 like this:-

const TabNavigator2 = createBottomTabNavigator({
 Home: HomeScreen,
 Settings: SettingsScreen,
});

Then Stack Navigator :-

  const StackNavigator = createStackNavigator(
{
  Login: LoginScreen,
  Tab1: TabNavigator1,
  Tab2: TabNavigator2,
},
{
  initialRouteName: 'Login',
}
);

A main Main Navigator: -

{this.state.isLogin ? <StackNavigator/> : <TabNavigator1/>}

on LogOut you can go like:-

onPress=()=>{this.props.navigation.navigate('Login')}

OR

onPress=()=>{this.props.navigation.push('Login')}

Hope it help!!!


问:
Last added element value reflected in whole list in python - How to solve this problem?
The following is my data:

```<code>"Jay": 1, "Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2
</code>```

I would like to put it into a list to make it look like this:

```<code>["Jay": 1,"Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2]
</code>```

My issue is that only the final element is pushed to the entire list. The result looks like this:

```<code>["Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2]
</code>```

How would I resolve this issue?

答:
Don't use dict, use list and tuple instead:

```<code>your_list = [ ('Jay', 1), ('Raj', 3), ('Jay', 1), ('Raj', 3) ]
</code>```

When using dict you cannot use same keys.

Body:
The following is my data:

"Jay": 1, "Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2

I would like to put it into a list to make it look like this:

["Jay": 1,"Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2]

My issue is that only the final element is pushed to the entire list. The result looks like this:

["Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2]

How would I resolve this issue?

Body:
Don't use dict, use list and tuple instead:

your_list = [ ('Jay', 1), ('Raj', 3), ('Jay', 1), ('Raj', 3) ]

When using dict you cannot use same keys.


问:
How to get all messages of a particular user or group in mesibo using plain javascript
The Documentation provides examples for android and IOS but not for JS.
We also looked at the demo projects, but they are in angular.
how do we do it in plain JS

I wrote this by imitating the Android example and Angular example

```<code>   api.readDbSession(null, '96042', null, function on_message(m) {
        console.log('m is ', m);
        console.log('m.read is ', m.read(100))
    });
</code>```

But the above results in m is null

答:
Have you checked code on GitHub</p>

```<code>var session = api.readDbSession(null, '96042', null, function on_message(m) {
        console.log('m is ', session.messages);
        console.log('m is ', session.getMessages());
    });
    session.read(100);
</code>```

Body:
The Documentation provides examples for android and IOS but not for JS.
We also looked at the demo projects, but they are in angular.
how do we do it in plain JS

I wrote this by imitating the Android example and Angular example

   api.readDbSession(null, '96042', null, function on_message(m) {
        console.log('m is ', m);
        console.log('m.read is ', m.read(100))
    });

But the above results in m is null

Body:
Have you checked code on GitHub

var session = api.readDbSession(null, '96042', null, function on_message(m) {
        console.log('m is ', session.messages);
        console.log('m is ', session.getMessages());
    });
    session.read(100);


问:
Is there a way of deleting the tables inside a PDF using Python?
Is there a way of deleting the tables inside a PDF using Python? So far I've been working with pdfplumber to parse through the text within the PDF, and wanted to know is there is a way to ignore or delete the text inside a the tables.

答: I would recommend using a Python package called Camelot. It is very efficient in extracting tabular data from PDF's. Here is the link to the documentation. </p>


问:
Python PIP Install Cache Path [windows]
I don't have enough space on my C drive (PRIMARY) and can't install packages due to not having enough space, I have installed my python onto my D drive.

however when i try to install i get this error

error: could not install packages due to an environmenterror: [errno 28] no space left on device

I have even made a symlink (directory) to point the pip folder from my windows user profile appdata folder to a folder named pip on my d drive, even when doing this I still get the error listed above.

Thanks for the support and help <3

Edit: I have tried using a virtual enviroment, but still without success

答: Did you used the --target when installed the packages ? </p>

Title: Python PIP Install Cache Path [windows]


问:
Problem with creating instances of type using reflection from strong-named assembly
I have an existing .NET 2.0 Win Forms solution that's deployed on the client. For the sake of this scenario, lets call it 'WinApp.exe'.  WinApp.exe has a direct reference to a private assembly named 'Assembly.dll'. Assembly.dll has a direct reference to another assembly named 'Framework.dll'. Within Framework.dll is a type named 'IPlugIn'. Framework.dll is not strong-named, but the version of the assembly is 1.0. There is a class in Assembly.dll that implements IPlugIn from Framework.dll.

I have another .NET 2.0 Win Forms solution named 'Framework.exe'.  This Win Forms project also has a direct reference to Framework.dll, which has the 'IPlugIn' type defined. Framework.dll is not strong-named, but the version of this assembly is 2.0. Bit for bit, 'IPlugIn' in Framework.dll v2 is identical to 'IPlugIn' in Framework.dll v1. The code in Framework.exe uses reflection to load the implementation of IPlugIn that's in WinApp:

```<code>AssemblyName an = AssemblyName.GetAssemblyName("C:\\Program Files\\WinApp\\Assembly.dll");
Assembly dll = Assembly.Load(an);
object o = Activator.CreateInstance(dll.GetType("WinApp.ClassThatImplementsIPlugIn"));
IPlugIn iPlugIn = o as IPlugIn;
</code>```

So far, so good. This code works!  Now here's the troublesome part. I need to assign a strong name to Framework.dll v2, so that it can be put in the GAC. However, WinApp and its dependent assemblies will not be redeployed - it must continue to use the same versions of assemblies that it's currently using. When I give Framework.dll v2 a strong name and recompile and run Framework.exe, when the above code executes I receive a "InvalidCastException" on line:

```<code>IPlugIn iPlugIn = o as IPlugIn;
</code>```

I think I'm receiving this exception because now that one version of Framework.dll has a strong name, the runtime is treating the type "IPlugIn" as if it's a different type altogether.  I need to know if there's any way to solve this issue. Again, the requirements are:

I must be able to put Framework.dll v2 in the GAC (therefore it must have a strong name).

WinApp must continue to work as it currently does (continue to reference Framework.dll v1). I cannot redistribute newly compiled assemblies for WinApp.

Thanks in advance!

Chad

答:
The problem here is that both the strong named Framework as the old Framework assembly are loaded. .NET does not really care that both definitions of IPlugin are the same. They are from a differend assembly so they are different (I am a little puzzled as why it will raise an InvalidCastException as a cast like that will just returns null if failed).

option A

One method to still use the class will be to use reflection but this might go a long way when more types hosted in Framework come to play. all of these will need to be accessed using reflection.
You can create wrappers to hide the reflection using something like this:

```<code>public class PluginWrapper : IPlugin
{
  object fObj;
  PropertyInfo fNameProperty;
  MethodInfo fGetOtherMethod;

  public PluginWrapper(object o)
  {
    fObj = o;
    fNameProperty = o.GetType().GetInterface("IPlugin").GetProperty("Name");
    fGetOtherMethod = o.GetType().GetInterface("IPlugin").GetMethod("GetOther", new Type[] { typeof(string) });
  }

  public string Name
  {
    get { return (string)fNameProperty.GetValue(fObj, null); }
  }

  public IOther GetOther(string name)
  {
    object result = fGetOtherMethod.Invoke(fObj, new object[] { name });

    if (result == null)
      return null;

    return new OtherWrapper(result);
  }
}
</code>```

Then you can use your object as following:

```<code>IPlugin iPlugIn = new PluginWrapper(o);
</code>```

option B

I can think of another way. I am not sure if this a road you should go as it looks a lot of "hacking" in my eyes but i'll share it anyway and let you decide.

You can let the assembly load using a byte stream instead of AssemblyName. That way it will be unable to resolve the other Framework assembly and giving you a change to break in on the AssemblyResolve event:

```<code>AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
Assembly dll = Assembly.Load(File.ReadAllBytes(@"C:\Program Files\WinApp\Assembly.dll"));
object o = Activator.CreateInstance(dll.GetType("WinApp.ClassThatImplementsIPlugIn"));
IPlugin iPlugIn = o as IPlugin;

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
  if (args.Name.ToLower().StartsWith("framework,"))
    return typeof(IPlugin ).Assembly;

  return null;
}
</code>```

This might be a little tricky as by that you will give .NET a promise that the assembly is compatible and that you are prepared to take the risk. If things are not compatible then problems might quickly start to arise.

Other options

There might maybe also be ways to solve the problem using bindingredirect element in app.config. I'm not really known with the details about how that works but might be worth looking into a bit.

ContentLicense: CC BY-SA 3.0

Body:
I have an existing .NET 2.0 Win Forms solution that's deployed on the client. For the sake of this scenario, lets call it 'WinApp.exe'.  WinApp.exe has a direct reference to a private assembly named 'Assembly.dll'. Assembly.dll has a direct reference to another assembly named 'Framework.dll'. Within Framework.dll is a type named 'IPlugIn'. Framework.dll is not strong-named, but the version of the assembly is 1.0. There is a class in Assembly.dll that implements IPlugIn from Framework.dll.

I have another .NET 2.0 Win Forms solution named 'Framework.exe'.  This Win Forms project also has a direct reference to Framework.dll, which has the 'IPlugIn' type defined. Framework.dll is not strong-named, but the version of this assembly is 2.0. Bit for bit, 'IPlugIn' in Framework.dll v2 is identical to 'IPlugIn' in Framework.dll v1. The code in Framework.exe uses reflection to load the implementation of IPlugIn that's in WinApp:

AssemblyName an = AssemblyName.GetAssemblyName("C:\\Program Files\\WinApp\\Assembly.dll");
Assembly dll = Assembly.Load(an);
object o = Activator.CreateInstance(dll.GetType("WinApp.ClassThatImplementsIPlugIn"));
IPlugIn iPlugIn = o as IPlugIn;

So far, so good. This code works!  Now here's the troublesome part. I need to assign a strong name to Framework.dll v2, so that it can be put in the GAC. However, WinApp and its dependent assemblies will not be redeployed - it must continue to use the same versions of assemblies that it's currently using. When I give Framework.dll v2 a strong name and recompile and run Framework.exe, when the above code executes I receive a "InvalidCastException" on line:

IPlugIn iPlugIn = o as IPlugIn;

I think I'm receiving this exception because now that one version of Framework.dll has a strong name, the runtime is treating the type "IPlugIn" as if it's a different type altogether.  I need to know if there's any way to solve this issue. Again, the requirements are:

I must be able to put Framework.dll v2 in the GAC (therefore it must have a strong name).

WinApp must continue to work as it currently does (continue to reference Framework.dll v1). I cannot redistribute newly compiled assemblies for WinApp.

Thanks in advance!

Chad

Body:
The problem here is that both the strong named Framework as the old Framework assembly are loaded. .NET does not really care that both definitions of IPlugin are the same. They are from a differend assembly so they are different (I am a little puzzled as why it will raise an InvalidCastException as a cast like that will just returns null if failed).

option A

One method to still use the class will be to use reflection but this might go a long way when more types hosted in Framework come to play. all of these will need to be accessed using reflection.
You can create wrappers to hide the reflection using something like this:

public class PluginWrapper : IPlugin
{
  object fObj;
  PropertyInfo fNameProperty;
  MethodInfo fGetOtherMethod;

  public PluginWrapper(object o)
  {
    fObj = o;
    fNameProperty = o.GetType().GetInterface("IPlugin").GetProperty("Name");
    fGetOtherMethod = o.GetType().GetInterface("IPlugin").GetMethod("GetOther", new Type[] { typeof(string) });
  }

  public string Name
  {
    get { return (string)fNameProperty.GetValue(fObj, null); }
  }

  public IOther GetOther(string name)
  {
    object result = fGetOtherMethod.Invoke(fObj, new object[] { name });

    if (result == null)
      return null;

    return new OtherWrapper(result);
  }
}

Then you can use your object as following:

IPlugin iPlugIn = new PluginWrapper(o);

option B

I can think of another way. I am not sure if this a road you should go as it looks a lot of "hacking" in my eyes but i'll share it anyway and let you decide.

You can let the assembly load using a byte stream instead of AssemblyName. That way it will be unable to resolve the other Framework assembly and giving you a change to break in on the AssemblyResolve event:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
Assembly dll = Assembly.Load(File.ReadAllBytes(@"C:\Program Files\WinApp\Assembly.dll"));
object o = Activator.CreateInstance(dll.GetType("WinApp.ClassThatImplementsIPlugIn"));
IPlugin iPlugIn = o as IPlugin;

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
  if (args.Name.ToLower().StartsWith("framework,"))
    return typeof(IPlugin ).Assembly;

  return null;
}

This might be a little tricky as by that you will give .NET a promise that the assembly is compatible and that you are prepared to take the risk. If things are not compatible then problems might quickly start to arise.

Other options

There might maybe also be ways to solve the problem using bindingredirect element in app.config. I'm not really known with the details about how that works but might be worth looking into a bit.


问:
overlay one pdf with another from the command line: pdftk alternative?
I use a bash script to auto-generate a pdf calendar each month.I use the wonderful remind program as the basis for this routine. Great as are the calendars I get using that program, I need a more detailed header for the calendar (than just the name of the month and the year). I couldn't puzzle out a way to get the remind program to enhance the header, but I was able to get the enhanced results I wanted by creating a second pdf containing the header enhancements I need, then overlaying that pdf onto the calendar I produce with remind, via the pdftk utility (pdftk calendar.pdf stamp calendar_overlay.pdf output MONTH-YEAR-cal.pdf). Unfortunately, I recently lost the ability to use pdftk since keeping it on my system would necessitate me ceasing to do other system updates. In short, I had to remove it in order to continue updating my system.

So now I'm looking for some alternative that I can incorporate into my bash script. I am not finding any utility that will allow me to overlay one pdf with another, like pdftk allows. It seems I may be able to do something like what I'm after using imagemagick (-convert), though I would likely need to overlay the pdf with an image file like a .jpg rather than with a pdf. Another possible solution may be to use TeX/LaTeX to insert text into the pdf as described at https://rsmith.home.xs4all.nl/howto/adding-text-or-graphics-to-a-pdf-file.html.

I wanted to ask here, before investing a lot of time and effort into pursuing one or other of the two potential options I've identified, whether there is some other way, using command line options that can be incorporated into a bash script, of overlaying one pdf with another in the manner described? Input will be appreciated.

LATER EDIT: another link with indications how to do such things using LaTeX https://askubuntu.com/questions/712691/batch-add-header-footer-to-pdf-files

答: pdftk-java is a Java-based port of pdftk which looks to be actively in development.  Given that its only real requirement appears to be Java 7+, it should work even in environments such as your own that no longer support the requirements of pdftk, so long as they have a Java runtime installed.</p>


问:
NaN resulting from sum of values in nodeJS
I'm fairly new to Javascript. But I created an HTML code that takes input and then the NodeJS runs it on the server to calculate the sum. I downloaded both modules properly. But I still seem to get Nan as the sum of numbers.

The code seems to work properly for a friend. And I copy pasted his JS code to mine, still no luck.

JS

```<code>const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
      console.log(req.body);
      var num1, num2, total = 0;
      num1 = req.body.num1;
      num2 = req.body.num2;
      total = num1 + num2;
      console.log(total);
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});
</code>```

HTML

```<code><form action="/" method="POST">
    <input type="text " name="num1 " placeholder="First Number " />
    <input type="text " name="num2 " placeholder="Second Number " />
    <button type="submit " name="submit ">Calculate</button>
</form>
</code>```

答:
2 mistakes:

you put spaces in the names

you use text instead of numbers

Here is a correct code:

```<code><form action="http://localhost:3000/" method="POST">
    <input type="number" name="num1" placeholder="First Number" />
    <input type="number" name="num2" placeholder="Second Number" />
    <button type="submit" name="submit">Calculate</button>
</form>

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
      console.log(req.body);
      var num1, num2, total = 0;
      num1 = +req.body.num1;
      num2 = +req.body.num2;
      total = num1 + num2;
      console.log(total);
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});
</code>```

Body:
I'm fairly new to Javascript. But I created an HTML code that takes input and then the NodeJS runs it on the server to calculate the sum. I downloaded both modules properly. But I still seem to get Nan as the sum of numbers.

The code seems to work properly for a friend. And I copy pasted his JS code to mine, still no luck.

JS

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
      console.log(req.body);
      var num1, num2, total = 0;
      num1 = req.body.num1;
      num2 = req.body.num2;
      total = num1 + num2;
      console.log(total);
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});

HTML

<form action="/" method="POST">
    <input type="text " name="num1 " placeholder="First Number " />
    <input type="text " name="num2 " placeholder="Second Number " />
    <button type="submit " name="submit ">Calculate</button>
</form>

Body:
2 mistakes:

you put spaces in the names

you use text instead of numbers

Here is a correct code:

<form action="http://localhost:3000/" method="POST">
    <input type="number" name="num1" placeholder="First Number" />
    <input type="number" name="num2" placeholder="Second Number" />
    <button type="submit" name="submit">Calculate</button>
</form>

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
      console.log(req.body);
      var num1, num2, total = 0;
      num1 = +req.body.num1;
      num2 = +req.body.num2;
      total = num1 + num2;
      console.log(total);
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});


问:
Cakephp - Display list element inside if
I'm currently displaying a list using cakephp, but I've been unable to redirect on clicking in an specific elemnt component which has to disappear in some cases, this is what I have:

```<code><li><a href="<?php echo $this->Url->build(["controller" => "pages","action" => "index"]);?>">Top 20</a>
<?php
$a = true;
  if($a){
    $prod_pm= '<li><a href="<?= $this->Url->build(["controller" => "Catalogo","action" => "cat",11229])?
    >">Promotions</a>';
  }else{
    $prod_pm = '';
}?>
<?= $prod_pm ?>
<li><a href="<?= $this->Url->build(["controller" => "Catalogo","action" => "cat",11050]) ?>"></a>
</code>```

It seems that the php redirected after the href citation is not working that way, also I tried declaring a variable with the code outside and inserting in place of $this->Url->build(["controller" => "Catalogo","action" => "cat",11229])
but didn't work.

Thanks in advance for any hint or help.

答:
You're trying to call PHP code from inside a string constant. The <?= is just taken as part of the string. Is there any reason why you need the $prod_pm variable? Seems like you are making this harder on yourself than it needs to be:

```<code><li>...
<?php
$a = true;
if ($a):
?>
<li><a href="<?= $this->Url->build(['controller' => 'Catalogo', 'action' => 'cat', 11229]) ?>">Promotions</a>
<?php
endif;
?>
<li>...
</code>```

or, equivalently,

```<code><li>...
<?php
$a = true;
if ($a) {
    echo $this->Html->tag('li',
        $this->Html->link('Promotions', ['controller' => 'Catalogo', 'action' => 'cat', 11229])
    );
}
?>
<li>...
</code>```

Body:
I'm currently displaying a list using cakephp, but I've been unable to redirect on clicking in an specific elemnt component which has to disappear in some cases, this is what I have:

<a href="<?php echo $this->Url->build(["controller" => "pages","action" => "index"]);?>">Top 20
<?php
$a = true;
  if($a){
    $prod_pm= '
<a href="<?= $this->Url->build(["controller" => "Catalogo","action" => "cat",11229])?
    >">Promotions';
  }else{
    $prod_pm = '';
}?>
<?= $prod_pm ?>

<a href="<?= $this->Url->build(["controller" => "Catalogo","action" => "cat",11050]) ?>">

It seems that the php redirected after the href citation is not working that way, also I tried declaring a variable with the code outside and inserting in place of $this->Url->build(["controller" => "Catalogo","action" => "cat",11229])
but didn't work.

Thanks in advance for any hint or help.

Body:
You're trying to call PHP code from inside a string constant. The <?= is just taken as part of the string. Is there any reason why you need the $prod_pm variable? Seems like you are making this harder on yourself than it needs to be:

<li>...
<?php
$a = true;
if ($a):
?>
<li><a href="<?= $this->Url->build(['controller' => 'Catalogo', 'action' => 'cat', 11229]) ?>">Promotions</a>
<?php
endif;
?>
<li>...

or, equivalently,

<li>...
<?php
$a = true;
if ($a) {
    echo $this->Html->tag('li',
        $this->Html->link('Promotions', ['controller' => 'Catalogo', 'action' => 'cat', 11229])
    );
}
?>
<li>...


问:
How to correct result with Union All
I am fetching the result of Union All but Only 1 query is running.

```<code>select user_leftside as SId  from tbl_user inner join (select @sid:=(select group_concat(user_leftside,',',user_rightside) from tbl_user where find_in_set(user_id, @nsid)) , @nsid:=@sid as fset from tbl_user, (select @nsid:='first_left_child',@sid='')v )gr on find_in_set(user_leftside,fset) where user_leftside <> ''
UNION ALL
select user_rightside as SId  from tbl_user inner join (select @sid:=(select group_concat(user_leftside,',',user_rightside) from tbl_user where find_in_set(user_id, @nsid)) , @nsid:=@sid as fset from tbl_user, (select @nsid:='first_left_child',@sid='')v )gr on find_in_set(user_rightside,fset) where user_rightside <> ''
</code>```

How can i get the result with Union All. This is tree related query

答:
Use different variable names inside those two subqueries.

The use of variables in MySQL queries is always risky: the order of evaluation is not guaranteed. These subqueries might even perform evaluations in parallel and so you must avoid spillover of variable values from one to the other.

Title: How to correct result with Union All

Body:
I am fetching the result of Union All but Only 1 query is running.

select user_leftside as SId  from tbl_user inner join (select @sid:=(select group_concat(user_leftside,',',user_rightside) from tbl_user where find_in_set(user_id, @nsid)) , @nsid:=@sid as fset from tbl_user, (select @nsid:='first_left_child',@sid='')v )gr on find_in_set(user_leftside,fset) where user_leftside <> ''
UNION ALL
select user_rightside as SId  from tbl_user inner join (select @sid:=(select group_concat(user_leftside,',',user_rightside) from tbl_user where find_in_set(user_id, @nsid)) , @nsid:=@sid as fset from tbl_user, (select @nsid:='first_left_child',@sid='')v )gr on find_in_set(user_rightside,fset) where user_rightside <> ''

How can i get the result with Union All. This is tree related query


问:
Azure CDN connect custom domain
I have static website on azure storage, it's connected to azure cdn to have https, and i have my custom domain folla.com.pl I want this domain to point to https://companywebsitecdn.azureedge.net/ which is address of my website on azure cdn. I chose custom domain on cdn configuration site, it asks me to make dns mapping to verify ownership, so i make CNAME cdnverify.folla.com.pl to cdnveriy.companywebsitecdn.azureedge.net  and it get me to other window with custom doamin https config. And here's my problem, it get's stuck on second step

How I'm suppouse to configure another mapping to make it work, what i mean is to make folla.com.pl to point to https://companywebsitecdn.azureedge.net/ with https. I can't proivde what i already tried with my dns because it was a lot and i don't remember all of it. Also it's already second try and everytime after failure I have wait 8 hours for another try. Thanks in advance

This is my DNS config

答:
When you try to add your custom domain folla.com.pl in the custom domains settings of Azure CDN endpoint. Before this step, you should have a CNAME record in the following format in the DNS zone.

When you turn on the custom domain https, you don't need to make a CNAME cdnverify.folla.com.pl to cdnveriy.companywebsitecdn.azureedge.net. Read here.

If that CNAME record still exists and does not contain the cdnverify
  subdomain, the DigiCert CA uses it to automatically validate ownership
  of your custom domain.

If the CNAME record entry contains the cdnverify subdomain, follow the rest of the instructions in this step.

DigiCert sends a verification email to the following email addresses. Verify that you can approve directly from one of the following addresses and read here.

```<code>admin@<your-domain-name.com>
administrator@<your-domain-name.com>
webmaster@<your-domain-name.com>
hostmaster@<your-domain-name.com>
postmaster@<your-domain-name.com>
</code>```

Automatic validation typically takes a few hours. If you don’t see your domain validated in 24 hours, open a support ticket.

Title: Azure CDN connect custom domain

Body:
When you try to add your custom domain folla.com.pl in the custom domains settings of Azure CDN endpoint. Before this step, you should have a CNAME record in the following format in the DNS zone.

When you turn on the custom domain https, you don't need to make a CNAME cdnverify.folla.com.pl to cdnveriy.companywebsitecdn.azureedge.net. Read here.

If that CNAME record still exists and does not contain the cdnverify
  subdomain, the DigiCert CA uses it to automatically validate ownership
  of your custom domain.

If the CNAME record entry contains the cdnverify subdomain, follow the rest of the instructions in this step.

DigiCert sends a verification email to the following email addresses. Verify that you can approve directly from one of the following addresses and read here.

admin@<your-domain-name.com>
administrator@<your-domain-name.com>
webmaster@<your-domain-name.com>
hostmaster@<your-domain-name.com>
postmaster@<your-domain-name.com>

Automatic validation typically takes a few hours. If you don’t see your domain validated in 24 hours, open a support ticket.


问:
How to round away from 0 in Python 3.x?
In Python 2 rounding is done away from 0, so, for example, round(0.5) is 1.0.

In Python 3.x, however, rounding is done toward the even choice, so round(0.5)  is 0.

What function can I use in Python 3.x to get the old behavior?

答:
Pretty much like the other solutions, but using a shorthand if statement instead of a function:

```<code>    segments = ceil(gamma / 90) if gamma > 0 else floor(gamma/90)
</code>```

Title: How to round away from 0 in Python 3.x?

Body:
Pretty much like the other solutions, but using a shorthand if statement instead of a function:

    segments = ceil(gamma / 90) if gamma > 0 else floor(gamma/90)


问:
call to pure virtual function from base class constructor
I have a base class MyBase that contains a pure virtual function:

void PrintStartMessage() = 0

I want each derived class to call it in their constructor

then I put it in base class(MyBase) constructor

```<code> class MyBase
 {
 public:

      virtual void PrintStartMessage() =0;
      MyBase()
      {
           PrintStartMessage();
      }

 };

 class Derived:public MyBase
 {

 public:
      void  PrintStartMessage(){

      }
 };

void main()
 {
      Derived derived;
 }
</code>```

but I get a linker error.

```<code> this is error message :

 1>------ Build started: Project: s1, Configuration: Debug Win32 ------
 1>Compiling...
 1>s1.cpp
 1>Linking...
 1>s1.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall MyBase::PrintStartMessage(void)" (?PrintStartMessage@MyBase@@UAEXXZ) referenced in function "public: __thiscall MyBase::MyBase(void)" (??0MyBase@@QAE@XZ)
 1>C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe : fatal error LNK1120: 1 unresolved externals
 1>s1 - 2 error(s), 0 warning(s)
</code>```

I want force to all derived classes to...

```<code>A- implement it

B- call it in their constructor
</code>```

How I must do it?

答:
Facing the same problem, I imaginated a (not perfect) solution. The idea is to provide a certificate to the base class that the pure virtual init function will be called after the construction.

```<code>class A
{
  private:
    static const int checkValue;
  public:
    A(int certificate);
    A(const A& a);
    virtual ~A();
    virtual void init() = 0;
  public:
    template <typename T> static T create();
    template <typeneme T> static T* create_p();
    template <typename T, typename U1> static T create(const U1& u1);
    template <typename T, typename U1> static T* create_p(const U1& u1);
    //... all the required possibilities can be generated by prepro loops
};

const int A::checkValue = 159736482; // or any random value

A::A(int certificate)
{
  assert(certificate == A::checkValue);
}

A::A(const A& a)
{}

A::~A()
{}

template <typename T>
T A::create()
{
  T t(A::checkValue);
  t.init();
  return t;
}

template <typename T>
T* A::create_p()
{
  T* t = new T(A::checkValue);
  t->init();
  return t;
}

template <typename T, typename U1>
T A::create(const U1& u1)
{
  T t(A::checkValue, u1);
  t.init();
  return t;
}

template <typename T, typename U1>
T* A::create_p(const U1& u1)
{
  T* t = new T(A::checkValue, u1);
  t->init();
  return t;
}

class B : public A
{
  public:
    B(int certificate);
    B(const B& b);
    virtual ~B();
    virtual void init();
};

B::B(int certificate) :
  A(certificate)
{}

B::B(const B& b) :
  A(b)
{}

B::~B()
{}

void B::init()
{
  std::cout << "call B::init()" << std::endl;
}

class C : public A
{
  public:
    C(int certificate, double x);
    C(const C& c);
    virtual ~C();
    virtual void init();
  private:
    double x_;
};

C::C(int certificate, double x) :
  A(certificate)
  x_(x)
{}

C::C(const C& c) :
  A(c)
  x_(c.x_)
{}

C::~C()
{}

void C::init()
{
  std::cout << "call C::init()" << std::endl;
}
</code>```

Then, the user of the class can't construct an instance without giving the certificate, but the certificate can only be produced by the creation functions:

```<code>B b = create<B>(); // B::init is called
C c = create<C,double>(3.1415926535); // C::init is called
</code>```

Moreover, the user can't create new classes inheriting from A B or C without implementing the certificate transmission in the constructor. Then, the base class A has the warranty that init will be called after construction.

Body:
I have a base class MyBase that contains a pure virtual function:

void PrintStartMessage() = 0

I want each derived class to call it in their constructor

then I put it in base class(MyBase) constructor

 class MyBase
 {
 public:

      virtual void PrintStartMessage() =0;
      MyBase()
      {
           PrintStartMessage();
      }

 };

 class Derived:public MyBase
 {

 public:
      void  PrintStartMessage(){

      }
 };

void main()
 {
      Derived derived;
 }

but I get a linker error.

 this is error message :

 1>------ Build started: Project: s1, Configuration: Debug Win32 ------
 1>Compiling...
 1>s1.cpp
 1>Linking...
 1>s1.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall MyBase::PrintStartMessage(void)" (?PrintStartMessage@MyBase@@UAEXXZ) referenced in function "public: __thiscall MyBase::MyBase(void)" (??0MyBase@@QAE@XZ)
 1>C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe : fatal error LNK1120: 1 unresolved externals
 1>s1 - 2 error(s), 0 warning(s)

I want force to all derived classes to...

A- implement it

B- call it in their constructor

How I must do it?

Body:
Facing the same problem, I imaginated a (not perfect) solution. The idea is to provide a certificate to the base class that the pure virtual init function will be called after the construction.

class A
{
  private:
    static const int checkValue;
  public:
    A(int certificate);
    A(const A& a);
    virtual ~A();
    virtual void init() = 0;
  public:
    template <typename T> static T create();
    template <typeneme T> static T* create_p();
    template <typename T, typename U1> static T create(const U1& u1);
    template <typename T, typename U1> static T* create_p(const U1& u1);
    //... all the required possibilities can be generated by prepro loops
};

const int A::checkValue = 159736482; // or any random value

A::A(int certificate)
{
  assert(certificate == A::checkValue);
}

A::A(const A& a)
{}

A::~A()
{}

template <typename T>
T A::create()
{
  T t(A::checkValue);
  t.init();
  return t;
}

template <typename T>
T* A::create_p()
{
  T* t = new T(A::checkValue);
  t->init();
  return t;
}

template <typename T, typename U1>
T A::create(const U1& u1)
{
  T t(A::checkValue, u1);
  t.init();
  return t;
}

template <typename T, typename U1>
T* A::create_p(const U1& u1)
{
  T* t = new T(A::checkValue, u1);
  t->init();
  return t;
}

class B : public A
{
  public:
    B(int certificate);
    B(const B& b);
    virtual ~B();
    virtual void init();
};

B::B(int certificate) :
  A(certificate)
{}

B::B(const B& b) :
  A(b)
{}

B::~B()
{}

void B::init()
{
  std::cout << "call B::init()" << std::endl;
}

class C : public A
{
  public:
    C(int certificate, double x);
    C(const C& c);
    virtual ~C();
    virtual void init();
  private:
    double x_;
};

C::C(int certificate, double x) :
  A(certificate)
  x_(x)
{}

C::C(const C& c) :
  A(c)
  x_(c.x_)
{}

C::~C()
{}

void C::init()
{
  std::cout << "call C::init()" << std::endl;
}

Then, the user of the class can't construct an instance without giving the certificate, but the certificate can only be produced by the creation functions:

B b = create<B>(); // B::init is called
C c = create<C,double>(3.1415926535); // C::init is called

Moreover, the user can't create new classes inheriting from A B or C without implementing the certificate transmission in the constructor. Then, the base class A has the warranty that init will be called after construction.


问:
Unable to add an array index
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

```<code>// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };
</code>```

i want to get something like

```<code>f0: 1,
f1: 5,
f2: 9
</code>```

答:
Try this:</p>

```<code>         for( const [key, value] of Object.entries(test)){
                let obj= {};
                obj['f' +key] = value;
                this.sf.push(obj);
                    }
</code>```

Title: Unable to add an array index

Body:
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };

i want to get something like

f0: 1,
f1: 5,
f2: 9

Body:
Try this:

         for( const [key, value] of Object.entries(test)){
                let obj= {};
                obj['f' +key] = value;
                this.sf.push(obj);
                    }


问:
Help with a SQL Query
I have a question on a SQL query and im wondering where to start. Thoughts so far include creating a table in memory with a range of dates, and joining on to it to get the sum of hours entered for a particular day.

Just to give an idea of the background of this question here is a little information.

The database is structured like so:

The result im trying to achieve with the query im currently writing needs to look like this:

The Query I have written so far:

```<code>DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2011/05/01 00:00'
SET @WeekEndDate = '2011/05/07 00:00'

SELECT
[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
'???' AS 'Mon',
'???' AS 'Tue',
'???' AS 'Wed',
'???' AS 'Thu',
'???' AS 'Fri',
'???' AS 'Sat',
'???' AS 'Sun'

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode]
</code>```

And this outputs the result set below:

As you can see the result set is almost there, I just need to total the number of hours worked on that particular day, grouping on ContractID, JobID, ProjectID, CostRateCode so I can get the number of hours for each cost rate on each unique project.

Is this possible with the current table design? or by using a temporary calendar table for the dates between the two passed in to the query?

EDIT:
Updated Query:

```<code>SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @RequestedByID AS BIGINT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME
DECLARE @WaitingForUserID AS BIGINT
DECLARE @WaitingForUserTypeID AS BIGINT
DECLARE @WaitingForTypeUser AS VARCHAR(50)
DECLARE @WaitingForTypeUserType AS VARCHAR(50)

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 1
THEN SUM(JobSheetLineHours.Hours )
END
AS MON,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 2
THEN SUM(JobSheetLineHours.Hours )
END
AS TUE,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 3
THEN SUM(JobSheetLineHours.Hours )
END
AS WED,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 4
THEN SUM(JobSheetLineHours.Hours )
END
AS THU,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 5
THEN SUM(JobSheetLineHours.Hours )
END
AS FRI,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 6
THEN SUM(JobSheetLineHours.Hours )
END
AS SAT,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 7
THEN SUM(JobSheetLineHours.Hours )
END
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode],
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
    WHEN 1
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 2
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 3
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 4
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 5
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 6
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 7
    THEN     JobSheetLineHours.Hours
    END
</code>```

Updated Result Set:

What I'm trying to do now is remove the JobSheetDate from the result set so the Total hours for each day are not all on seperate rows eg. The values for the same contract, project etc are put in the same row, but in the Mon, Tues, Wed etc column, rather than on multiple rows with the hours for one day populated, and the rest of the days null (see screenshot)

EDIT 2:
Updated Query:

```<code>SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
--[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 1
THEN JobSheetLineHours.Hours
END )
AS MON,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 2
THEN JobSheetLineHours.Hours
END )
AS TUE,
SUM(CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 3
THEN JobSheetLineHours.Hours
END)
AS WED,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 4
THEN JobSheetLineHours.Hours
END)
AS THU,
SUM(CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 5
THEN JobSheetLineHours.Hours
END )
AS FRI,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 6
THEN JobSheetLineHours.Hours
END )
AS SAT,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 7
THEN JobSheetLineHours.Hours
END )
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    --[JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode],
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
    WHEN 1
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 2
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 3
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 4
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 5
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 6
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 7
    THEN     JobSheetLineHours.Hours
    END
</code>```

Results:

FINAL Update with finished Query:

```<code>SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Monday
     WHEN 1
     THEN [JobSheetLineHours].[Hours]
     END )
AS MON,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Tuesday
     WHEN 2
     THEN [JobSheetLineHours].[Hours]
     END )
AS TUE,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Wednesday
     WHEN 3
     THEN [JobSheetLineHours].[Hours]
     END )
AS WED,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Thursday
     WHEN 4
     THEN [JobSheetLineHours].[Hours]
     END )
AS THU,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Friday
     WHEN 5
     THEN [JobSheetLineHours].[Hours]
     END )
AS FRI,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Saturday
     WHEN 6
     THEN [JobSheetLineHours].[Hours]
     END )
AS SAT,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Sunday
     WHEN 7
     THEN [JobSheetLineHours].[Hours]
     END )
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode]
</code>```

答:
Try a subquery where you have the question marks for the days, one subquery for each day of the week; the date of the day is calculated from dates passed in.  Monday's would be:

```<code>( SELECT SUM([JobSheetLineHours].[Hours])
  FROM [JobSheet]
  INNER JOIN [JobSheetLine] ON [JobSheetLine].[JobSheetID] =
    [JobSheet].[JobSheetID]
  INNER JOIN [JobSheetLineHours] ON [JobSheetLineHours].[JobSheetLineID] =
    [JobSheetLine].[JobSheetLineID]
  WHERE[JobSheet].[JobSheetDate] = @WeekStartDate + 1 AND
   [JobSheet].[Deleted]=@Deleted AND
   [JobSheetLine].[Deleted]=@Deleted AND
   [JobSheetLineHours].[Deleted]=@Deleted )
</code>```

For Tuesday you would add 2, etc.

NOTE: This will only work if @WeekStartDate is indeed a Sunday, though it seems that you are already assuming such.

Title: Help with a SQL Query

Body:
I have a question on a SQL query and im wondering where to start. Thoughts so far include creating a table in memory with a range of dates, and joining on to it to get the sum of hours entered for a particular day.

Just to give an idea of the background of this question here is a little information.

The database is structured like so:

The result im trying to achieve with the query im currently writing needs to look like this:

The Query I have written so far:

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2011/05/01 00:00'
SET @WeekEndDate = '2011/05/07 00:00'

SELECT
[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
'???' AS 'Mon',
'???' AS 'Tue',
'???' AS 'Wed',
'???' AS 'Thu',
'???' AS 'Fri',
'???' AS 'Sat',
'???' AS 'Sun'

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode]

And this outputs the result set below:

As you can see the result set is almost there, I just need to total the number of hours worked on that particular day, grouping on ContractID, JobID, ProjectID, CostRateCode so I can get the number of hours for each cost rate on each unique project.

Is this possible with the current table design? or by using a temporary calendar table for the dates between the two passed in to the query?

EDIT:
Updated Query:

SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @RequestedByID AS BIGINT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME
DECLARE @WaitingForUserID AS BIGINT
DECLARE @WaitingForUserTypeID AS BIGINT
DECLARE @WaitingForTypeUser AS VARCHAR(50)
DECLARE @WaitingForTypeUserType AS VARCHAR(50)

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 1
THEN SUM(JobSheetLineHours.Hours )
END
AS MON,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 2
THEN SUM(JobSheetLineHours.Hours )
END
AS TUE,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 3
THEN SUM(JobSheetLineHours.Hours )
END
AS WED,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 4
THEN SUM(JobSheetLineHours.Hours )
END
AS THU,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 5
THEN SUM(JobSheetLineHours.Hours )
END
AS FRI,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 6
THEN SUM(JobSheetLineHours.Hours )
END
AS SAT,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 7
THEN SUM(JobSheetLineHours.Hours )
END
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode],
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
    WHEN 1
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 2
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 3
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 4
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 5
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 6
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 7
    THEN     JobSheetLineHours.Hours
    END

Updated Result Set:

What I'm trying to do now is remove the JobSheetDate from the result set so the Total hours for each day are not all on seperate rows eg. The values for the same contract, project etc are put in the same row, but in the Mon, Tues, Wed etc column, rather than on multiple rows with the hours for one day populated, and the rest of the days null (see screenshot)

EDIT 2:
Updated Query:

SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
--[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 1
THEN JobSheetLineHours.Hours
END )
AS MON,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 2
THEN JobSheetLineHours.Hours
END )
AS TUE,
SUM(CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 3
THEN JobSheetLineHours.Hours
END)
AS WED,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 4
THEN JobSheetLineHours.Hours
END)
AS THU,
SUM(CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 5
THEN JobSheetLineHours.Hours
END )
AS FRI,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 6
THEN JobSheetLineHours.Hours
END )
AS SAT,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 7
THEN JobSheetLineHours.Hours
END )
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    --[JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode],
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
    WHEN 1
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 2
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 3
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 4
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 5
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 6
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 7
    THEN     JobSheetLineHours.Hours
    END

Results:

FINAL Update with finished Query:

SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Monday
     WHEN 1
     THEN [JobSheetLineHours].[Hours]
     END )
AS MON,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Tuesday
     WHEN 2
     THEN [JobSheetLineHours].[Hours]
     END )
AS TUE,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Wednesday
     WHEN 3
     THEN [JobSheetLineHours].[Hours]
     END )
AS WED,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Thursday
     WHEN 4
     THEN [JobSheetLineHours].[Hours]
     END )
AS THU,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Friday
     WHEN 5
     THEN [JobSheetLineHours].[Hours]
     END )
AS FRI,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Saturday
     WHEN 6
     THEN [JobSheetLineHours].[Hours]
     END )
AS SAT,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Sunday
     WHEN 7
     THEN [JobSheetLineHours].[Hours]
     END )
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode]

Body:
Try a subquery where you have the question marks for the days, one subquery for each day of the week; the date of the day is calculated from dates passed in.  Monday's would be:

( SELECT SUM([JobSheetLineHours].[Hours])
  FROM [JobSheet]
  INNER JOIN [JobSheetLine] ON [JobSheetLine].[JobSheetID] =
    [JobSheet].[JobSheetID]
  INNER JOIN [JobSheetLineHours] ON [JobSheetLineHours].[JobSheetLineID] =
    [JobSheetLine].[JobSheetLineID]
  WHERE[JobSheet].[JobSheetDate] = @WeekStartDate + 1 AND
   [JobSheet].[Deleted]=@Deleted AND
   [JobSheetLine].[Deleted]=@Deleted AND
   [JobSheetLineHours].[Deleted]=@Deleted )

For Tuesday you would add 2, etc.

NOTE: This will only work if @WeekStartDate is indeed a Sunday, though it seems that you are already assuming such.


问:
How can I set individual marker size on stock marker series in Anychart?
How can I set individual marker size on STOCK MARKER series? It works fine on basic MARKER series: https://docs.anychart.com/Basic_Charts/Marker_Chart#individual_points</p>

答:
The Stock chart implements a special mode that supports individual point settings. Usually, it is required for coloring but it also supports marker sizing too.
Here is the sample.
Pay attention to the chart data and line 19. The true argument is required to enable this mode.


问:
Signed integer promote to unsigned long
In x86-64 linux environment, why C promote signed integer -1 to unsigned long 0xffffffffffffffff, but not 0xffffffff?</p>

```<code>#include <stdio.h>

int main() {
  unsigned long ul = (int)-1;
  printf("%lx\n", ul);
}
</code>```

答:
C11 §6.3.1.3 Signed and unsigned integers ¶1,2:

When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)

60) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.

So, -1 is converted by adding ULONG_MAX + 1, yielding ULONG_MAX, as you discovered.  Your system must be using 64 bits for the unsigned long type.

Title: Signed integer promote to unsigned long

Body:
In x86-64 linux environment, why C promote signed integer -1 to unsigned long 0xffffffffffffffff, but not 0xffffffff?

#include <stdio.h>

int main() {
  unsigned long ul = (int)-1;
  printf("%lx\n", ul);
}


问:
Error when loading external xml file with php via https : SSL3_GET_SERVER_CERTIFICATE
I can't get a xml file to load.

This code works great:

```<code>$url = 'http://www.w3schools.com/xml/note.xml';
$xml = simplexml_load_file($url);
print_r($xml);
</code>```

But this one

```<code>$url = 'https://www.boardgamegeek.com/xmlapi2/thing?id=105551';
$xml = simplexml_load_file($url);
print_r($xml);
</code>```

doesn't work. I get this error:

Warning: simplexml_load_file(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in /storage/content/59/113059/boardgamelevelup.com/public_html/index.php on line 19 Warning: simplexml_load_file(): Failed to enable crypto in /storage/content/59/113059/boardgamelevelup.com/public_html/index.php on line 19 Warning: simplexml_load_file(https://www.boardgamegeek.com/xmlapi2/thing?id=105551): failed to open stream: operation failed in /storage/content/59/113059/boardgamelevelup.com/public_html/index.php on line 19 Warning: simplexml_load_file(): I/O warning : failed to load external entity "https://www.boardgamegeek.com/xmlapi2/thing?id=105551" in /storage/content/59/113059/boardgamelevelup.com/public_html/index.php on line 19

The xml file from boardgamegeek works on other sites. Should I use a different php code to load that xml file?

答:
The work and example that @VolkerK displayed was excellent and simple.
While this method didn't work for me, I took it one step further and basically removed the security for the moment.

```<code>$context = stream_context_create(array('ssl'=>array(
    'verify_peer' => false,
    "verify_peer_name"=>false
    )));

libxml_set_streams_context($context);

$sxml = simplexml_load_file($webhostedXMLfile);
</code>```

Yes, this is bad practice, but sometimes you need a temp fix instead of messages like this:

Warning: simplexml_load_file(): SSL operation failed with code 1.
  OpenSSL Error messages: error:14090086:SSL
  routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in
  /srv/www/resources/public_html/files/etc/file.php on line 150 Warning:
  simplexml_load_file(): Failed to enable crypto in
  /srv/www/resources/public_html/files/etc/file.php on line 150

I hope it helps someone else.

Body:
I can't get a xml file to load.

This code works great:

$url = 'http://www.w3schools.com/xml/note.xml';
$xml = simplexml_load_file($url);
print_r($xml);

But this one

$url = 'https://www.boardgamegeek.com/xmlapi2/thing?id=105551';
$xml = simplexml_load_file($url);
print_r($xml);

doesn't work. I get this error:

Warning: simplexml_load_file(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in /storage/content/59/113059/boardgamelevelup.com/public_html/index.php on line 19 Warning: simplexml_load_file(): Failed to enable crypto in /storage/content/59/113059/boardgamelevelup.com/public_html/index.php on line 19 Warning: simplexml_load_file(https://www.boardgamegeek.com/xmlapi2/thing?id=105551): failed to open stream: operation failed in /storage/content/59/113059/boardgamelevelup.com/public_html/index.php on line 19 Warning: simplexml_load_file(): I/O warning : failed to load external entity "https://www.boardgamegeek.com/xmlapi2/thing?id=105551" in /storage/content/59/113059/boardgamelevelup.com/public_html/index.php on line 19

The xml file from boardgamegeek works on other sites. Should I use a different php code to load that xml file?

Body:
The work and example that @VolkerK displayed was excellent and simple.
While this method didn't work for me, I took it one step further and basically removed the security for the moment.

$context = stream_context_create(array('ssl'=>array(
    'verify_peer' => false,
    "verify_peer_name"=>false
    )));

libxml_set_streams_context($context);

$sxml = simplexml_load_file($webhostedXMLfile);

Yes, this is bad practice, but sometimes you need a temp fix instead of messages like this:

Warning: simplexml_load_file(): SSL operation failed with code 1.
  OpenSSL Error messages: error:14090086:SSL
  routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in
  /srv/www/resources/public_html/files/etc/file.php on line 150 Warning:
  simplexml_load_file(): Failed to enable crypto in
  /srv/www/resources/public_html/files/etc/file.php on line 150

I hope it helps someone else.


问:
I want to swap objects keys with new key in javascript. How can I do that?
I am displaying keypad  from 0 to 9 keys and adding action to it.
EX:
keypad display

I have keypad array to display keypad:

```<code>const keypad= [
 {
    symbol: '1',
    checked: false
  },
  {
    symbol: '2',
    alias: 'abc',
    checked: false
  },
  {
    symbol: '3',
    alias: 'def',
    checked: false
  },
  {
    symbol: '4',
    alias: 'ghi',
    checked: false
  },
 ......
]
</code>```

When toggle any key, it will add action to it and storing it to redux as object:
Ex: here in this screenshot, I have selected ket 1,2, and 3. My redux object will be like this.

```<code>const obj1 = {
   "1": {keypadValue:{symbol:"1", alias:undefined},selectedAction:"exit"}
   "2": {keypadValue:{symbol:"2", alias:'abc'},selectedAction:"repeat menu"}',
   "3": {keypadValue:{symbol:"3", alias:'def},selectedAction:"name dialing"}
}
</code>```

Now I want to swap keys: I have selected keys 1,2 and 3. I can swap key with this 3 as well as I can swap with keys those are not selected from keypad. those I can select from dropdown.

I have dropdowndropdown keypad
1. when I click key 1 and choose key 4 from dropdown, I want to swap key 1 with 4. SO in this case key 1 will be unchecked and key 4 will be checked.

It can also swap with selected action key: Ex: I can swap key 1 with 2, key 1 with 3 and etc...

If I swap key 1 with key 2 my redux object would be:

```<code>const obj1 = {
   "2": {keypadValue:{symbol:"2", alias:'abc'},selectedAction:"exit"}
   "1": {keypadValue:{symbol:"1", alias:undefined},selectedAction:"repeat menu"}',
   "3": {keypadValue:{symbol:"3", alias:'def},selectedAction:"name dialing"}
}

</code>```

If I swap Key 2 with 4

object will be:

```<code>const obj1 = {
   "1": {keypadValue:{symbol:"1", alias:undefined},selectedAction:"exit"}
   "4": {keypadValue:{symbol:"4", alias:'ghi'},selectedAction:"repeat menu"}',
   "3": {keypadValue:{symbol:"3", alias:'def},selectedAction:"name dialing"}
}
</code>```

how can I do this?

I have tried given solution. but it didnt work!!

```<code>handleRoutingActionKeypadToggle(newKey) {
    const { actions, object } = this.props;
    const { oldKey, keypad } = this.state;

    const updatedKey = manageChangeKeyOption(
      object,
      oldKey,
      newKey,
      keypad
    );

    actions.updateRoutingAction(updatedKey);

    console.log('updatedKey', updatedKey);
  }

export const updateObject = (obj, key, keypad) => {
  const keypadObj = keypad.find(k => k.symbol === key);

  obj.keypadValue = keypadObj;
};

export const manageChangeKeyOption = (
  object,
  oldKey,
  newKey,
  keypad
) => {
  if (object[oldKey.symbol] && object[newKey.symbol]) {
    const oldKeyData = object[newKey.symbol];

    object[oldKey.symbol] = object[newKey.symbol];

    object[newKey.symbol] = oldKeyData;
    updateObject(
      object[oldKey.symbol],
      oldKey.symbol,
      keypad
    );

    updateObject(object[newKey.symbol], newKey.symbol, keypad);

    return object;
  } else if (object[oldKey.symbol]) {
    object[newKey.symbol] = object[oldKey.symbol];
    updateObject(object[newKey.symbol], newKey.symbol, keypad);
    delete object[oldKey.symbol];

    return object;
  }
};
</code>```

console

答:
Can you please try this snippet? This should work for you

const keypad= [
 {
    symbol: '1',
    checked: false
  },
  {
    symbol: '2',
    alias: 'abc',
    checked: false
  },
  {
    symbol: '3',
    alias: 'def',
    checked: false
  },
  {
    symbol: '4',
    alias: 'ghi',
    checked: false
  }
]
const obj1 = {
   "1": {keypadValue:{symbol:"1", alias:undefined},selectedAction:"exit"},
   "2": {keypadValue:{symbol:"2", alias:'abc'},selectedAction:"repeat menu"},
   "3": {keypadValue:{symbol:"3", alias:'def'},selectedAction:"name dialing"}
}
function updatePosition(oldKey, newKey){
 if(obj1[oldKey] && obj1[newKey]){
     //swap keys
        let oldKeyData = obj1[oldKey];
        obj1[oldKey] = obj1[newKey];
        obj1[newKey] = oldKeyData;
        updateObject(obj1[oldKey], oldKey);
        updateObject(obj1[newKey], newKey);
    }else{
     if(obj1[oldKey]){
         obj1[newKey] = obj1[oldKey];
            updateObject(obj1[newKey], newKey);
            delete obj1[oldKey];
        }else{
         //this is new insert to list
        }
    }
    return obj1;
}
function updateObject(obj, key){
   let keypadObj = keypad.find(k => k.symbol == key);
    obj.keypadValue = keypadObj;
}
console.log(updatePosition(1,2));
console.log(updatePosition(1,4));```

Body:
I am displaying keypad  from 0 to 9 keys and adding action to it.
EX:
keypad display

I have keypad array to display keypad:

const keypad= [
 {
    symbol: '1',
    checked: false
  },
  {
    symbol: '2',
    alias: 'abc',
    checked: false
  },
  {
    symbol: '3',
    alias: 'def',
    checked: false
  },
  {
    symbol: '4',
    alias: 'ghi',
    checked: false
  },
 ......
]

When toggle any key, it will add action to it and storing it to redux as object:
Ex: here in this screenshot, I have selected ket 1,2, and 3. My redux object will be like this.

const obj1 = {
   "1": {keypadValue:{symbol:"1", alias:undefined},selectedAction:"exit"}
   "2": {keypadValue:{symbol:"2", alias:'abc'},selectedAction:"repeat menu"}',
   "3": {keypadValue:{symbol:"3", alias:'def},selectedAction:"name dialing"}
}

Now I want to swap keys: I have selected keys 1,2 and 3. I can swap key with this 3 as well as I can swap with keys those are not selected from keypad. those I can select from dropdown.

I have dropdowndropdown keypad
1. when I click key 1 and choose key 4 from dropdown, I want to swap key 1 with 4. SO in this case key 1 will be unchecked and key 4 will be checked.

It can also swap with selected action key: Ex: I can swap key 1 with 2, key 1 with 3 and etc...

If I swap key 1 with key 2 my redux object would be:

const obj1 = {
   "2": {keypadValue:{symbol:"2", alias:'abc'},selectedAction:"exit"}
   "1": {keypadValue:{symbol:"1", alias:undefined},selectedAction:"repeat menu"}',
   "3": {keypadValue:{symbol:"3", alias:'def},selectedAction:"name dialing"}
}

If I swap Key 2 with 4

object will be:

const obj1 = {
   "1": {keypadValue:{symbol:"1", alias:undefined},selectedAction:"exit"}
   "4": {keypadValue:{symbol:"4", alias:'ghi'},selectedAction:"repeat menu"}',
   "3": {keypadValue:{symbol:"3", alias:'def},selectedAction:"name dialing"}
}

how can I do this?

I have tried given solution. but it didnt work!!

handleRoutingActionKeypadToggle(newKey) {
    const { actions, object } = this.props;
    const { oldKey, keypad } = this.state;

    const updatedKey = manageChangeKeyOption(
      object,
      oldKey,
      newKey,
      keypad
    );

    actions.updateRoutingAction(updatedKey);

    console.log('updatedKey', updatedKey);
  }

export const updateObject = (obj, key, keypad) => {
  const keypadObj = keypad.find(k => k.symbol === key);

  obj.keypadValue = keypadObj;
};

export const manageChangeKeyOption = (
  object,
  oldKey,
  newKey,
  keypad
) => {
  if (object[oldKey.symbol] && object[newKey.symbol]) {
    const oldKeyData = object[newKey.symbol];

    object[oldKey.symbol] = object[newKey.symbol];

    object[newKey.symbol] = oldKeyData;
    updateObject(
      object[oldKey.symbol],
      oldKey.symbol,
      keypad
    );

    updateObject(object[newKey.symbol], newKey.symbol, keypad);

    return object;
  } else if (object[oldKey.symbol]) {
    object[newKey.symbol] = object[oldKey.symbol];
    updateObject(object[newKey.symbol], newKey.symbol, keypad);
    delete object[oldKey.symbol];

    return object;
  }
};

console


问:
An Error Occurred While serializing to JSON
Hi firends i'm getting error when i tried to Serialize JSON. I have a model and it have List property;
MyModel:

```<code>public virtual int Kod { get; set; }
    public virtual string Ad { get; set; }
    public virtual string TrafikKod { get; set; }
    public virtual int TapuKod { get; set; }
    public virtual bool AktifMi { get; set; }

    [JsonIgnore]
    public virtual IList<TapuIlceModel> IlceList { get; set; }

    public TapuIlModel()
    {
        IlceList = new List<TapuIlceModel>();
    }
</code>```

MyApiController:

```<code>  [Route("api/TapuZeminApi/GetZemins")]
    [HttpPost]
    public string GetZeminsFromZeminArg(object arg)
    {
        ZeminArg zemArg = SConvert.DeserializeJSON<ZeminArg>(arg.ToString());

        List<TapuZeminModel> zeminList = TapuModule.GetZeminListFromArgs(zemArg);

        string jsonResult = SConvert.SerializeJSON(zeminList);
        return jsonResult;
</code>```

Here is a picture about my reciving data error;

And this my inner exc.;

.{"Error getting value from 'ReadOnly' on 'NHibernate.Proxy.DefaultLazyInitializer'."}

.{"Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session."}

What should i do? I need all data... Thanks

when i check again i found something like that:

Why is there 2 base??? And why name is different? Anyone know?

答:
I geting same error when serilize SerializeJSON(object) , i have try JsonConvert.SerializeObject with JsonSerializerSettings and ContractResolver, it will work.

```<code>string jsonResult = JsonConvert.SerializeObject(object, new JsonSerializerSettings() {
            ContractResolver = new NHibernateContractResolver()
        });
</code>```

Body:
Hi firends i'm getting error when i tried to Serialize JSON. I have a model and it have List property;
MyModel:

public virtual int Kod { get; set; }
    public virtual string Ad { get; set; }
    public virtual string TrafikKod { get; set; }
    public virtual int TapuKod { get; set; }
    public virtual bool AktifMi { get; set; }

    [JsonIgnore]
    public virtual IList<TapuIlceModel> IlceList { get; set; }

    public TapuIlModel()
    {
        IlceList = new List<TapuIlceModel>();
    }

MyApiController:

  [Route("api/TapuZeminApi/GetZemins")]
    [HttpPost]
    public string GetZeminsFromZeminArg(object arg)
    {
        ZeminArg zemArg = SConvert.DeserializeJSON<ZeminArg>(arg.ToString());

        List<TapuZeminModel> zeminList = TapuModule.GetZeminListFromArgs(zemArg);

        string jsonResult = SConvert.SerializeJSON(zeminList);
        return jsonResult;

Here is a picture about my reciving data error;

And this my inner exc.;

.{"Error getting value from 'ReadOnly' on 'NHibernate.Proxy.DefaultLazyInitializer'."}

.{"Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session."}

What should i do? I need all data... Thanks

when i check again i found something like that:

Why is there 2 base??? And why name is different? Anyone know?

Body:
I geting same error when serilize SerializeJSON(object) , i have try JsonConvert.SerializeObject with JsonSerializerSettings and ContractResolver, it will work.

string jsonResult = JsonConvert.SerializeObject(object, new JsonSerializerSettings() {
            ContractResolver = new NHibernateContractResolver()
        });


问:
How many bits is a WORD and is that constant over different architectures?
Is a machine WORD always the same or does it depend on the machine architecture?
And is the meaning of the word WORD context sensitive or generally applicable?

答:
A word is typically the "native" data size of the CPU. That is, on a 16-bit CPU, a word is 16 bits, on a 32-bit CPU, it's 32 and so on.

And the exception, of course, is x86, where a word is 16 bit wide (because x86 was originally a 16-bit CPU), a DWORD is 32-bit (because it became a 32-bit CPU), and a QWORD is 64-bit (because it now has 64-bit extensions bolted on)

OwnerDisplayName: mixedpickles

OwnerDisplayName: jalf

ContentLicense: CC BY-SA 2.5


问:
WinAPI mouse move notification for full desktop
In WinAPI is there a mouse move notification for the full desktop (full screen) and not for a window only?

I would like to receive mouse screen coordinates in my main window procedure.

Edit:

What I try to do is getting the coordinates from the mouse when dragging from a button in my window to outside that window.

答:
Not as such, no. If you wanted to do something anywhere on the desktop from within your program, e.g. point somewhere or draw something anywhere, you could capture the mouse and then follow the movement until the mouse button is released. See SetCapture for this.

For an example, see this article on MSDN: Drawing Lines with the Mouse

Otherwise you can always use Windows hooks to follow mouse movements anywhere.


问:
What I'm missing here? IsSuccessStatusCode not valid
In my code I'm trying to communicate with a php webservice.  In my Xamarin code in Csharp IsSuccessStatusCode it's invalid "'string' does not contain a definition for "isSuccessStatusCode'....  All codes i seen in the net includes this but i don't know it's not working for me.</p>

```<code>private async void GetDataAsync()
{
    //nota: para que await funcione hay que escribir en la rutina al lado de private async
    HttpClient httpClient = new HttpClient();
    var response = await httpClient.GetStringAsync("http://192.168.1.33:82/usuarios_xamarin/Usuarios.php");

    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
        var posts = JsonConvert.DeserializeObject<List<Posts>>(content);
    }
    //pertenece al nugget newtonsoft.json
    //si no esta instalado hay que instalarlo en los nuggets

    //var posts = JsonConvert.DeserializeObject<List<Posts>>(response);

}

</code>```

答:
response is a string and string doesnt have a method IsSuccessStatusCode. If you use GetAsync instead of GetStringAsync, then you can use the property (IsSuccessStatusCode) of response.

Documentation on HttpClient.GetAsync Method

Body:
In my code I'm trying to communicate with a php webservice.  In my Xamarin code in Csharp IsSuccessStatusCode it's invalid "'string' does not contain a definition for "isSuccessStatusCode'....  All codes i seen in the net includes this but i don't know it's not working for me.

private async void GetDataAsync()
{
    //nota: para que await funcione hay que escribir en la rutina al lado de private async
    HttpClient httpClient = new HttpClient();
    var response = await httpClient.GetStringAsync("http://192.168.1.33:82/usuarios_xamarin/Usuarios.php");

    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
        var posts = JsonConvert.DeserializeObject<List<Posts>>(content);
    }
    //pertenece al nugget newtonsoft.json
    //si no esta instalado hay que instalarlo en los nuggets

    //var posts = JsonConvert.DeserializeObject<List<Posts>>(response);

}


问:
Assign a value to an rvalue reference returned from function
```<code>#include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
    return std::forward<Container>(arr)[n];
}
</code>```

Make a function call :

```<code>#include <vector>
index(std::vector {1, 2, 3, 4, 5}, 2) = 0;
</code>```

When function calling finished, the object std::vector {1, 2, 3, 4, 5} will be destroyed, assigning a value to a deallocated address would cause undefined behaviour. But the above code works well and valgrind detected nothing. Maybe the compile helps me make another invisible variable like

```<code>auto &&invisible_value {index(std::vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;
</code>```

If my guess is incorrect, I want to know why assigning a value to an rvalue reference returned from function is worked and when the temporary object index(std::vector {1, 2, 3, 4, 5}, 2) will be destroyed.

This idea originated from 《Effective Modern C++》, Item3 : Understand decltype.

答: You said "When function calling finished, the object vector {1, 2, 3, 4, 5} will be destroyed" but that is untrue. The temporary created for the function call is not deleted until the statement ends, i.e. the next line of code. Otherwise imagine how much code would break that passes c_str() of a temporary string.</p>

Body:
#include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
    return std::forward<Container>(arr)[n];
}

Make a function call :

#include <vector>
index(std::vector {1, 2, 3, 4, 5}, 2) = 0;

When function calling finished, the object std::vector {1, 2, 3, 4, 5} will be destroyed, assigning a value to a deallocated address would cause undefined behaviour. But the above code works well and valgrind detected nothing. Maybe the compile helps me make another invisible variable like

auto &&invisible_value {index(std::vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;

If my guess is incorrect, I want to know why assigning a value to an rvalue reference returned from function is worked and when the temporary object index(std::vector {1, 2, 3, 4, 5}, 2) will be destroyed.

This idea originated from 《Effective Modern C++》, Item3 : Understand decltype.


问:
Grouping data by week and days
i want to regroup my data by week then by days of week . this is my code </p>

```<code>$pp=Path::join('reservations', function($join){
$join->on('reservations.path_id', '=', 'paths.id')
->where('reservations.state','=',1);})
->where('paths.user_id','=',Auth::user()->id)
->whereBetween('departure_date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
->get()
->groupBy(function($date)  {
return Carbon::parse($date->departure_date)->format('d'); // grouping by days
})->toArray();
</code>```

<p>this is my output my output
but I would like for the results to be presented like </p>

```<code>Monday => some data ..
Tuesday => some data ..
Wednesday => some data ...
</code>```

答:
use mysql DateTimeFunctions:

```<code>->groupBy(DB::raw('DAYNAME(departure_date)')
</code>```

you can use:  (DAYOFMONTH) to return the day order in month

or DAYOFWEEK to return the day order in week,
or DAYOFYEAR to return the day order in year,

and lot of option to group by day format

edit:

to add an alias:

```<code>->select('*',DB::raw('DAYNAME(departure_date) as weekDay')
    ->groupBy(DB::raw('weekDay'))->get();
</code>```

Title: Grouping data by week and days

Body:
i want to regroup my data by week then by days of week . this is my code

$pp=Path::join('reservations', function($join){
$join->on('reservations.path_id', '=', 'paths.id')
->where('reservations.state','=',1);})
->where('paths.user_id','=',Auth::user()->id)
->whereBetween('departure_date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
->get()
->groupBy(function($date)  {
return Carbon::parse($date->departure_date)->format('d'); // grouping by days
})->toArray();

this is my output my output
but I would like for the results to be presented like

Monday => some data ..
Tuesday => some data ..
Wednesday => some data ...

Body:
use mysql DateTimeFunctions:

->groupBy(DB::raw('DAYNAME(departure_date)')

you can use:  (DAYOFMONTH) to return the day order in month

or DAYOFWEEK to return the day order in week,
or DAYOFYEAR to return the day order in year,

and lot of option to group by day format

edit:

to add an alias:

->select('*',DB::raw('DAYNAME(departure_date) as weekDay')
    ->groupBy(DB::raw('weekDay'))->get();


问:
Find and replace specific text characters across a document with JS
I'm wondering if there is a lightweight way I could use JavaScript or jQuery to sniff out a specific text character across a document; say € and find all instances of this character. And then! Write an ability to replace all instances of this with say a $.

I found this snippet for starters:

```<code>var str = 'test: '';

str = str.replace(/'/g, "'");
</code>```

Essentially; I am wanting a solution for a one page document. Grab all instances of X and make it XY. Only text characters.

答:
Here is something that might help someone looking for this answer:
The following uses jquery it searches the whole document and only replaces the text.
for example if we had

```<code><a href="/i-am/123/a/overpopulation">overpopulation</a>
</code>```

and we wanted to add a span with the class overpop around the word overpopulation

```<code><a href="/i-am/123/a/overpopulation"><span class="overpop">overpopulation</span></a>
</code>```

we would run the following

```<code>        $("*:containsIN('overpopulation')").filter(
            function() {
                return $(this).find("*:contains('" + str + "')").length == 0
            }
        ).html(function(_, html) {
            if (html != 'undefined') {
                return html.replace(/(overpopulation)/gi, '<span class="overpop">$1</span>');
            }

        });
</code>```

the search is case insensitive searches the whole document and only replaces the text portions in this case we are searching for the string 'overpopulation'

```<code>    $.extend($.expr[":"], {
        "containsIN": function(elem, i, match, array) {
            return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
        }
    });
</code>```

Body:
I'm wondering if there is a lightweight way I could use JavaScript or jQuery to sniff out a specific text character across a document; say € and find all instances of this character. And then! Write an ability to replace all instances of this with say a $.

I found this snippet for starters:

var str = 'test: '';

str = str.replace(/'/g, "'");

Essentially; I am wanting a solution for a one page document. Grab all instances of X and make it XY. Only text characters.

Body:
Here is something that might help someone looking for this answer:
The following uses jquery it searches the whole document and only replaces the text.
for example if we had

<a href="/i-am/123/a/overpopulation">overpopulation</a>

and we wanted to add a span with the class overpop around the word overpopulation

<a href="/i-am/123/a/overpopulation"><span class="overpop">overpopulation</span></a>

we would run the following

        $("*:containsIN('overpopulation')").filter(
            function() {
                return $(this).find("*:contains('" + str + "')").length == 0
            }
        ).html(function(_, html) {
            if (html != 'undefined') {
                return html.replace(/(overpopulation)/gi, '<span class="overpop">$1</span>');
            }

        });

the search is case insensitive searches the whole document and only replaces the text portions in this case we are searching for the string 'overpopulation'

    $.extend($.expr[":"], {
        "containsIN": function(elem, i, match, array) {
            return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
        }
    });


问:
Bootstrap modal hide is not working
Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.

```<code><button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>

<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
  <div class="modal-bootstrap-dialog modal-sm">
    <div class="modal-bootstrap-content">
      <div class="modal-bootstrap-body">
        -- content ----
      </div>
    </div>
  </div>
  <div class="modal-bootstrap-footer">
     <button type="submit" class="button primary" data-dismiss="modal">Close</button>
     <button type="submit" class="button primary">Save changes</button>
  </div>
</div>

<script type="text/javascript">
$("#buy").click(function () {
   var a = 4;
   if (a == 5) {
     alert("if");
     $('#myModal').modal('show');
   }
   else {
    alert("else");
    $('#myModal').modal('hide');
   }

});
</script>
</code>```

bootply

答: I had same problem. Remove fade class.

Title: Bootstrap modal hide is not working

Body:
Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.

<button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>

        -- content ----

     <button type="submit" class="button primary" data-dismiss="modal">Close</button>
     <button type="submit" class="button primary">Save changes</button>

bootply

Body: I had same problem. Remove fade class.