text:
Q: YouTube API V3 activities publishedAfter / publishedBefore parameter ignored As per the docs https://developers.google.com/youtube/v3/docs/activities/list it should be possible to get activities for my homepage, and filter using the publishedAfter parameter, to get activities published after say, 10th January 2015.
However it appears that this parameter is ignored (as is publishedBefore).
I've called this from code and also from the 'try it' page https://developers.google.com/youtube/v3/docs/activities/list#try-it using:
part=id,snippet
home=true
publishedAfter=2015-01-10T00:00:00.0Z

Request:
GET https://www.googleapis.com/youtube/v3/activities?part=id%2Csnippet&home=true&publishedAfter=2015-01-10T00%3A00%3A00.0Z&key={YOUR_API_KEY}

From response JSON:
...
"publishedAt": "2015-01-12T14:47:50.000Z",
...
"publishedAt": "2015-01-06T16:24:28.000Z",
...
"publishedAt": "2015-01-07T16:36:44.000Z",
...
"publishedAt": "2015-01-12T13:26:01.000Z",
...
"publishedAt": "2015-01-07T16:19:07.000Z",
...

Some of these dates are before 2015-01-10
Not sure whether I've missed something in the docs or this is a bug. It seems to work ok for 'my' videos (mine=true) and activities for a specific channel (channelId=abc123)
I have only recently created this account / enabled 'my' channel, in case this has any effect.
UPDATE just realised there are two open issues for this:
https://code.google.com/p/gdata-issues/issues/detail?id=6088
https://code.google.com/p/gdata-issues/issues/detail?id=6366

A: I am also not so happy with how the API responds to this term and suspect it might be fussy about the timestamp format. According to the docs,  publishedAfter and publishedBefore need to be RFC 3339 formatted date-time value (1970-01-01T00:00:00Z)

A: From what I have found, it seems publishedAfter and publishedBefore is still limited:
The developer page says "Note that if the relatedToVideoId parameter is set, the only other supported parameters are part, maxResults, pageToken, regionCode, relevanceLanguage, safeSearch, type (which must be set to video), and fields."
Other pages have expert comments:

*

*"Greetings folks! There's not much we can do in this library with
bugs in backend APIs. If this is still an issue, please do file a bug
in the YouTube API issue tracker!" -JustinBeckwith, April 15,
2018, and

*"Status: Won't Fix (Obsolete)" -ma...@google.com
 Dec 22, 2016 12:08AM. (Found through the link noted above by Nick Baker).
I tested it on the API Explorer and with Google Script using apps script. Only when I use the relatedToVideoId script the publishedAfter and publishedBefore do not work. When I only query a keyword without using relatedToVideoId, then the publishedAfter and publishedBefore do work.
If you cannot get it to work with the relatedToVideoId, then you can report it in the Issue Tracker, but I think they know already. I'm hoping to find a work-around.


text:
Q: COUNT function with padded numbers I'm sorry if this has already been answered, but I haven't found it in my searches. Though, it does seem like it should be relatively simple.
I'm trying to find duplicates in a table. Some of the data in there is from a legacy database that we've integrated into this one. The rules we have now weren't enforced back then, so we're in the process of cleaning it up now.
Sadly, our project numbers are strings. Some project numbers have leading zeroes while others do not. Also some Project Numbers have letters in them.
I need to find projects which have the same root number regardless of leading zeroes. So for instance:
PROJ_NUM
021523
000345
21523
345
00345

I want it to count 2 for project 021523 and 3 for 000345.
My current code is as follows:
SELECT LPAD(PROJ_NUM, 6, '0') PROJ_NUM
       , PROJ_TYPE
       , COUNT(LPAD(PROJ_NUM, 6, '0')) COUNT
FROM TABLE
HAVING COUNT(LPAD(PROJ_NUM, 6, '0')) > 1
GROUP BY LPAD(PROJ_NUM, 6, '0'), PROJ_TYPE
ORDER BY PROJ_TYPE, PROJ_NUM

Any help would be appreciated. Thanks.
Edit: Proj_Type is necessary for this query, due to there being different project types with the same project number, which I don't want to count as duplicates.
Edit: I've discovered that part of the problem I was having involved trailing spaces with project numbers. My code as it stands is currently:
SELECT PROJ_NUM
    , PROJ_TYPE
    , CNT
FROM (
    SELECT LPAD(PROJ_NUM, 6, '0') PROJ_NUM
    , PROJ_TYPE
    , COUNT(PROJ_NUM) CNT
    FROM TABLE
    GROUP BY LPAD(PROJ_NUM, 6, '0'), PROJ_TYPE
)
WHERE CNT > 1
AND PROJ_TYPE IS NOT NULL
ORDER BY PROJ_TYPE, PROJ_NUM

A: If your project numbers are numeric, you can use TO_NUMBER() to get rid of leading zeroes.
SELECT COUNT(0), TO_NUMBER(PROJ_NUM) AS PROJ_NUM FROM TABLE GROUP BY TO_NUMBER(PROJ_NUM)

A: I would suggest that you strip out the leading zeros using ltrim():
SELECT LTRIM(PROJ_NUM, '0') as PROJ_NUM, COUNT(*) as cnt
FROM TABLE
GROUP BY LTRIM(PROJ_NUM, '0')
HAVING COUNT(*) > 1;

Nothing in your question involves the project type, so that is not included in the query.

A: I have created a SQLFiddle test case using your data and it returns the results you want.
However, I made up values for PROJ_TYPE because you didn't provide them in your sample data. I assigned each project the same Type, which is why my query works. Perhaps in your real data the "duplicate" projects have different types? If so, your query would return no rows.
Two ways of working around this. The first is obvious: remove PROJ_TYPE from the query. But if you want to see the Type too you can use a sub-query with an analytic count to get this information: note that this query returns one row per Project:
select proj_num, proj_type from (
    SELECT LPAD(PROJ_NUM, 6, '0') PROJ_NUM
           , PROJ_TYPE
           , count(*) over (partition by LPAD(PROJ_NUM, 6, '0')) cnt
    FROM t23
    )
where cnt > 1
ORDER BY proj_num, proj_type
/

This may not the solution you're looking for. If that is the case please edit your question providing a clearer explanation of the problem you're trying to solve and sufficient example data for us to reproduce it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ModuleNotFoundError: No module named '_tkinter' on macOS Tkinter doesn't work, it throws an error.
Installation
% pip3 install tk

My code
#!/usr/bin/env python3

import tkinter as tk

The Error
Traceback (most recent call last):
  File "/Users/arghadip/Library/Application Support/CodeRunner/Unsaved/Untitled.py", line 4, in <module>
    import tkinter as tk
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 37, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'

A: For Python3 tkinter can be simply installed by,
brew install python-tk

pip sometimes wont work successfully on my Mac, especially with the High Sierra OS version. Brew can be used to install all kinds of software packages in mac.

A: I was having the same issue with the module name change in Python2 to Python3.. as stated in the previous post, "brew install python-tk" worked for me. I'm running the following:

*

*Python 3.9.13 64-bit

*vsCode 1.68.0

*macOS Monterey

A: If you are in macOS, you can run the below commands to install python-tk. I have tested it on the latest macOS Ventura 13.1 and it worked like a charm.
sudo chown -R $(whoami) /usr/local/share /usr/local/share/man /usr/local/share/man/man8
chmod u+w /usr/local/share /usr/local/share/man /usr/local/share/man/man8
brew install python-tk


text:
Q: mvc dropdown option with title tag in mvc <select id="priority">
    <option value="calendar" title="icons/icon_calendar.gif">Calendar</option>
    <option value="shopping_cart" title="icons/icon_cart.gif">Shopping Cart</option>
    <option value="cd" title="icons/icon_cd.gif">CD</option>
    <option value="email"  selected="selected" title="icons/icon_email.gif">Email</option>
    <option value="faq" title="icons/icon_faq.gif">FAQ</option>
    <option value="games" title="icons/icon_games.gif">Games</option>
</select>

I want this type of drop down in mvc with title attribute
 @Html.DropDownListFor(model => model.priority, new SelectList(ViewBag.Priority, "Value", "Text"), "-- Select Priority --", new { @class = "required" })

A: The built-in DropDownList helper doesn't allow you for setting additional HTML attributes on individual options such as title. You will have to write your own custom helper if you want to achieve that. Here's one same implementation you may take a look at adapt to your needs.

A: @Html.DropDownListFor(model => model.priority, new SelectList(ViewBag.Priority, "Value", "Text"), "-- Select Priority --", new { @class = "required", title="priority" })

A: Probably you can achieve your desired output by
1.create a custom helper with with extension method which will return MvcHtmlString which will create your custom HTML for dropdown and call that method in your view.
Like Below
public static class CustomDropdown
{
public static string Dropdown(Priority priority)
      {
           StringBuilder sb=new StringBuilder ();
           sb+="<Select id='drop'>";
           for(int i=0;i<priority.name.length;i++)
       {
           sb+="<option id='dropop' value='"+priority.value[i]+"'                      title='"+priority.title[i]+"'>"+priority.name[i]+"</option>";
       }
        sb+="</select>";
              return Convert.ToString(sb);
      }
   }
 }

2.Bind the options of the given select with help of jquery like
  var i=0;
$('.drpclass option').each(function(){
$(this).attr('title',Model.priority.title[i])
i++;
});


text:
Q: disabling date in two datepicker i am using two date section for Check-in and check-out respectively. i have disabled the dates before the current date in check-in section by

how to disable the current date in check-out.
for example, today is 17-05-2016. all the dates before and including 17-05-2016 should be disabled

A: Since you don't want to use the current date, you'll likely want to create a reference for tomorrow to use to initialize your date pickers :
// Get tomorrow
var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

As far as the logic you need, you could consider updating the minDate attribute for your "check-out" picker as the value is changed within "check-in" using the onSelect() function :
// Get tomorrow
var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);
// Set up your datepickers
$( "#check-in" ).datepicker({
    minDate: tomorrow,
    onSelect: function(dateText, inst) {
        // Get the selected date
        var inDate = new Date($(this).val());
        // Set the minimum date for the check out option to the selected date
        $("#out").datepicker('option', 'minDate',inDate);
    }
});
$('#check-out').datepicker({
    minDate: tomorrow
});

Example

<!DOCTYPE html>

  <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

      Check In
      Check Out

        <input id='in' />

        <input id='out' />


text:
Q: Android IMAGE_CAPTURE returns RESULT_CANCELED I'm trying to use MediaStore.ACTION_IMAGE_CAPTURE intent to take a profile photo.
The code that starts the intent:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File myPicture = new File(OfflineApp.getAppContext().getFilesDir() + "/" + getResources().getString(R.string.contact_photos_dir), getResources().getString(R.string.my_photo_file_name));
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(myPicture));
startActivityForResult(cameraIntent, REQUEST_CODE_TAKE_PHOTO);

And the onActivityResult part:
case REQUEST_CODE_TAKE_PHOTO:
    if (resultCode == RESULT_OK) {
        String path = new File(OfflineApp.getAppContext().getFilesDir() + "/" + getResources().getString(R.string.contact_photos_dir), getResources().getString(R.string.my_photo_file_name)).getAbsolutePath();
        ContactManager.getInstance().updateMyImage(path);
    }
    break;

However, the result code is always RESULT_CANCELED, only if I provide MediaStore.EXTRA_OUTPUT, even if the file doesn't exist.

A: Since Camera Intent is launching the Camera app, it has no access to my apps file folder. Fixed it by passing an external folder file and copying it to my local folder.

A: You can let the camera app save the image in an external file like this, then use the image from there later
private void captureImage() {
    // You can pass an external file Uri to the intent to which the camera app can write
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // File file = new File(getCacheDir(), IMAGE_FILENAME); // this doesn't work as the camera app doesn't have permission to this apps cache dir
    // File file = new File("/sdcard/image.jpg"); // avoid hardcoding file names
    File file = new File(Environment.getExternalStorageDirectory(), IMAGE_FILENAME);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

    // intent.setData(Uri.fromFile(file));
    // intent.putExtra(MediaStore.EXTRA_OUTPUT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK){
        if(requestCode == REQUEST_CODE_CAPTURE_IMAGE){
            File file = new File(Environment.getExternalStorageDirectory(), IMAGE_FILENAME);
            Uri uri = Uri.fromFile(file);
            mImagePath = uri.getPath();
            String extension = MimeTypeMap.getFileExtensionFromUrl(mImagePath);
            if(extension != null){
                mImageMIMEType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            } else {
                mImageMIMEType = "image/jpg"; // fallback, also a best guess
            }
            // use image here
        }
    }
}

A: Use this File instead:
    File storageDir =  context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    try {
         File myPicture = File.createTempFile(String.valueOf(DateUtils.nowInMillis()), you_extension, storageDir);
    } catch (Exception e) {
         e.printStackTrace();
    }


text:
Q: How do I convert following raw data to zoo or xts timestamp? My raw data in a CSV-file looks like this, i.e. the date-time format is %Y%m%d, the letter "T", followed by %H%M%S:
20151230T090029, 33.04
20151230T090029, 33.06
20151230T090029, 33.07
20151230T090029, 33.05
20151230T090029, 33.04
20151230T090029, 33.05
20151230T090029, 33.04

How can I make this first column a time-index in zoo or xts?

A: Given your data as d:
> d
               V1    V2
1 20151230T090029 33.04
2 20151230T090029 33.06
3 20151230T090029 33.07
4 20151230T090029 33.05
5 20151230T090029 33.04
6 20151230T090029 33.05
7 20151230T090029 33.04

Then conversion to POSIX time classes can be done using the format string given in comments:
> as.POSIXct(d$V1,format="%Y%m%dT%H%M%S")
[1] "2015-12-30 09:00:29 GMT" "2015-12-30 09:00:29 GMT"
[3] "2015-12-30 09:00:29 GMT" "2015-12-30 09:00:29 GMT"
[5] "2015-12-30 09:00:29 GMT" "2015-12-30 09:00:29 GMT"
[7] "2015-12-30 09:00:29 GMT"

And a zoo object constructed:
> zoo(d$V2, as.POSIXct(d$V1,format="%Y%m%dT%H%M%S"))
2015-12-30 09:00:29 2015-12-30 09:00:29 2015-12-30 09:00:29 2015-12-30 09:00:29
              33.04               33.06               33.07               33.05
2015-12-30 09:00:29 2015-12-30 09:00:29 2015-12-30 09:00:29
              33.04               33.05               33.04
Warning message:
In zoo(d$V2, as.POSIXct(d$V1, format = "%Y%m%dT%H%M%S")) :
  some methods for "zoo" objects do not work if the index entries in 'order.by' are not unique

with that warning because all the time points are the same.

A: As Josh O'Brien suggested, you can do this with read.zoo:
library(zoo)
Lines <- "20151230T090029, 33.04
20151230T090029, 33.06
20151230T090029, 33.07
20151230T090029, 33.05
20151230T090029, 33.04
20151230T090029, 33.05
20151230T090029, 33.04"
z <- read.zoo(text=Lines, sep=",", FUN=as.POSIXct, format="%Y%m%dT%H%M%S")

Then you could deal with the identical timestamp issue Gabor mentioned by converting to xts and using xts::make.index.unique.
library(xts)
x <- as.xts(z)
options(digits.secs=3)
(u <- make.index.unique(x, 0.001))
#                          [,1]
# 2015-12-30 09:00:29.000 33.04
# 2015-12-30 09:00:29.000 33.06
# 2015-12-30 09:00:29.001 33.07
# 2015-12-30 09:00:29.002 33.05
# 2015-12-30 09:00:29.003 33.04
# 2015-12-30 09:00:29.004 33.05
# 2015-12-30 09:00:29.005 33.04

See How R formats POSIXct with fractional seconds for why the fractional seconds print in a way that makes them look incorrect.


text:
Q: How do I save in Grand Theft Auto 5? I'm a new gamer and don't play much. I started playing yesterday and I get to a point where I finish robbing the bank and then killing the cops to get in the car that crosses the train. After the prologue I take control of Franklin who is with Lamar. I then steal a car and chase Lamar. I never finish that part but then next time it starts all over again.
How do I save it so I can start from where I steal the car and not robbing the bank?

A: You save the game by either sleeping in a bed in one of the character's safe houses, or selecting the "Quick Save" option on the your mobile phone (neither are available IIRC while in a mission).
To bring up your character's phone, press the Up button on the D-Pad. The Quick Save icon is the one in the left column of the middle row.


text:
Q: How to test the below api in test class? I have the controller class like the below with the method I need to test:
@RestController
@RequestMapping(value = "/v1/offers")
public class OffersControllerV1 {

    private static final Logger logger = LoggerFactory.getLogger(OffersControllerV1.class);

    // ...

    @GetMapping("/all")
    public ResponseEntity<ApiResponse> getAllNewOffers(Pageable pageable) {
        List<OfferResponseInfo> offersList = null;
        ApiResponse response = null;
        try {
             offersList = offerFinderService.getAllNewOffers(pageable);
             response = ApiResponse.ofSuccess(offersList, "All offers fetched successfully");
        }catch(Exception e) {
            response = ApiResponse.ofFailure("Failed to fetch offers. Please try again");
        }
        return new ResponseEntity<>(response, HttpStatus.valueOf(response.getCode()));
    }

}

The test case for the controller class is as below. I am trying to test method getAllNewOffers but getting response status 404. Also I am trying to invoke configuration class but it is never invoked.
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {PageableConfig.class, SortParamConfig.class})
public class OffersControllerV1Test {

   protected MockMvc mvc;

   @Autowired
   WebApplicationContext webApplicationContext;

   @Before
   public void setUp() {
        MockitoAnnotations.initMocks(this);
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   }

   @Test
   public void evaluatesValidSortParameters_getAllNewOffers() throws Exception {
        int status = mvc.perform(MockMvcRequestBuilders.get("/v1/offers/all")
                .param("page", "5")
                .param("size", "10")
                .param("sort", "publishedDate,asc")
                .param("sort", "createdDate,desc"))
                .andReturn().getResponse().getStatus();

        ArgumentCaptor<Pageable> pageableCaptor = ArgumentCaptor.forClass(Pageable.class);
        verify(offerFinderService).getAllNewOffers(pageableCaptor.capture());
        PageRequest pageable = (PageRequest) pageableCaptor.getValue();

        assertEquals(5, pageable.getPageNumber());
        assertEquals(10, pageable.getPageSize());
    }
}

A: I have sorted it out. I was missing @WebMvcTest(controllers = controller.class)
@AutoConfigureMockMvc(addFilters = false) annotations.


text:
Q: Spring 3+ How to create a TestSuite when JUnit is not recognizing it I'm using Spring 3.0.4 and JUnit 4.5. My test classes currently uses Spring's annotation test support with the following syntax:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration (locations = { "classpath:configTest.xml" })
@TransactionConfiguration (transactionManager = "txManager", defaultRollback = true)
@Transactional
public class MyAppTest extends TestCase

{
 @Autowired
 @Qualifier("myAppDAO")
 private IAppDao appDAO;
    ...
}

I don't really need the line extends TestCase to run this test. It's not needed when running this test class by itself. I had to add extends TestCase so that I can add it in a TestSuite class:
public static Test suite() {
        TestSuite suite = new TestSuite("Test for app.dao");
  //$JUnit-BEGIN$
  suite.addTestSuite(MyAppTest.class);
        ...

If I omit the extends TestCase, my Test Suite will not run. Eclipse will flag suite.addTestSuite(MyAppTest.class) as error.
How do I add a Spring 3+ test class to a Test Suite? I'm sure there's a better way. I've GOOGLED and read the docs. If you don't believe me, I'm willing to send you all my bookmarks as proof. But in any case, I would prefer a constructive answer. Thanks a lot.

A: You are right; JUnit4-style tests should not extend junit.framework.TestCase
You can include a JUnit4 test as part of a JUnit3 suite this way:
public static Test suite() {
   return new JUnit4TestAdapter(MyAppTest.class);
}

Usually you would add this method to the MyAppTest class. You could then add this test to your larger suite:
 public class AllTests {
   public static Test suite() {
     TestSuite suite = new TestSuite("AllTests");
     suite.addTest(MyAppTest.suite());
     ...
     return suite;
   }
}

You can create a JUnit4-style suite by creating a class annotated with Suite
@RunWith(Suite.class)
@SuiteClasses( { AccountTest.class, MyAppTest.class })
public class SpringTests {}

Note that AccountTest could be a JUnit4-style test or a JUnit3-style test.


text:
Q: Existence of solution to $tx'(t)=x(t)-1$ by Picard's existence theorem Given the ODE:
$$
\left\{
\begin{array}
ttx'(t)=x(t)-1 \\
x(0)=1
\end{array}
\right.
$$
I have found that there are infinitely many solutions to the equation: $x(t)=Ct+1, C \in \Bbb R$.
I am wondering how does it agree with Picard's existence theorem.
If I write $x'(t)=f(t,x(t)) \;$ where $\; f(t,x)=\frac{x-1}{t}$, then $f$ is not continuous in $0$. Can I conclude the theorem doesn't work in the other direction?


text:
Q: How can I use seperate name, rather than my nickname in IRC? I am relatively unfamiliar with how IRC works. I have had a registered nickname with freenode for a couple years and I have only used it a couple times.
What I'd like to do is use a simple name when I visit a private chat room set up for a small business with only a few people.
Lets say my registered name is 'longname16' and the name I want to use for this small private freenode chat room is the name 'me1' Is this possible? I want to retain my long registered name but use a simple one as a nickname.

A: You can use the short name if you want (as long as someone else hasn't registered it) simply by issuing /nick me1. Note that nicknames are global in IRC, though, so if you are in any other channels this will also change your nickname there. You can just use /nick longname16 to go back to your registered name, although depending on how FreeNode's services are configured, you may need to /msg nickserv identify <password> again. Note that if the short nick you want to use is already registered by someone else, you won't be able to use it. But unregistered nicks are fair game for anyone that wants to use them.
Basically, the thing to understand, is that registered nicks in IRC are not like an account on a website - you don't need to "sign in" to a nick. Anyone chooses whatever nick they want, and you don't have a specific nick that belongs to you, you can use whatever you want (as long as someone else currently in the server isn't using it, since nicks need to be unique at any given time). Thing is, most people will choose the same nick over and over (so that everyone else will know who they are), and it's annoying if you join the server and someone's using the nick that you always use. So many IRC servers provide nick registration as a convenience, so that if you always use the same nick and you don't want someone else to use it, you can set a password on it to make sure it's always available for you and no one else can use it to pretend to be you. It's not something you have to do in order to "log in" to the IRC server.
On the other hand, note that there are some channels that require you to have registered your nick in order to join. This is just a simple method to avoid trolls, since the extra command it takes to register a nick will deter a surprising number of people. These aren't very common, though.


text:
Q: Outlook Web App / OWA dosent meet the security policy Im having big time trouble accessing a Outlook Web App / OWA page on one computer. Accessing the website gives me most of the time the following error.

I do not have access to the OWA / Exchange configuration but i think this may be a client problem because i have a second pc where it works fine. Using differen browsers show me java applett error and that i should install/update java.
PC where it does not work:

*

*up to date internet explorer 11

*64 bit windows 7

PC where its works:

*

*up to date internet explorer 11

*64 bit windows 8

What i tested:

*

*checked internet setting / compare them to the pc where it works

*resetted internet settings

*cleared internet cache / cookies

*resetting internet explorer

*added owa site to trusted sites

*update java

*reinstall java

*java security settings changed

*enhanced protection mode is not enabled

*compare the advanced setting between the clients - no difference in configuration

Any idea how to solve this?

A: Its not a good solution but when you set the internet explorer to delete all temp files, history and cookies on every programm close it works fine.
So my guess is that when you access the webapp  it will create some local stored file that seems to be somehow corrupt.


text:
Q: Enable IndentGuide Eclipse plugin in java files To install indentation in Eclipse I dropped this IndentGuide jar in the dropins folder (I couldn't install it in the "Install Software..." option as it's not available any longer).
I restarted Eclipse and I see the IndentGuide customization screen, but java does not show in available content types:

The indentation works fine in text extensions, but does not work for java. I looked at the eclipse/configuration folder but couldn't find anything. Any ideas?
UPDATE
This is what I see under Text > Java:

A: Update preferences to make it work with Java files


text:
Q: Is dynamic behavior addition the only advantage of using the Decorator pattern? I am studying Decorator design pattern at the moment and this thinking bother me a lot.
Would it be easier just to have one base class with boolean value corresponding to its feature?
For example:
The textview, can have vertical scroll, horizontal scroll, border, etc. if the textview base class has the BOOL for canVerScroll, canHorScroll, hasBorder; why is this not better than Decorator design pattern?
Thanks for helping!

A:
Would it be easier just to have one base class with boolean value corresponding to its feature?

This would violate a SOLID principle called the Open-Closed principle. The Open-Closed principle states that components should be open to extension but closed to modification. If you have a single TextView class, it will need to be changed every-time you want to introduce a new behavior in your text-view.

why is this not better than Decorator design pattern?

Imagine that users of your API (who don't have access to your API source code) want to introduce a new behavior for the TextView class called Rotate 360 degrees. They have two options here, either wait for you to add a new BOOL to the TextView base class and support this functionality or figure out a way to buid this functionality on top of your TextView. One option they could go with is to create a TextViewAdapter (read Adapter pattern) that will allow them to add the required functionality over and above the functionality that you provided.
Wouldn't it be better if you provided the ability to extend your API out of the box rather than creating an API that is not extensible without your intervention?


text:
Q: "iPod Developer Teams"
Possible Duplicate:
Test iOS app on device without apple developer program or jailbreak
XCode - IPhone Development Teams

I cannot compile my iPad app to an iPad (I can only use the simulator). When I try to authorize my iPad for development, I log in with my Apple ID and then get the message, "the indicated user is not on any iphone development teams." I'm having trouble figuring out just what team I am supposed to belong to. Is it talking about the signing up for a full-fledged developer account? Is it really the case that I cannot even test an app on my own iPad without paying? Or is it referring to something else?
Thanks!

A: Yes, it's really the case that you can't test your app on your own iPad without paying.

A: Without jailbreaking your device, you'll need to sign up for a [paid] developer subscription.
See also: Test iOS app on device without apple developer program or jailbreak


text:
Q: How to save any object which is declared as a class variable and initialized inside a test in JUnit I am designing test cases in JUnit. My question is how to save any object which is declared as a class variable and initialized inside a test. Currently in such cases I am getting java.lang.NullPointerException.
Below is the brief description-
I have three services listed below which needs to be tested-

*

*Service 1(login): It accept a username password pair and returns
cookies in response.

*Service 2(postmessage): It accept a message,
which must be supplied with cookies in the request and returns an
unique id of posted message

*Service 3(markasread): It accept a
message id, which must be supplied with cookies. The message id,
which should be used in Service 3 is returned by service 2.

This is what I was expecting to work-
import static org.junit.Assert.*;
import org.junit.Test;

public class ProfileTest{
    private String cookie;
    private String messageId;

    @Test
    public void loginTest(){
        String username = "demouser";
        String password = "demopassword";

        HttpResponse response = login(username, password);
        cookie = response.getCookie();

        assertEquals(response.getResponse(), "success");
    }

    @Test
    public void postmessageTest(){
        String message = "Hi, this is test message";
        HttpResponse response = postmessage(message, cookie);
        messageId = response.getCookie();

        assertEquals(response.getResponse(), "success");
    }

    @Test
    public void markasreadTest(){
        HttpResponse response = markasread(messageId, cookie);

        assertEquals(response.getResponse(), "success");
    }
}

A: The answer is you cannot and you should not it. Each run of test cases will have its own copy of class variables. The idea behind this is just that each test case should run independently and should not depend on each other.
It may be possible through some junk code but I really don't have such a recommendation for you.
If possible then try to club the tescases together and run as a single one.

A: The reason you can't do it is the BlockJUnit4ClassRunner creates a new instance of the test class per leaf method. It constructs the test class with the default constructor.
BlockJUnit4ClassRunner
The relevant code is

protected Object createTest() throws Exception {
    return getTestClass().getOnlyConstructor().newInstance();
}


text:
Q: how to use Gmail smtp in iOS app I am new to Xcode I need an app to send a email. Background: the destination email Id is typed in a text and by clicking the send button the message body Sample should go to the destination Email ID I tried this code in the function button clicked but it is not working when ever i try this code I get error in function can any one guide me with a step by step tutorial
mailTransfer[673:207] delegate - error(-5): timeout sending message
                2014-07-05 10:54:05.393 mailTransfer[673:207] * stopping watchdog * I had added the SMTP files from google documents ... any other way to correct this code
     - (IBAction)sendMessageInBack:(id)anObject
    {

                        SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
                        testMsg.fromEmail = @"Yours mail ids";
                        testMsg.toEmail = emailField.text;
                        testMsg.relayHost = @"smtp.gmail.com";
                        testMsg.requiresAuth = YES;
                        testMsg.login = @"Your mail ids";
                        testMsg.pass = @"id password";
                        testMsg.subject = @"Test application ";
                        testMsg.wantsSecure = YES;
                        testMsg.delegate = self;
                        NSDictionary *plainPart = [NSDictionarydictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,@"Sample",kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
                        testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
                        [testMsg send];
    }
    -(void)messageSent:(SKPSMTPMessage *)message{
        [message release];
        NSLog(@"delegate - message sent");
    }
    -(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
        [message release];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Unable to send email" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
        NSLog(@"delegate - error(%d): %@", [error code], [error localizedDescription]);
    }

A: in SKPSMTPMessage.m
update the following line
CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);

with
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);

A: Download SMTP framework and import SKPSMTPMessage class..
#import "SKPSMTPMessage.h"
-(void)sendEmailVideo:(NSString*)_toEmailAddress andCC:(NSString*)ccEmail

{
@try
    {

    // Message =[data getContentOfPanic];

    NSData *webData = [NSData dataWithContentsOfURL:videoURL];
    SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
    emailMessage.fromEmail=@"nikki.varsha@gmail.com";//sender email address

    emailMessage.toEmail=_toEmailAddress;
    //receiver email address
    emailMessage.relayHost=@"smtp.gmail.com";
    //emailMessage.ccEmail =ccEmail;
    emailMessage.requiresAuth = YES;
    emailMessage.login = @"nikki.varsha@gmail.com"; //sender email address
    emailMessage.pass = @"123";
    //sender email password
    emailMessage.subject =@"Panic Video Message";
    emailMessage.wantsSecure = YES;
    emailMessage.delegate = self;
    NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,
                               Message,kSKPSMTPPartMessageKey,@"8bit",  kSKPSMTPPartContentTransferEncodingKey,nil];

    NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"Video.mov\"",kSKPSMTPPartContentTypeKey,
                             @"attachment;\r\n\tfilename=\"Video.mov\"",kSKPSMTPPartContentDispositionKey,[webData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];

    emailMessage.parts=[NSArray arrayWithObjects:plainPart,vcfPart,nil];
    dispatch_queue_t backgroundVideoQueue = dispatch_queue_create("com.VideoQue", 0);

    dispatch_sync(backgroundVideoQueue, ^{
        [emailMessage send];
    });
}
@catch (NSException *exception)
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Host" message:@"No Reciever Email Ids Available! " delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert show];
}
}

pragma mark - sendEmail delegate (SKPSMTPMessage)
-(void)messageSent:(SKPSMTPMessage *)message
{
NSLog(@"delegate - Email sent");
NSLog(@"Mesg %@",message);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Email sent." message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];

}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"err=%@" ,message);
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Error"
                      message:@"Unable to send email Please Check EmailId & Password"
                      delegate:self
                      cancelButtonTitle:@"OK"
                      otherButtonTitles: nil];
[alert show];
});

}

A: in SKPSMTPMessage.m file do change the following line
Remove this line
//CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);

Add this line
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);

Thanks


text:
Q: Cleaning up a messy Chart.js line chart result I have the following chart using Chart.js.

As you can see the result is incredibly messy.
How would I go about cleaning this up?

I've tried stepSize in the x axis but it didn't do anything.

var ctx = $("#chart");

   var myLineChart = new Chart(ctx, {
    type: 'line',

       data: {
     datasets:
     [
      {
       backgroundColor: '#27ae60',
       borderColor: '#27ae60',
       data: [
        {x:'2018-04-06 09:09:09.655699',y:167.96},{x:'2018-04-06 09:11:54.471139',y:177.35},{x:'2018-04-06 10:05:54.898945',y:173.22},{x:'2018-04-06 10:08:55.355812',y:177.30},{x:'2018-04-06 10:12:11.805191',y:180.15},{x:'2018-04-06 10:13:19.715115',y:179.14},{x:'2018-04-06 10:15:05.644111',y:176.00},{x:'2018-04-06 10:46:13.565495',y:156.05},{x:'2018-04-06 11:02:45.523708',y:180.08},{x:'2018-04-06 11:03:33.727033',y:180.56},{x:'2018-04-06 11:04:35.171490',y:179.14},{x:'2018-04-06 11:45:58.156544',y:181.19},{x:'2018-04-06 11:50:39.120997',y:180.23},{x:'2018-04-06 11:51:55.661541',y:180.57},{x:'2018-04-06 11:54:04.882602',y:181.16},{x:'2018-04-06 11:55:00.040104',y:180.06},{x:'2018-04-06 11:56:33.241252',y:180.55},{x:'2018-04-06 11:59:20.307318',y:179.14},{x:'2018-04-06 12:01:40.442655',y:180.57},{x:'2018-04-06 12:05:46.062293',y:180.93},{x:'2018-04-06 12:30:20.836871',y:179.17},{x:'2018-04-06 13:00:21.519024',y:180.04},{x:'2018-04-06 13:30:19.546782',y:180.25},{x:'2018-04-06 14:00:22.271000',y:180.59},{x:'2018-04-06 14:30:21.328425',y:180.60},{x:'2018-04-06 15:00:26.159340',y:180.17},{x:'2018-04-06 15:30:24.866116',y:181.00},{x:'2018-04-06 16:00:24.717159',y:181.03},{x:'2018-04-06 16:30:19.425427',y:181.17},{x:'2018-04-06 17:00:23.965748',y:181.17},{x:'2018-04-06 17:30:21.966713',y:180.22},{x:'2018-04-06 18:00:24.467742',y:180.55},{x:'2018-04-06 18:30:19.554409',y:180.09}       ],
       fill: false,
      },
      {
       backgroundColor: '#2980b9',
       borderColor: '#2980b9',
       data: [
        {x:'2018-04-06 09:09:09.655699',y:182.11},{x:'2018-04-06 09:11:54.471139',y:180.95},{x:'2018-04-06 10:05:54.898945',y:183.27},{x:'2018-04-06 10:08:55.355812',y:182.44},{x:'2018-04-06 10:12:11.805191',y:183.12},{x:'2018-04-06 10:13:19.715115',y:183.14},{x:'2018-04-06 10:15:05.644111',y:182.87},{x:'2018-04-06 10:46:13.565495',y:181.60},{x:'2018-04-06 11:02:45.523708',y:183.19},{x:'2018-04-06 11:03:33.727033',y:182.84},{x:'2018-04-06 11:04:35.171490',y:182.77},{x:'2018-04-06 11:45:58.156544',y:182.47},{x:'2018-04-06 11:50:39.120997',y:182.23},{x:'2018-04-06 11:51:55.661541',y:181.48},{x:'2018-04-06 11:54:04.882602',y:183.43},{x:'2018-04-06 11:55:00.040104',y:183.20},{x:'2018-04-06 11:56:33.241252',y:182.88},{x:'2018-04-06 11:59:20.307318',y:181.19},{x:'2018-04-06 12:01:40.442655',y:182.04},{x:'2018-04-06 12:05:46.062293',y:182.18},{x:'2018-04-06 12:30:20.836871',y:182.82},{x:'2018-04-06 13:00:21.519024',y:182.27},{x:'2018-04-06 13:30:19.546782',y:183.40},{x:'2018-04-06 14:00:22.271000',y:181.61},{x:'2018-04-06 14:30:21.328425',y:182.89},{x:'2018-04-06 15:00:26.159340',y:182.87},{x:'2018-04-06 15:30:24.866116',y:182.99},{x:'2018-04-06 16:00:24.717159',y:182.86},{x:'2018-04-06 16:30:19.425427',y:182.88},{x:'2018-04-06 17:00:23.965748',y:181.96},{x:'2018-04-06 17:30:21.966713',y:181.87},{x:'2018-04-06 18:00:24.467742',y:182.90},{x:'2018-04-06 18:30:19.554409',y:183.07}       ],
       fill: false,
      }
     ]
    },

    options: {
        responsive: false,
        maintainAspectRatio: false,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:false
                }
            }],
            xAxes: [{
                   type: 'time',
       time: {
        parser: 'YYYY-MM-DD HH:mm:ss',
        unit: 'minute',
        displayFormats: {
                           'minute': 'HH:mm',
         'hour': 'HH:mm'
                          }
       },
       ticks: {
        source: 'data'
       }
               }]
        }
    }

   });
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/locale/af.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
</head>
<body>
<canvas id="chart" width="800" height="450"></canvas>
</body>
</html


text:
Q: Why does adding an index on a column containing a char version of a UUID decrease performance? I have a table with 3.5 million rows containing UUIDs in their ascii representation (so 36 chars) and an integer amount.
I need to SUM all amounts grouping by UUID, so the query is very simple:
SELECT uuid, SUM(amount) FROM table GROUP BY uuid;

results:

*

*with an index on uuid: Time: 68.074s

*without an index: Time: 8.188s

execution plan with index:
| id | select_type | table  | type  | possible_keys    | key      | key_len | ref    | rows    | Extra  |
+----+-------------+-----------------------------+-------+------------------+------------------+---------+
| 1  | SIMPLE      | amount | index | uuid_idx         | uuid_idx | 110     | <null> | 3424833 | <null> |
+----+-------------+-----------------------------+-------+------------------+------------------+---------+

execution plan without index:
| id | select_type | table  | type | possible_keys | key    | key_len | ref    | rows    | Extra                           |
+----+-------------+-----------------------------+------+---------------+--------+---------+--------+---------+-------------
| 1  | SIMPLE      | amount | ALL  | <null>        | <null> | <null>  | <null> | 3424833 | Using temporary; Using filesort |
+----+-------------+-----------------------------+------+---------------+--------+---------+--------+---------+-------------

Am I missing something or does an index on that column really dramatically decrease performance on that kind of query?

A: The EXPLAINs show that, with the index, it used the index.  That lead to jumping around:  Pick the next alphabetical UUID, reach into the table in random location for the rows to find the amounts to SUM up.
Without the index, it simply plowed through straight through the table, collecting data, then sorting in order to finish the task.
3.5M random lookups apparently takes longer than sorthing 3.5M rows.
Converging the UUID to BINARY(16) would shrink it, thereby helping a little.
Having INDEX(uuid, amount) would significantly speed up this query.  But still, the random nature of uuids is a performance drag.
Some related discussion:  http://mysql.rjweb.org/doc.php/uuid


text:
Q: How could Dr. Willett unsummon this creature in The Case of Charles Dexter Ward? In Lovecraft's The Case of Charles Dexter Ward, the phrase "do not call up any that you can not put down" is oft repeated.

... doe not call up Any that you can not put downe; by the Which I meane, Any that can in Turne call up Somewhat against you, whereby your Powerfullest Devices may not be of use. Ask of the Lesser, lest the Greater shal not wish to Answer, and shal commande more than you.

The contradiction:

 Joseph Curwen was a very powerful necromancer; his spell against his descendant transcended time, and he even summoned Yog-Sothoth thrice. He was killed by a monster that he had raised but not managed to put down.

Still,

 Dr. Willett, who knew nothing of necromancy and just happened to stumble upon the words of the unsummoning incantation, managed to put Curwen down. The latter wasn't even caught flat-footed.

Did I miss something, or was the doctor just very lucky?

A: Curwen wasn't killed by something he called up. The warning "Do not call up..." I think means that you shouldn't call up someone from "essential saltes" that would be hostile to you and immediately prevent you from controlling him. I would assume that anyone so called would be a little disoriented at first, so you could be prepared to put down any subject that wasn't cooperative or responsive to your threats.
And yes, Curwen was put down by Dr. Willett using the "descending node" of the spell.

A: It seems to me that any necromancer who was called up from the saltes MIGHT be able to somehow silence the words of the descending node of the spell if He/She/It had the power or the will to conquer the caster.  I would guess that Ward had such knowledge but did not expect or resist the Dr. precisely Because the Doctor was not a necromancer, so he should not have known how to put Ward downe.

A: Without looking back to my book, I don't believe Curwen was unsummoned. He was simply transformed to dust. Something that is possible to be done to humans.


text:
Q: Split a string according to a regexp in VBScript I would like to split a string into an array according to a regular expression similar to what can be done with preg_split in PHP or VBScript Split function but with a regex in place of delimiter.
Using VBScript Regexp object, I can execute a regex but it returns the matches (so I get a collection of my splitters... that's not what I want)
Is there a way to do so ?
Thank you

A: If you can reserve a special delimiter string, i.e. a string that you can choose that will never be a part of the real input string (perhaps something like "#@#"), then you can use regex replacement to replace all matches of your pattern to "#@#", and then split on "#@#".
Another possibility is to use a capturing group. If your delimiter regex is, say, \d+, then you search for (.*?)\d+, and then extract what the group captured in each match (see before and after on rubular.com).

A: You can alway use the returned array of matches as input to the split function. You split the original string using the first match - the first part of the string is the first split, then split the remainder of the string (minus the first part and the first match)... continue until done.

A: I wrote this for my use. Might be what you're looking for.
Function RegSplit(szPattern, szStr)
Dim oAl, oRe, oMatches
Set oRe = New RegExp
oRe.Pattern = "^(.*)(" & szPattern & ")(.*)$"
oRe.IgnoreCase = True
oRe.Global = True
Set oAl = CreateObject("System.Collections.ArrayList")

Do
    Set oMatches = oRe.Execute(szStr)
    If oMatches.Count > 0 Then
        oAl.Add oMatches(0).SubMatches(2)
        szStr = oMatches(0).SubMatches(0)
    Else
        oAl.Add szStr
        Exit Do
    End If
Loop
oAl.Reverse
RegSplit = oAl.ToArray
End Function
'**************************************************************
Dim A
A = RegSplit("[,|;|#]", "bob,;joe;tony#bill")
WScript.Echo Join(A, vbCrLf)

Returns:
bob

joe
tony
bill

A: I think you can achieve this by using Execute to match on the required splitter string, but capturing all the preceding characters (after the previous match) as a group. Here is some code that could do what you want.
'// Function splits a string on matches
'// against a given string
Function SplitText(strInput,sFind)
    Dim ArrOut()

    '// Don't do anything if no string to be found
    If len(sFind) = 0 then
        redim ArrOut(0)
        ArrOut(0) = strInput
        SplitText = ArrOut
        Exit Function
    end If

    '// Define regexp
    Dim re
    Set re = New RegExp

    '// Pattern to be found - i.e. the given
    '// match or the end of the string, preceded
    '// by any number of characters
    re.Pattern="(.*?)(?:" & sFind & "|$)"
    re.IgnoreCase = True
    re.Global = True

    '// find all the matches >> match collection
    Dim oMatches: Set oMatches = re.Execute( strInput )

    '// Prepare to process
    Dim oMatch
    Dim ix
    Dim iMax

    '// Initialize the output array
    iMax = oMatches.Count - 1
    redim arrOut( iMax)

    '// Process each match
    For ix = 0 to iMax

        '// get the match
        Set oMatch = oMatches(ix)

        '// Get the captured string that precedes the match
        arrOut( ix ) = oMatch.SubMatches(0)

    Next

    Set re = nothing

    '// Check if the last entry was empty - this
    '// removes one entry if the string ended on a match
    if arrOut(iMax) = "" then Redim Preserve ArrOut(iMax-1)

    '// Return the processed output
    SplitText = arrOut

End Function


text:
Q: Bill calculation (very simple math question) I hope this question isn't too simple! If it is, let me know if I should post it elsewhere, thank you. (Also, I didn't know what to tag it with, sorry!)
My wife and I live with my brother-in-law Bob, and, for 30% of the time, also live with Bob's three children.
Our last gas bill was for $161.21 for 45 days.
This is how we work Bob's share of the bill. It seems right but I'm sure there are much simpler ways.
Is this correct?
Is there a more efficient way? (I'm sure there is!)

*

*Total cost (a) divided by number of days (b) = cost per day (c)
            e.g. $161.21/ 45days = $3.58 per day

            c = a/b

*Then calculate how many days the children were here (30%) (y)
            e.g. 30% of 45days = 13.5days

            y = b/100 X 30

*Then calculate how many days the children are not here (z)
            e.g. 45 – 13.5 = 31.5

            z = b - y

*Then find out how much it costs for the amount of days the children are here (d)
            e.g. 13.5 x $3.58 = $48.33

            d = y X c

*Then find out how much per person and times by 4 (Bob + 3 children) (e)
            e.g. ($48.33/ 6 = $8.055) x 4 = $32.22

            e = (d/6) X 4

*Then find out how much Bob owes for the remaining time (f)
            e.g. (31.5 x $3.58 = $112.77) / 3 = $37.59

            f = (z X c) / 3

*Finally, add (e) plus (f):

$32.22 + $37.59 = $69.81

*

*x = e + f
            or:

*x = ((d/6) X 4) + ((z X c) / 3)
            or:

*x = (((y X c)/6) X 4) + (((b - y) X c) / 3)
            or:

*x = ((((b/100 X 30) X c)/6) X 4) + (((b - (b/100 X 30)) X c) / 3)
            or:

*x = ((((b/100 X 30) X (a/b))/6) X 4) + (((b – (b/100 X 30)) X (a/b)) / 3)
            Where:

            a = total cost

            b = number of days

A: The easiest way, if you wish to distribute equitably, is to compute the number of person-days in the month.
If you, your wife, and Bob all live there 100% of the time, for 45 days in a billing period, that's 135 person-days. If his three kids are there for 14 days each in the billing period, that's another 42 person-days.
Thus, the bill is going to be $\frac{\$161.21}{135+42} = \frac{\$161.21}{177} = \$0.911$ per person-day.
Then, Bob can be attributed 45+42 = 87 person-days.
So his share of the bill is $87 \cdot \$0.911 = \$79.24$.
Edit: updated to reflect 45 day billing period

This process is a standard management/accounting practice. If you've ever done project management, you've almost certainly had to estimate "man-months" or "man-hours". This is the same idea.
When you're computing your bill, if you're a bachelor, you might only be concerned with "dollars per day." Once you start living with more people, then it might be sensible to start looking at "dollars per person per day" or "dollars per day per person". Are these two quantities different? How can we find out?
It turns out that units can be manipulated mathematically through multiplication and division: if you walk 5 meters per 10 seconds, you walk $\frac{5 \textrm{meters}}{10 \textrm{seconds}} = \frac12 \textrm{m/s}$. If you do that for 100 seconds, you multiply:
$$\require{cancel}
\frac12 \frac{\textrm{meters}}{\cancel{\textrm{seconds}}} \cdot 100 \cancel{\textrm{seconds}} = 50 \textrm{meters}.$$
In your example, if you compute "dollars per person per day", you have
$$\frac{\left(\frac{161.21 \textrm{ dollars}}{N \textrm{ people}}\right)}{45 \textrm{ days}} = \frac{161.21 \textrm{ dollars}}{45N \textrm{ people}\cdot \textrm{days}}.$$
Otherwise, if you compute "dollars per day per person", you have
$$\frac{\left(\frac{161.21 \textrm{ dollars}}{45 \textrm{ days}}\right)}{45 \textrm{ people}} = \frac{161.21 \textrm{ dollars}}{45N \textrm{ people}\cdot \textrm{days}}.$$
These quantities are the same.
Your only challenge is to compute $N$ -- the number of people. Since each kid is only there 30% of the time, they only effectively count as 30% of a person. So your $N$ can be computed as
$$N = 1_{\textrm{you}} + 1_{\textrm{wife}} + 1_{\textrm{Bob}} + 3\cdot 0.3_{\textrm{kid}} = 3.9$$
Then, now that you can compute "dollars per person-day", you multiply it by each party's attributable person-days: 87 for Bob, 90 for you and your wife. And bam, you get your bill.
(One side note: in my earlier example, I rounded the number of days of kids up to an integer. In this example, 45*0.3 is not an integer number of days, so the result will be different by a handful of cents).


text:
Q: I have a repeating result in a column, even though I have rules set against it. How can I remove this repeated occurance? The Program problem is this:
Friendly Numbers:
There are certain pairs of numbers that are known as 'friendly numbers'. By definition, friendly numbers are two distinct numbers, the sum of whose proper divisors equals the other number.
For example: The smallest pair of friendly numbers are 220 and 284.  The proper divisors of 220 are: 1,2,4,5,10,11,20,22,24,44,55, and 110. The sum of these divisors is 284.
On the other hand, the proper divisors of 284 are: 1,2,4,71, and 142.  The sum of these divisors is 220.
Therefore, 220 and 284 are called 'friendly numbers'.  Write a program to find and print the first two dozen pair of friendly numbers.
The list of friendly numbers can be found here. I am trying to get to 80620 and 389924.
My source code is here:
program  Friendly Numbers;

type List=Array[1..50] of Integer;

var Num,Sum,Sum2,C,C2,C3,C4,CheckNum,LastNum:Integer;
    NumUsed:String;
    CheckedNum,CheckedSum:List;

begin
Num:=200;

while C3<=23 Do
  begin

    while C<Num Do
      begin
        C:=C+1;
        if (C<>Num) and (Num mod C=0) then Sum:=Sum+C;
      end;

    while C2<Sum Do
      begin
        C2:=C2+1;
        if (C2<>Sum) and (Sum mod C2=0) then Sum2:=Sum2+C2;
      end;

    if Num=Sum2 then
      begin

        for C4:=1 to 35 do
          begin
            if CheckedNum[C4]=C2 then NumUsed:='T';
            if CheckedSum[C4]=Num then NumUsed:='T';
          end;

        if (C2<>LastNum) and (NumUsed<>'T') and (Num<>C2) then
          begin
            C3:=C3+1;
            Writeln(C3,')',Num:8,C2:8);
            LastNum:=Num;
          end;

      Checknum:=CheckNum+1;
      CheckedNum[CheckNum]:=Num;
      CheckedSum[CheckNum]:=C2;
    end;

  NumUsed:='F';
  Num:=Num+1;
  Sum:=0;
  Sum2:=0;
  C:=0;
  C2:=0;
  end;

Readln;
end.

Output:

1)     220     284
2)    1184    1210
3)    2620    2924
4)    5020    5564
5)    6232    6368
6)   10744   10856
7)   12285   14595
8)   17296   18416
9)   63020   76084
10)   66928   66992
11)   67095   71145
12)   69615   87633
13)   79750   88730
14)  100485  124155
15)  122265  139815
16)  122368  123152
17)  141664  153176
18)  142310  168730
19)  171856  176336
20)  176272  180848
21)  176336  171856

*176336 repeats on the preceding line, when 176336 already appeared on the right column two lines before.
22)  180848  176272
23)  185368  203432
24)  196724  202444

A: There's a difference between what you are storing into the arrays and what you are displaying on the screen. You are storing every pair, but displaying (or, at least, trying to display) only unique ones. And you are enumerating the displayed pairs differently from those stored. Adding to that is the fact that, when checking whether a number has already been encountered (and displayed, apparently), you are searching only the first 35 elements of your arrays.
Now, if you decided to display all the pairs that your program discovers, i.e. to see what is being stored into the arrays and under which indices, you could see the following:
1)     220     284
2)     284     220
3)     496     496
4)    1184    1210
5)    1210    1184
6)    2620    2924
7)    2924    2620
8)    5020    5564
9)    5564    5020
10)    6232    6368
11)    6368    6232
12)    8128    8128
13)   10744   10856
14)   10856   10744
15)   12285   14595
16)   14595   12285
17)   17296   18416
18)   18416   17296
19)   63020   76084
20)   66928   66992
21)   66992   66928
22)   67095   71145
23)   69615   87633
24)   71145   67095
25)   76084   63020
26)   79750   88730
27)   87633   69615
28)   88730   79750
29)  100485  124155
30)  122265  139815
31)  122368  123152
32)  123152  122368
33)  124155  100485
34)  139815  122265
35)  141664  153176
36)  142310  168730
37)  153176  141664
38)  168730  142310
39)  171856  176336  <<<
40)  176272  180848
41)  176336  171856
42)  180848  176272
43)  185368  203432
44)  196724  202444
...

Note when 176336 is first encountered: in the pair #39. Now you see why your program seems to disregard it when displaying the number the second time: simply because it doesn't bother to search the arrays beyond the 35th element.
On the other hand, 35 might be enough if you stored only what you displayed.

A: The condition for your final list is
If (C2<>LastNum) and (NumUsed<>'T') and (Num<>C2) Then
Using
If (C2<>LastNum) and (NumUsed<>'T') and (Num<C2) Then
should leave only one pair having the smaller number first.
The switched pairs are also in 20) and 22) and probably there are more to follow.
Haven't checked the correctness, though.


text:
Q: 404 for custom post link on IIS with URL Rewrite Module I need to use IIS to develop the new WordPress site. After reading a lot of articles, I installed the URL Rewrite Module on IIS (https://www.iis.net/downloads/microsoft/url-rewrite).
My site structure is:
localhost/projectname/projectcms/
I set the WordPress URL on cms as:
http://localhost/projectname/projectcms
And the wordpress was installed inside the projectcms folder.
The site URL as:
http://localhost/projectname
Also, I customize the post link as:
http://localhost/projectname/% category%/%year%/%postname%/
(no space between "%" and "c")
However, those pages display 404 errors.
What is the rewrite rule I need to set on the URL Rewrite Module in order to make those links work?

A: Do you want to redirect from http://localhost/projectname to http://localhost/projectname/% category%/%year%/%postname%/? if so, you can try this rule:
<rule name="test" enabled="false" stopProcessing="true">
    <match url="^projectname$" />
    <action type="Redirect" url="http://localhost/projectname/% category%/%year%/%postname%/" />
</rule>


text:
Q: While cycle create an infinite loop I wrote this PHP code to put on a wordpress page template:
<?php
query_posts('showposts=10&cat=7');
while (have_posts()) : the_post();
?>

    <?php the_content(); ?>

<?php endwhile; ?>

When I view the page I don't see any result and the right bar of the browser continue to reduce itself. I have understand that the code create an infinite loop.
Where I mistake?
Thanks

A: Firstly, you should not use query_posts. It's too invasive for simple loops, and messes with the entire WP_Query. Also showposts should be posts_per_page.
Secondly, it's hard to gauge what this issue is without more context. Perhaps pastebin your entire page, and edit it into your question. My guess is a loop within a loop, and should stop at like a 100 posts. (10 X 10) but if it's reset anywhere else if could very well go infinite!
Use this code instead to create loops:
$custom_query = new WP_Query( 'posts_per_page=10' );

if($custom_query->have_posts()) :

    while ( $custom_query->have_posts() ) : $custom_query->the_post();

        //global $post; // for stuff like $post->post_name

        // Post stuff here
        // the_title();

    endwhile;

endif;
// Reset Post Data
wp_reset_postdata();

Look at the WordPress codex for more details. http://codex.wordpress.org/Class_Reference/WP_Query#Parameters

A: You should use an if statement in your loop:
<?php
query_posts('showposts=10&cat=7');
if ( have_posts() ): while ( have_posts() ) : the_post();
?>

    <?php the_content(); ?>

<?php endwhile; endif; ?>

A: Without further information, I would say that in each loop of the while statement, the function is returning the first row of the data? So each time the while loop executes you are calling the function again, which is returning the same row over and over again without actually iterating through the result set.


text:
Q: C++ input function that calls itself I have a question regarding a function that takes a string(command, first, and last name) and executes depending on what that input is. My function has several else if statement, and if the input is considered invalid, how do I let the user type in another command? Thank you
EXAMPLE_INPUT = "CREATE John Doe"

std::string get_input(std::string& s)
{
  std::string raw_input;
  std::getline(std::cin, raw_input);
  std::istringstream input(raw_input);

  std::string command;
  std::string first_name;
  std::string last_name;

  input >> command;
  input >> first_name;
  input >> last_name;

  //what do I return? I can't return all 3 (command, first, last)
}

void std::string input_function(std::string& s)
{
  if (s == "ONE")
  {
    call function_one()
  }

  else if (s == "TWO")
  {
    call function_two()
  }

  else
  {
    //How do I get user to type in something else(call get_input() again)?
  }
}

A:  struct input_result {
   std::string command;
   std::string first_name;
   std::string last_name;
 };

have your get input function return the above (an input_result).
The function that processes the input should have a means of returning failure or an error.  Then the code that calls get_input can call the processing code, notice it failed, and loop back to calling get_input.
You can wrap the two up into one function called get_and_process that first gets, then processes, and if the processing fails repeats the get.
You should only take things by bare & if you plan on changing them -- if not, take by const & instead.

A: If you want to return more than one variable, consider enclosing them in a struct or a class and return that. About typing in another command, you theoretically could use recursion as your post suggest but that's just wrong, it will crash the program if the user types wrong words in too many times. Instead you could use a simple while loop:
bool success = false;
while(!success){
    /* check the input, if it's correct - process it and set success to true */

}

A: You usually want to do this by putting the related data together into a struct (or class):
struct whatever {
    std::string command;
    std::string first_name;
    std::string last_name;
};

...then overloading operator>> for that type:
std::istream &operator>>(std::istream &is, whatever &w) {
    return is >> w.command >> w.first_name >> w.last_name;
}

This allows all the data to be "returned" in a single structure, and the status of the input operation to be returned in the istream that's actually returned, so you can read an item, and check whether that succeeded in a single operation:
std::ifstream in("myfile.txt");
whatever x;

if ( in >> x)
    // input succeeded, show some of the data we read:
    std::cout << "command: " << x.command
              << "\tName: " << x.last_name << ", " << x.first_name << "\n";
else
    std::cerr << "Input failed";

To give the user another chance to enter data when reading fails, you'd typically do something like this:
while (!in >> x)
    "Please Enter command, First name and last name:\n";

Note that when reading data (especially data you expect to be entered interactively by the user) you almost always want to check the input this way.


text:
Q: Error haciendo una consulta SQL con JavaScript estoy intentando hacer un SELECT desde node.js para obtener un error de una tabla de "errores" pero obtengo el siguiente error y ya no se que mas hacer o a que se debe.

UnhandledPromiseRejectionWarning: RequestError: Could not find stored
  procedure 'S@param1L'.

Este es el codigo que uso:
function BD_Connection(err){
  var conn = sql.connect(config, function(err, request){
    var message = "Codigo error: BD0001 \nDescripcion: Error al conectar con la base de datos \nFuncion: BD_Connection()";
  if(err) {
    //throw new error(message);
    console.log(err)
  }else{
    conn.query("SELECT * FROM Error WHERE Error_Code = DB0002",function(err, result){
      if(err){
        console.log("Error")
      }else{
        console.log(result)
      }
    })
  }
  })
}

En este metodo llamo a esa funcion:
app.listen(3001, function(err, res){
  if(err){
    console.log("Error")
  }else{
    console.log('Im listening');

  }
  let fs = require('fs');

fs.readFile('config/config.txt', 'utf-8', (err, data) => {
  if(err) {
    console.log('error: ', err);
  } else {
    var NewConfig = JSON.parse(data);
    config = NewConfig;
    BD_Connection("DB0002");
}
});
});

Alguien sabe a que se ppuede deber? Gracias.


text:
Q: Pandas table lookup I have a pandas lookup table which looks like this
Grade   Lower_Boundary  Upper_Boundary
1   -110    -96
2   -96 -91
3   -91 -85
4   -85 -81
5   -81 -77
6   -77 -72
7   -72 -68
8   -68 -63
9   -63 -58
10  -58 -54
11  -54 -50
12  -50 -46
13  -46 -42
14  -42 -38
15  -38 -34
16  -34 -28
17  -28 -18
18  -18 -11
19  -11 -11
20  -11 -9

I have another pandas dataframe that looks contains score. I want to assign 'Grade' to the score column, by looking up the look up table. So based on which interval of lower and upper boundary the score falls, the grade should be assigned from that row in the lookup table. Is there a way to do it without typing a bunch of if then else statements? I am thinking just of excel's index match.
Score   Grade
-75 6
-75 6
-60 9
-66 8
-66 8
-98 1
-60 9
-82 4
-70 7
-60 9
-60 9
-60 9
-56 10
-70 7
-70 7
-70 7
-66 8
-56 10
-66 8
-66 8

A: A one-line solution (I call your lookup table lookup):
df['Score'].apply(lambda score: lookup['Grade'][(lookup['Lower_Boundary'] <= score) & (lookup['Upper_Boundary'] > score)].values[0])

Explanation:
For a given score, here is how to find the grade:
score = -75
match = (lookup['Lower_Boundary'] <= score) & (lookup['Upper_Boundary'] > score)
grade = lookup['Grade'][match]

This return a series of length 1. You can get its value with, for instance:
grade.values[0]

All you need to do is apply the above to the score column. If you want a one-liner, use a lambda function:
df['Score'].apply(lambda score: lookup['Grade'][(lookup['Lower_Boundary'] <= score) & (lookup['Upper_Boundary'] > score)].values[0])

Otherwise the following would be more readable:
def lookup_grade(score):
    match = (lookup['Lower_Boundary'] <= score) & (lookup['Upper_Boundary'] > score)
    grade = lookup['Grade'][match]
    return grade.values[0]

df['Score'].apply(lookup_grade)

This approach would also make it easier to deal with cases when no match is found.

A: One option is with the conditional_join from pyjanitor, and also covers overlapping intervals:
# pip install pyjanitor
import pandas as pd
import janitor

(df2
.conditional_join(
    df1,
    ('Score', 'Lower_Boundary', '>='),
    ('Score', 'Upper_Boundary', '<='),
    how = 'left')
.loc[:, ['Score', 'Grade']]
)

    Score  Grade
0     -75      6
1     -75      6
2     -60      9
3     -66      8
4     -66      8
5     -98      1
6     -60      9
7     -82      4
8     -70      7
9     -60      9
10    -60      9
11    -60      9
12    -56     10
13    -70      7
14    -70      7
15    -70      7
16    -66      8
17    -56     10
18    -66      8
19    -66      8

You could achieve this also with pd.IntervalIndex and it should be faster, especially if your data does not have overlapping intervals.


text:
Q: Fabric 2.0.1 What is the replacement for env? I have an old fabfile.py (Fabric 1.8.3) which has the following line:
env.key_filename = '/etc/appliance/fabric/id_rsa'

How do I do the same in Fabric 2.0.1? I tried using fab with -i  option. But it doesn't seem to be working.

A: You can specify key_filename as part of connect_kwargs when constructing a Connection: fabric.connection.Connection
Alternatively you can set connect_kwargs's key_filename key in your configuration file.


text:
Q: JQuery .text() is removing my input tags checkbox completely I don't think I can explain this too good in words, so I made a fiddle for you guys:
JSFiddle

$(document).ready(function () {
 $("#clickMe").click(function(){
    $("#label1").text("test1234");
    $("#label2").text("test1234");
  })
});

      <input type="checkbox"/>
       Label 1

    <input type="checkbox" id="checkbox_id">

      Label 2

<button id="clickMe">
Click me
</button>

As you can see, I prepared one input checkbox surrounded by a label, and one where the label is assigned via the for="..." functionality.
I now try to change the text of the label on both. However, the surrounding label is completely losing the <input> tag it is surrounding. It is just completely gone.
The other one works perfectly.
However, I would like to have it working the first way. Is there a possiblity to achieve this?

A: The safe and best way is to replace your HTML to add a  for the text content and use .text() on the :

$(document).ready(function () {
  $("#clickMe").click(function(){
    $("#label1 span").text("test1234");
    $("#label2 span").text("test1234");
  })
});

      <input type="checkbox"/>
      Label 1

    <input type="checkbox" id="checkbox_id">

      Label 2

<button id="clickMe">
  Click me
</button>

A: This is what you're looking for:
$(document).ready(function () {
    $("#clickMe").click(function(){
    var childElement = $('#label1').find('input:checkbox');

    $("#label1").append(childElement).before(childElement).text('123');
    $("#label2").text("test1234");
  })
});

Or try it on your (updated) fiddle:
— https://jsfiddle.net/9m4bgyq8/4/

EDIT
This one is better:
$(document).ready(function () {
    $("#clickMe").click(function(){
    var childElement = $('#label1').find('input:checkbox');

    $("#label1").html(childElement);
    $('#label1').append(' test1234');

    $("#label2").text("test1234");
  });
});

— https://jsfiddle.net/9m4bgyq8/12/

A: You had the label tag outside of the input on the first one - once you switch that around it should work.
      <input type="checkbox"/>

   Label 1

$(document).ready(function () {
 $("#clickMe").click(function(){
    $("#label1").text("test1234");
    $("#label2").text("test1234");
  })
});

      <input type="checkbox"/>

       Label 1

    <input type="checkbox" id="checkbox_id">

      Label 2

<button id="clickMe">
Click me
</button>

A: Well you can try using native DOM manipulated like so :
$(document).ready(function () {
  $("#clickMe").click(function(){
    $('#label1')[0].childNodes[2].nodeValue='123213';
  });
});

Demo

A: jQuery.text() replaces the contents of a DOM node with the provided text. It's like emptying the element, then writing the text into it, so non-text child nodes are removed as well.
You could go over every childNode, check if it's a text node, and replace it with a new text - but there's a catch because there are probably more than one text nodes (white space also counts!). So I made a function that removes all text nodes and replaces the last one with new text:
demo
jQuery.fn.replaceText = function( newText ){
    this.each( function(element){
    [].slice.call(this.childNodes).forEach(function(node,i, nodes){
      if( node.nodeType == 3){
        if( i == nodes.length -1 ){  // last text node: change the text
            node.nodeValue = newText;
        }
        else { // any other text node: remove it
            node.parentNode.removeChild( node );
        }
      }
    });
  });
}

A: In case anyone needs an answer that doesn't involve changing the markup, you can use:

  $("#clickMe").click(function() {
    $("#label1").html($.trim($("#label1").html())).contents().filter(function(e) {
      if (this.nodeType === 3) this.nodeValue = ' test1234'
    });
    $("#label2").text("test1234");
  })

      <input type="checkbox" /> Label 1

    <input type="checkbox" id="checkbox_id">

      Label 2

<button id="clickMe">
  Click me
</button>

A: For sure it does because jQuery .text() "set the content of each element in the set of matched elements to the specified text." (http://api.jquery.com/text/#text2)
To solve your problem you can wrap the text you want to change in your label e.g.: Label 1 https://jsfiddle.net/9m4bgyq8/2/


text:
Q: Transform NSString to NSURL within a JSON Array with Mantle Let's say given to me is the following JSON response
{
    "images": [
        "http://domain.com/image1.jpg",
        "http://domain.com/image2.jpg",
        "http://domain.com/image3.jpg"
    ]
}

With Mantle I want to parse those strings and transform them into NSURLs but keep them in an NSArray.
So my Objective-C model object would look like
@interface MyModel : MTLModel <MTLJSONSerializing>
// Contains NSURLs, no NSStrings
@property (nonatomic, copy, readonly) NSArray *images;
@end

Is there an elegant way to achieve that? Some NSURL array transformer?
+ (NSValueTransformer*)imagesJSONTransformer
{
    return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:[NSURL class]];
}

Obviously NSURL does not derive from MTLModel, so that will not work.

A: Unfortunately, Mantle 1.x doesn't have an easy way to apply an existing transformer (in this case, the transformer named MTLURLValueTransformerName) to each element of an array.
You can do it like this:
+ (NSValueTransformer*)imagesJSONTransformer {
    NSValueTransformer *transformer = [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
    return [MTLValueTransformer transformerWithBlock: ^NSArray *(NSArray *values) {
        NSMutableArray *transformedValues = [NSMutableArray arrayWithCapacity:values.count];
        for (NSString *value in values) {
            id transformedValue = [transformer transformedValue:value];
            if (transformedValue) {
                [transformedValues addObject:transformedValue];
            }
        }
        return transformedValues;
    }];
}

In Mantle 2.0, you'll be able to use the predefined array mapping transformer. Mantle 2.0 is still in development.


text:
Q: Ever since vs since Let's say you kissed a co-worker, after that you have been thinking of her incessantly. You say:

Ever since the day we kissed, I can't stop thinking about you.

Or

Since the day we kissed, I can't stop thinking about you.

What is difference between the two? (Sentence meaning)

A: "Ever since" is very idiomatic in this circumstance. It is such a common expression that it wouldn't occur to me (or most other people, I think) to start out that sentence with just plain "Since". However, either way is grammatical, and perfectly good English.
"Ever since the day we kissed ..." sounds slightly more emphatic/dramatic than simply "Since the day we kissed ...", but other than that both sentences have the very same meaning, and both sound fine.


text:
Q: How to use silhouette_score in Sklearn with mixed (categorical and numerical) data? I have come to a situation where I have mixed data set as mentioned and try unsupervised clustering.
I am trying many different experiments including Gower's distance and K-prototype. I wanna try some of sklearn metrics to see how they will give me values.
While I was looking at silhouette_score, there is an argument 'metric' and I can decide with what I want to compute distances. But as my data has mixed types, I would like to choose manhattan for numerical and hamming for categorical. Is there a way I can use silhouette_score for both metrics at one go? if all my input data were numerical, I would have done as below:
silhouette_score(friendRecomennderData, labels, metric = 'manhattan')

Thank you in advance.

A: You are getting confused in the arguments that are passed to silhouette_score. If you read the documentation mentioned here, it say the following about the input data, i.e. the parameter X:

X: array [n_samples_a, n_samples_a] if metric == "precomputed", or, [n_samples_a, n_features] otherwise. Array of pairwise distances between samples, or a feature array.

Thus the data can only be a numerical array comprising of distances between the samples. It's not possible to have distances as categorical values.
You need to first cluster your data, then get the distance matrix and provide the distance matrix as input to silhouette_score.

A: You can use distance metrics like gowers distance which deals with mixed data types and then use computed distance matrix as X and metric = 'precomputed' in silhouette_score function.


text:
Q: Show the two elements in foreach loop in every iteration? How we can show the two elements in for each loop in each iteration?
For example I have an array like this:
$arr = array('a', 'b', 'c', 'd','e','f');

And want to show the records like this:
  a-b
  c-d
  e-f

Any ideas?

A: Loop over the array with for.
Print the current and current plus one value in each iteration by counter.
Increment the counter.
<?php
$arr = array('a', 'b', 'c', 'd','e','f');
$i=0;
$len = count($arr);
for ($i=0; $i< $len; $i++) { // We could have used count($arr)
//instead of $len. But, it will lead to
//multiple calls to count() function causing code run slowly.
    echo "
".$arr[$i] . '-' . $arr[$i+1];
  ++$i;
}
?>

A: You can use array_chunk, it is meant exactly for these kind of cases and it's the shortest and most efficient way to do it.
$arr = array('a', 'b', 'c', 'd','e','f');
foreach(array_chunk($arr , 2) as $val) {
    echo implode('-', $val)."\n";
}

Chunks an array into arrays with size elements.

More details:
http://php.net/manual/en/function.array-chunk.php
Demo: https://3v4l.org/BGNbq

A: <?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
?>

The above example will output:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)

A: Try this:
<?php
  $array = array('a', 'b', 'c', 'd','e','f');
  $length = count($array);
  for ($i=0; $i< $length; $i+2) {
      echo "
".$arr[$i] . '-' . $arr[$i+1];
  }
?>


text:
Q: Translate help MS SQL => Oracle I am trying to translate an MS SQL function to oracle I am running into trouble. They reason being creating temporary table within the function to gradually add to. I can't seem to replace the temporary table with a cursor to gradually add to. Someone has to have a good idea how to write this in Oracle:
ALTER FUNCTION [dbo].[F_GetDateIntervalTable]
(
@OccurredFrom datetime,
@OccurredTo datetime,
@Interval decimal
)
RETURNS @Tbl table
(
[Dts] datetime
)
AS
BEGIN
    DECLARE @Count int
    --DECLARE @Tbl table([Dts] datetime)
    DECLARE @Dts datetime
    DECLARE @SeedDts datetime

SET @Count = 1
SET @Dts = DATEADD(MINUTE, FLOOR(DATEDIFF(MINUTE,0,@OccurredFrom)/@Interval)*@Interval, 0);
SET @SeedDts = DATEADD(MINUTE, FLOOR(DATEDIFF(MINUTE,0,@OccurredFrom)/@Interval)*@Interval, 0);
SET @OccurredTo = DATEADD(MINUTE, -@Interval, @OccurredTo);
WHILE (@SeedDts < @OccurredTo)
BEGIN
    SET @SeedDts = DATEADD(MINUTE, @Interval*(@Count-1), @Dts)
    INSERT INTO @Tbl(Dts) VALUES(@SeedDts)
    SET @Count = (@Count + 1)
END

RETURN

END

The output should be this (given the parameters):
@OccurredFrom = '2013-01-01',
@OccurredTo = '2013-01-02',
@Interval = 60

2013-01-01 00:00:00.000
2013-01-01 01:00:00.000
2013-01-01 02:00:00.000
2013-01-01 03:00:00.000
2013-01-01 04:00:00.000
2013-01-01 05:00:00.000
2013-01-01 06:00:00.000
2013-01-01 07:00:00.000
2013-01-01 08:00:00.000
2013-01-01 09:00:00.000
2013-01-01 10:00:00.000
2013-01-01 11:00:00.000
2013-01-01 12:00:00.000
2013-01-01 13:00:00.000
2013-01-01 14:00:00.000
2013-01-01 15:00:00.000
2013-01-01 16:00:00.000
2013-01-01 17:00:00.000
2013-01-01 18:00:00.000
2013-01-01 19:00:00.000
2013-01-01 20:00:00.000
2013-01-01 21:00:00.000
2013-01-01 22:00:00.000
2013-01-01 23:00:00.000

Any ideas are grealty appreciated!

A: Assuming you need to use a function rather than simply writing a SQL query
SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select date '2013-01-01' start_date,
  3           date '2013-01-02' end_date,
  4           60 interval
  5      from dual
  6  )
  7  select start_date + numtodsinterval( interval * (level-1), 'minute' )
  8    from x
  9* connect by level <= (end_date - start_date)*24*60/interval
SQL> /

START_DATE+NUMTODSI
-------------------
2013-01-01 00:00:00
2013-01-01 01:00:00
2013-01-01 02:00:00
2013-01-01 03:00:00
2013-01-01 04:00:00
2013-01-01 05:00:00
2013-01-01 06:00:00
2013-01-01 07:00:00
2013-01-01 08:00:00
2013-01-01 09:00:00
2013-01-01 10:00:00
2013-01-01 11:00:00
2013-01-01 12:00:00
2013-01-01 13:00:00
2013-01-01 14:00:00
2013-01-01 15:00:00
2013-01-01 16:00:00
2013-01-01 17:00:00
2013-01-01 18:00:00
2013-01-01 19:00:00
2013-01-01 20:00:00
2013-01-01 21:00:00
2013-01-01 22:00:00
2013-01-01 23:00:00

24 rows selected.

you can create a pipelined table function
SQL> create type tbl_date as table of date;
  2  /

Type created.

SQL> create or replace function get_date_interval( p_start_date in date,
  2                                                p_end_date   in date,
  3                                                p_interval   in number )
  4    return tbl_date
  5    pipelined
  6  is
  7    l_return_dt date := p_start_date;
  8  begin
  9    while( l_return_dt < p_end_date )
 10    loop
 11      pipe row( l_return_dt );
 12      l_return_dt := l_return_dt + numtodsinterval( p_interval, 'minute' );
 13    end loop;
 14    return;
 15  end;
 16  /

Function created.

SQL> select *
  2    from table( get_date_interval( date '2013-01-01',
  3                                   date '2013-01-02',
  4                                   60 ));

COLUMN_VALUE
-------------------
2013-01-01 00:00:00
2013-01-01 01:00:00
2013-01-01 02:00:00
2013-01-01 03:00:00
2013-01-01 04:00:00
2013-01-01 05:00:00
2013-01-01 06:00:00
2013-01-01 07:00:00
2013-01-01 08:00:00
2013-01-01 09:00:00
2013-01-01 10:00:00
2013-01-01 11:00:00
2013-01-01 12:00:00
2013-01-01 13:00:00
2013-01-01 14:00:00
2013-01-01 15:00:00
2013-01-01 16:00:00
2013-01-01 17:00:00
2013-01-01 18:00:00
2013-01-01 19:00:00
2013-01-01 20:00:00
2013-01-01 21:00:00
2013-01-01 22:00:00
2013-01-01 23:00:00

24 rows selected.


text:
Q: Azure Storage restrict access one container only This is my situation: Two groups in Azure AD.
Group 1 can access only container1, but not container2
Group 2 can access only container2, but not container1
To achieve this I have given IAM Role Permission on each container accordingly (assigned Storage Blob Data Contributor Role to group).
Code Sample I used: https://github.com/Azure-Samples/storage-dotnet-azure-ad-msal
But to upload/download any file on container I have to assign role of Storage Blob Data Contributor on Storage Account as well. If I give Storage Blob Data Contributor on Storage Account then that Group users can add files to any container.
So is there any way to achieve like,
Group 1 can access only container1, but not container2
Group 2 can access only container2, but not container1

A: Denying group to a container is not supported yet. As given in the image taken from IAM blade: "At this time, the only way you can add your own deny assignments is by using Azure Blueprints."
Denying access to users is quite a process. So it is best if you create two storage accounts and manage the access at storage account level instead of Container. This is not for group but for a single user in group.

A: What you can do is assign 'Reader' access to the storage account, then 'Storage Blob Data Reader' for that same user/group, BUT provide a condition to only allow them access to containers of a specific name. In my example below I called the container "test-access-medata"


text:
Q: Why aren't my LEDs turning on while using Proteus? I'm trying to simulate an audio vumeter, using an audio amplifier built with a LM386. However, when I connect the output of the signal to the input of one of the opamps (I'm using LM358), the outputs are all negative.

A: You are not sending any voltage signal to the comparators. Thus they won't show anything with no input.


text:
Q: Hyperledger Composer multi-user mode: ECONNREFUSED for issued identities I've been following Caroline's blog to setup a multi-user composer rest server. So, I have two servers viz. Admin Server and the User Server.
As mentioned in the tutorial I:

*

*Started the Admin Server with no authentication and single user mode. I started this server with Admin's card.

*Started the User Server with JWT authentication in multi-user mode. I started this server with Admin's card as well.

*Created a User participant and generated a card for user from the admin server.

*Exchanged the first JWT token for this user on the User Server. So now the user has an access token.

*Using this access-token I imported the user's card generated in #3 into the User Server.

*Checked the Wallet status using user's access-token and was able to see the card to be set as default. i.e. default:true

This seems to have worked fine. However, now I'm trying to ping the network using User Server and User's access token. And it results in:

Error: Error trying login and get user Context. Error: Error trying to enroll user or load channel configuration. Error: Calling enrollment endpoint failed with error [Error: connect ECONNREFUSED 127.0.0.1:7054]

I tried setting this card to be default again but with no luck. When I list the identities issued from the admin server, I'm able to see this identity. But the status of this identity is "ISSUED". While the status of admin identity is "ACTIVATED". Is this an issue?
Or am I missing out on any of the important step here?


text:
Q: Close modal as soon as another one is pressed I want a modal to close once a different modal is pressed, but I'm not sure on how to do  it.
Essentially, if modal1 is pressed, it should show the contents of modal1, but as soon as modal2 is pressed,modal1 should disappear and only modal2 should show it's contents. How do I go about this?
I've tried to set it up with an open and close in the onclick but only had problems.
This is how I've got my code currently set up:
 const [openQueueList, setOpenQueueList] = useState(false);
  const handleOpenQueue = () => {
    setOpenQueueList(true);
  };
  const [openRoomlist, setOpenRoomlist] = useState(false);
  const handleOpenRoom = () => {
    setOpenRoomlist(true);
  };
  const [openRoomQueueList, setOpenRoomQueueList] = useState(false);
  const handleOpenRoomQueue = () => {
    setOpenRoomQueueList(true);
  };

in the return

              {openQueueList ?
                <TrackTable></TrackTable>
               : null}

              {openRoomlist ?
               <LobbyUsers> </LobbyUsers>
               : null}

              {openRoomQueueList ?
                <QueueSection></QueueSection>
               : null}

Triggering the buttons
           <button onClick={handleOpenRoomQueue}>
              <QueueMusicIcon></QueueMusicIcon>
            </button>
            <button onClick={handleOpenRoom}>
              <GroupIcon ></GroupIcon>
            </button>
            <button onClick={handleOpenQueue}>
              <AudiotrackIcon></AudiotrackIcon>
            </button>

A: Instead of using a state for each modal you could give each a key.
State would look like this
const [currentModal, openModal] = useState(null);

Then to open
<button onClick={() => openModal('queueList')}>Queue List</button>
<button onClick={() => openModal('roomList')}>Room List</button>
<button onClick={() => openModal('roomQueueList')}>Room Queue List</button>

Then your modals would look something like:

  {currentModal === 'queueList' ?
    <TrackTable></TrackTable>
  : null}

  {currentModal === 'roomList' ?
    <LobbyUsers> </LobbyUsers>
  : null}

  {currentModal === 'roomQueueList' ?
    <QueueSection></QueueSection>
  : null}


text:
Q: Creating a 3D array in Java I'm trying to implement a 3D array in Java but I've a problem, my problem is that I don't know one of the lengths of 3D array size, it means that third length of my 3D is variable and it depends on
the input size. In other words my 3D array called
int arcbits[64][1][length(input)];

first two sizes are fixed, it's always [64][1] and just the third length is variable.
length(input) is always positive integer greater zero.
Input is like this form = {1,0,1,1}, so in this case for instance the arcbits size is:
int arcbits[64][1][4];

How do I implement that in Java? My problem is that there's a variable length which for instance in c++ or c we do dynamic allocation ...because we don't know the size of the array. So do I do 3D array in Java with implicitly variable size?!
I'm stuck on this about two days and I didn't succeed to implement 3D array in Java, this is the first time I counter this, any suggestion to help me out?

A: int[][][] arcbits = new int[64][1][length(input)];

See https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

A: see here:
Sum in Java (built in method)'s Implementation?
I already declared 3d array in java, I guess you look on the same concept.


text:
Q: $f[a_1] = G$ means $a_1 \subseteq f^{-1}[G]$ for functions on metric spaces? The theorem/proof:

Question
The part that I don't under stand is the red underlined bit.
What I understand:
let $a_1,a_2$ be sets s.t $a_1 \oplus a_2 = A$ and let $f[a_1] = G$ and let $f[a_2] = H$.
This works because $G$ and $H$ are disjointed.
But then $A = U\cup V$ (thanks to the "$A\cap $" and the way $U$ and $V$ are defined in the proof)suggests that $a_1 \subseteq f^{-1}[G]$ and $a_2 \subseteq f^{-1}[H]$
But how can we just assume this? Is it not possible to have $U\cup V \neq A$? {eg: $ f^{-1}[G] \subset a_1 $}


text:
Q: Running MariaDB from a replaced drive After replacing the hard drive in my laptop, I realized I forgot to make a backup of my databases. I still have the old drive available as external harddisk, but I can't boot into it.
The OS on both the old and new machine are Ubuntu 16.04, and the MariaDb version on both is 10.* The databases are all innodb.
I've tried pointing the datadir of my new installation to the old datadir, but that results in mysqld never starting.
I still have the complete disk, including the old mariadb binaries. Is there some way I can run those? I just need them for a few minutes to do a backup.

A: I have no idea if pointing to the old datadir works.
What I did and it worked fine for me in order to move data from an old server to a new one is: installed mysqld services on a new machine and before starting it, synced the data directory. After that starting the mysqld service on the new server I could find all databases completely intact.


text:
Q: \hspace does not work before longtable The following code produces the image below.
\documentclass[a4paper]{article}
\usepackage{lipsum}

\begin{document}
\lipsum[1]

\hspace{-14mm}
\begin{tabular}{p{2mm}p{122mm}p{2mm}}\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
\end{tabular}

\lipsum[1]
\end{document}

Now, I want to do the same with a longtable, however, the \hspace command seems to not cause any effect. Here is an example of it:
\documentclass[a4paper]{article}
\usepackage{longtable,lipsum}

\begin{document}
\lipsum[1]

\hspace{-14mm}
\begin{longtable}{p{2mm}p{122mm}p{2mm}}\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
\end{longtable}

\lipsum[1]
\end{document}

Any idea of how can I do that?

A: You need to set the length \LTleft, if you want to change the position of the longtable (as default it is centered).
\documentclass[a4paper]{article}
\usepackage{longtable}
\usepackage{lipsum}

\begin{document}
\lipsum[1]

\setlength\LTleft{-14mm}
\begin{longtable}{p{2mm}p{122mm}p{2mm}}\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
  &\parbox{122mm}{\lipsum[1]}& \\\hline
\end{longtable}

\lipsum[1]
\end{document}


text:
Q: No Password Prompt After Generating new Personal Access Token My github token expired recently, which I had to generate a fresh one. I however haven't been able to push to the remote git server since then. I get the error:
fatal: unable to access 'https://github.com/xx/yy/':
The requested URL returned error: 403

I also don't get a prompt to sign in. I can pull from a repo but I cannot push. How can I make my cli prompt me to input my github password/ access token? I'm using a macbook m1-pro

A: You can manually remove the old password using Keychain Access app. Rightclick on entry and choose "delete github.com". Then cli will ask you to re-enter credentials.


text:
Q: How to get statemachineARN with name of statemachine I have a state machine name(e.g. custom-state-machine), and I want the statemachineARN of this, how could I achieve that.
there is function, list_state_machines(), but it gives all the state machines details.
Also, I saw the function describe_state_machine(), but it requires the statemachineARN.
My goal is to get statemachineARN just from the name of state-machine

A: This is one approach. Get a list of all step functions using the list_state_machine call, then iterate through each, if there is a match on the name then extract the ARN.
import boto3

name = 'HelloWorld'

sfn_arn = None

client = boto3.client('stepfunctions')
response = client.list_state_machines()['stateMachines']
for sfn in response:
    if sfn['name'] == name:
        sfn_arn = sfn['stateMachineArn']


text:
Q: TSQL Continuous Counters Given:
Table A with fields F1, F2, F3, first two fields are ints, last is varchar.
F1 unique, F2 and F3 can container any values
F1  F2  F3
==========
1   1   A
2   1   A
3   1   A
9   1   B
19  2   B
20  2   C
29  2   C
34  2   B
35  2   A
36  2   A
37  2   A
49  2   A

I need to produce counters for for each combination of F2 and F3 for continues ranges of F1 in the following format:
Start Count F2 F3
=================
1     3     1  A
9     1     1  B
19    1     2  B
20    1     2  C
29    1     2  C
34    1     2  B
35    3     2  A
49    1     2  A

I know how to accomplish the task using a cursor, wonder if the result can be produced using just select statement?
Update 1 - Sorry if it wasn't clear - I want the last interval for 2-A to be split by two because of the brake in F1.

A: WITH MyCTE AS
(
  SELECT  T1.F1,
          T1.F2,
          T1.F3,
          ISNULL((
            SELECT TOP 1 F1
            FROM table1 AS x
            WHERE T1.F1 < x.F1 AND (T1.F3 = x.F3 AND T1.F2 = x.F2)
            ORDER BY F1 DESC
          ),0) AS grpby
  FROM    Table1 T1
)

SELECT  MIN(F1) AS Start,
        COUNT(F1) AS [Count],
        F2,
        F3
FROM    MyCTE
GROUP BY F2,
        F3,
        grpby
ORDER BY 1

Here is a fiddle example


text:
Q: Android Gson не присваивает POJO объекту значение при использовании Retrofit2 При использовании Retrofit2 столкнулся с проблемой. Создал POJO вида:
public class Root {
    private String str;
    private Map <Long, Long> map;
    //getters and setters
}

добавил класс MapJsonDesirializer
который отрабатывает, и даже правильно парсит JSON, но не присваивает его нужному полю.
public class MapJsonDeserializer implements JsonDeserializer<Map<Long, Long>> {
    @Override
    public Map<Long, Long> deserialize(
            JsonElement json,
            Type typeOfT,
            JsonDeserializationContext context
    ) throws JsonParseException {
        if (json != null) {
            Map<Long, Long> result = new HashMap<>();
            Iterator<Map.Entry<String, JsonElement>> iterator =
                    json.getAsJsonObject().entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, JsonElement> next = iterator.next();
                result.put(Long.valueOf(next.getKey()), next.getValue().getAsLong());
            }
            return result;
        }
        return null;
    }
}

Подскажите пожалуйста, что могло пойти не так? Или может есть ещё какие нибудь способы распарсить HashMap, который приходит с сервера?


text:
Q: Why my dynamical programming of fibonacci doesn't give a linear time? I am watching this video. Basically it says that using a dictionary(python's language?) will make calculate fibonacci from time O(n^2) to O(n).
I have the programmed the following code, fibo1 ought to be O(n) but actually it runs really slow. fibo2 is the normal recursion and it is O(n^2) solution, but actually it runs much faster than fibo1. How can I understand this?
#include <iostream>
#include <map>
int fibo1(int i, std::map<int,int>& m);
int fibo2(int i);

int main()
{
    std::map<int,int> m;
    m[1] = 1; m[2] = 1;
    int n = 40;
    std::cout << fibo1(n,m);
    //std::cout << fibo2(n);
    return 0;
}

int fibo1(int i, std::map<int,int>& m)   {
    if(m[i]==0)   {
        return fibo1(i-1,m)+fibo1(i-2,m);
    }
    return m[i];
}

int fibo2(int i) {
    if(i==1 || i==2) {
        return 1;
    }

    return fibo2(i-1)+fibo2(i-2);
}

A: You never actually write the fib[n] at m[n], so you never look up anything and always recalculate it. Use m[i] = fibo1(i-1,m) + fibo1(i-2,m); in the if statement rather than the return line.

A: In the fibo1 method you are only returning the values without setting the map a proper value.
int fibo1(int i, std::map<int,int>& m)   {
if(m[i]==0)   {
    m[i] = fibo1(i-1,m)+fibo1(i-2,m);
}
return m[i];
}

Also, you should consider using a simple vector instead of a map to get a better performance

A: You do not store result in the map, and you should remember, that std::map::operator[] is doing lookup which is significantly expensive, so you should avoid multiple lookups for the same key:
int fibo1(int i, std::map<int,int>& m)   {
    int &value = m[i];
    if( value == 0)   {
        value = fibo1(i-1,m)+fibo1(i-2,m);
    }
    return value;
}