text:
Q: Can't I see a list of 'Others' in Foursquare herenow? I'm writing a program looking for 'herenow' of Foursquare. As I attached, there are 2 people in the venues, but I can't see the people using the API, the API only returns an empty list.
Can't I see the members because they are with a type "others"? Isn't there any way to solve the problem?
hereNow: {count: 2,
...,
groups: [{type: "others",
...
count: 2,
items: [ ]
}
]
},

A: As akdotcom mentioned the documentation gives you the latest information on how the endpoint works: https://developer.foursquare.com/docs/venues/herenow
There's been a change to how this endpoint works.
It used to be that it returned everybody currently checked-in at a venue (within 3 hours).
It's been changed so if you're not checked-in at a venue you can only see your friends (and friends of friends according to the current documentation) that are checked-in there, you cannot see non-friends.
Once you check-in you'll be able to see everybody with one exception, people that have opted out of appearing in herenow will not be shown though I believe are still reflected in the count.
I believe their explanation is this is more like the real world. If you're not physically there you cannot see who's there.
Only venue managers can see everybody checked-in without being checked-in themselves.

A: See the endpoint documentation (https://developer.foursquare.com/docs/venues/herenow) for an overview of what "herenow" information is returned for different types of requests. You're probably making a "userless" request which only returns counts, no user information.


text:
Q: twenty seventeen theme: comments UI not visible I'm new to WP, so I may be missing something. But I've tried everything and cannot figure out how to display the comments UI on posts. When I switch to different themes, the problem is resolved and I can see the comments box. But no luck whatsoever in the twenty seventeen theme. Any advice? I've spent a good amount of time trying to set up my new blog on this theme and I'd like to use it. But there seems to be some type of glitch. Thanks.

A: Had this problem and wasted SO many hours, until I read someone else's post explaining that in most themes the comment UI only shows up on the INDIVIDUAL blog post page, ie, the page that loads when you click on the title of the post, NOT on the landing page for the blog posts. Don't like it, but don't think it can be changed...

redpajama_set_name: RedPajamaStackExchange


text:
Q: knex transactions in the same network request (no dependencies) When writing transactions in application code you have 2 situations:

*

*A: You need to grab some data from the database, modify it in the app code, then do a subsequent SQL update using that modified app code data (second call depends upon first)

*B: You need to perform a series of commits that have no data dependencies on each other -  either they must all succeed or all fail

Examples (little contrived)
A:

*

*start transaction trx

*read from orders table the email addresses of everyone

*in the app code (database client) send everyone an email

*update every order to mark it's the user has been emailed

*end transaction

B:

*

*read from a csv text file containing orders (email, customer number) into memory

*start transaction trx

*in the app code, send everyone an email (assume none will fail)

*insert into another table a historal log of who has been emailed as part of trx

*update into a another table the total count of emails sent

*end transaction trx

it's a little contrived but the point is, in case B, operations 4 and 5 don't need to be in the same transaction as 1. in such a case we want to build a knex query which would produce
BEGIN TRANSACTION
INSERT INTO historicalEmailsSent ...
SET count FROM emailsSentCount WHERE customer='custId'
COMMIT
I'm not sure if knex does this today, when you create a transaction, e.g.
const trx = knex.trasnaction();
await trx('historicalEmailsSent).udpdate(...)

await trx('emailSentCount).update(...)
trx.commit();

my understanding is you will end up making 2 separate network requests to the database, holding the transaction open, when you could have made only one. This is because knex doesn't know if inbetween your first and second transaction, you do someething in your app code which then a later transaction depends upon.
Or am I mistaken?


text:
Q: My Flex app sometimes take a time navigating away to another tab and back to load in browser In my Flex app I give the user the ability to open up a new item form ( s:Panel ) and create multiple items on the page.
Sometimes for some odd reason bringing up the panel (simple task) seems to take a really long time to load (like 30 seconds or so) However, the weird thing is that if right after I click to open I navigate away from the Tab and back again to the Flex app tab it shows up right away.
I'm not sure if this has to do with refresh rate or some setting or is it general performance/memory issue with my app that I have to consider. When the application work it works fairly fast which is making me think it's not memory/performance issue.

A: It's hard to be sure without more details, but are you following the component life cycle? Just to be sure we're talking about the same thing, here's a nice presentation about it: http://www.slideshare.net/rjowen/adobe-flex-component-lifecycle-presentation


text:
Q: Why cannot invoke 'indexPathForCell' with an argument of list type '(UICollectionView)'? I created a UICollectionView with this tutorial.
And then I want pass indexPath from this UICollectionView to my GameViewController like in this question/answer.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: LevelCell = collectionView.dequeueReusableCellWithReuseIdentifier("Level", forIndexPath: indexPath) as! LevelCell
    cell.imgCell.image = UIImage(named: levels[indexPath.row + 1]!.levelImage)
    cell.lblCell.text = levels[indexPath.row + 1]!.levelLabel
    return cell
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "StartGame" {
        if let gameView = segue.destinationViewController as? GameViewController {
            if let cell = sender as? UICollectionViewCell, indexPath = collectionView.indexPathForCell(cell) {
                gameView.level = indexPath
            }
        }
    }
}

But this does not work - even when I use LevelCell instead of UICollectionViewCell. I get this error:
Cannot invoke 'indexPathForCell' with an argument list of type '(UICollectionViewCell)'
How can I get the indexPath of the element I just touched in my UICollectionView so that I can bypass it from this function to GameViewController?

A: You're casting the senderto UICollectionView, but it's probably UICollectionViewCell.
if let cell = sender as? UICollectionViewCell, indexPath = collectionView.indexPathForCell(cell) {
    gameView.level = indexPath
}


text:
Q: AWS DataPipeline EvaluateExpression using Java SDK Using the AWS DataPipeline API, I'm trying to programmatically evaluate an Expression like the following:
sometext-#{format(@scheduledStartTime, 'YYYYMMddHHmmss')

To evaluate the expression, I'm using a PipelineObject that looks something like the following:
Id:@MyPipelineObject_2018-08-26T01:00:00
Name:@MyPipelineObject_2018-08-26T01:00:00
     - Key:@scheduledStartTime
     - StringValue:2018-08-26T01:00:00
     - Key:@scheduledEndTime
     - StringValue:2018-08-27T01:00:00

How can I evaluate the expression, given that I know the pipelineId and pipelineObjectId? I'm using the Java AWS SDK, and creating an EvaluateExpressionRequest like so:
String expressionToBeEvaluated = "sometext-#{format(@scheduledStartTime, 'YYYYMMddHHmmss')";
String myPipelineObjectId = "@MyPipelineObject_2018-08-26T01:00:00";

EvaluateExpressionRequest evaluateExpressionRequest = new EvaluateExpressionRequest()
                .withPipelineId(myPipelineId)
                .withExpression(expressionToBeEvaluated)
                .withObjectId(myPipelineObjectId);

However, from the docs it's not clear to me how to actually issue the request with the EvaluateExpressionRequest object. I've looked at EvaluateExpressionResult but the setEvaluatedExpression method only takes a String as input.
Am I doing something wrong, missing something fundamental, or does the SDK just not support what I'm trying to do?
Any input or suggestions would be really appreciated. Thanks!

A: So I figured it out a few minutes after posting my question. It turns out the answer is very simple and I've just been looking at this stuff for too long. The DataPipeline object has the method evaluateExpression() which takes an EvaluateExpressionRequest and returns the EvaluateExpressionResult. You get the evaluated result by calling getEvaluatedExpression on the returned object.
EvaluateExpressionRequest evaluateExpressionRequest = new EvaluateExpressionRequest()
                .withPipelineId(myPipelineId)
                .withExpression(expressionToBeEvaluated)
                .withObjectId(myPipelineObjectId);

dataPipeline.evaluateExpression(evaluateExpressionRequest).getEvaluatedExpression(); //evaluates to sometext-20180826010000

Hope that helps anyone with a similar affliction!


text:
Q: Integrability of $ \exp(-f(x)) $ What are the loosest assumptions on $f(x)$ for the distribution $P_f$ whose density $p_f$ wrt lebesgue measure is given by
$$ p_f(x) = \frac{e^{-f(x)}}{ \int_{\mathbb R^d}  e^{-f(y)}dy} \qquad \text{for all } x \in \mathbb R^d, $$
to be well defined.
For example, $f(x) = \frac{x^\top \Sigma^{-1}x}{2}$ leads to a well defined distribution when  $\Sigma$ is positive definite (Normal distribution $\mathcal{N}(0, \Sigma)$). In this case, $f$ is strongly-convex and has Lipschitz continuous gradients.
I am guessing we do not need these two assumptions for $P_f$ to be well defined.


text:
Q: REST api to retrieve user profiles (Spring Boot) I want to display list of freelancers with there data and profile image.
How to write a rest api to retrieve list of profile images?
Or should I retrieve list of user data and retrieve there images one by one
I have created api to retrieve a single image
    @GetMapping(value = "/{userName}/retrieveImage")
    public ResponseEntity<?> retrieveImage(@PathVariable String userName) throws FileNotFoundException {
        byte[] imageData;
        imageData = freelancerService.retrieveImageFromFileSystem(userName);
        return new ResponseEntity<>(imageData, HttpStatus.OK);
    }

A: First of all, your url name is not good case for rest endpoint naming. You can check a good documentation for that:
Rest Api Rules
So it should be something like this:
@GetMapping(value = "/images/image/{userName}")

Instead of userName, use userId or similar to that which you can use it for database search with index and more suitable for unique identification for requests.
@ResponseBody
@GetMapping(value = "/images/image/{userName}", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> retrieveImage(@PathVariable String userName) throws IOException {
   InputStream inputStream = servletContext.getResourceAsStream(pathOfImageFile);
   // This method can return inputStream
   // freelancerService.retrieveImageFromFileSystem(userName);
   return new ResponseEntity<byte[]>(IOUtils.toByteArray(ininputStream, HttpStatus.CREATED);
}


text:
Q: css transform translate not working, has it been deleted or is this just a bug i m watching a tutorial video about css loaders, and replicating exactly that, in the code below, at this point in the video, the css transform, translate3d works, but on the replicated code below, it doesn't i ve checked what could possibly be the problem, severally comparing my code with that in the vid, but no issues, so how come css transform: translate3d isn't working, why are my balls not bouncing?
/*index.html*/
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/loader3.css">
    <title>CSS Loaders</title>

/* loader3.css*/
.loader {
    display: flex;
    justify-content: center;
    align-items: center;
}

.loader > span {
    display: inline-block;
    background-color: purple;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    margin: 0 8px;
    transform: translate3d(0);
    animation: bounce 0.6s infinite alternate;
}

.loader > span:nth-child(2) {
    background-color: palevioletred;
}

.loader > span:nth-child(3) {

}

@keyframes bounce {
   to {
        width: 16px;
        height: 16px;
        transform: translate3d(0 -16px, 0)
    }
}

A: pay attention to details
transform: translate3d(0 -16px, 0)
lack ,
transform: translate3d(0, -16px, 0)


text:
Q: PostgreSQL dynamic table access I have a products schema and some tables there.
Each table in products schema has an id, and by this id I can get this table name, e.g.
products
    \ product1
    \ product2
    \ product3

I need to select info from dynamic access to appropriate product, e.g.
SELECT * FROM 'products.'(SELECT id from categories WHERE id = 7);

Of course, this doesn't work...
How I can do something like that in PostgreSQL?

A: OK, I found a solution:
CREATE OR REPLACE FUNCTION getProductById(cid int) RETURNS RECORD AS $$
    DECLARE
    result RECORD;

    BEGIN
        EXECUTE 'SELECT * FROM ' || (SELECT ('products.' || (select category_name from category where category_id = cid) || '_view')::regclass) INTO result;

        RETURN result;
    END;
$$ LANGUAGE plpgsql;

and to select:
SELECT * FROM getProductById(7) AS b (category_id int, ... );

works for PostgreSQL 9.x

A: If you can change your database layout to use partitioning instead, that would probably be the way to go. Then you can just access the "master" table as if it were one table rather than multiple subtables.
You could create a view that combines the tables with an extra column corresponding to the table it's from. If all your queries specify a value for this extra column, the planner should be smart enough to skip scanning all the rest of the tables.
Or you could write a function in PL/pgSQL, using the EXECUTE command to construct the appropriate query after fetching the table name. The function can even return a set so it can be used in the FROM clause just as you would a table reference. Or you could just do the same query construction in your application logic.

A: To me, it sounds like you've a major schema design problem: shouldn't you only have one products table with a category_id in it?
Might you be maintaining the website mentioned in this article?
http://thedailywtf.com/Articles/Confessions-The-Shopping-Cart.aspx


text:
Q: Issue with org.mockito.Matchers.any() and jmockit I have one UT using jmockit and mockito
in this UT,I have one field @Tested TestService testService
testService have one method using Car as parameter : testService.doTest(Car car)
then my UT: testService.doTest(any(Car.class))
when I debug this UT I found that testService.doTest(any(Car.class)) always pass null into doTest(car),what if I want an instance of Car in doTest(car)?
I tried (Car)any(),(Car)anyObject(),none of them help,any ideas?
updated:
I Have code:
class TestService{
    @AutoWired
    Dependency dependency;

    doTest(Car car){
        dependency.doSomeThing(car);
        print(car.toString());
    }
}

UT code:
@Injectable Dependency mockDependency;
@Tested TestService testService;
//record
new Expectations() {{
    mockDependency.doSomeThing((Car)with(any));
    result=detailCar;
}};
//call verify
new Verifications(){{
    codeResult=testService.doTest((Car)with(any))
    //some codeResult assert
}};

this all jmockit version,I get NullPointerException at car.toString()
if I change it to:
new Verifications(){{
    codeResult=testService.doTest(new Car())
    //some codeResult assert
}};

or
final Car car;
new Verifications(){{
    codeResult=testService.doTest(car)
    //some codeResult assert
}};

I get MissingInvocation at codeResult=testService.doTest(...) seems instance car don't match (Car)with(any)

A: Mock car = mock(Car.class) and pass this car in doTest. Hope it ll help
Also if you are calling any method of Car, make sure you also define the behaviour.
for eg
when(car.getName(anyString())).then("bmw");


text:
Q: python turtle fill alternate squares i have created a program that creates a 10x10 grid of squares (30x30):
I am trying to write a subroutine that fills every 2nd square (like a checkerboard).
here is what I have so far, but can't get it to work
def colour():
for j in range(5):
    for i in range (4):
        turtle.fillcolor('black')
        turtle.begin_fill()
        turtle.forward(30)
        turtle.right(90)
        turtle.end_fill()
turtle.forward(60)

any help please

A: The main problem is begin_fill and end_fill were in the nested loop, so it was trying to fill each line of the square and not the finished shape. I also added turtle.pu() and turtle.pd() to get rid of the dragging line.
turtle.fillcolor('black')
for j in range(5):
    turtle.begin_fill()
    for i in range (4):
        turtle.forward(30)
        turtle.right(90)
    turtle.end_fill()
    turtle.pu()
    turtle.forward(60)
    turtle.pd()

If you did want the unfilled squares to show between the filled ones, a few quick edits could fix that:
turtle.fillcolor('black')
for j in range(10):
    if j & 1:
        turtle.begin_fill()
    for i in range (4):
        turtle.forward(30)
        turtle.right(90)
    if j & 1:
        turtle.end_fill()
    turtle.forward(30)


text:
Q: Finding extreme values in vector elements in R I have a vector like this:
x<-c(-0.193,-0.126,-0.275,-0.375,-0.307,-0.347,-0.159,-0.268,-0.013,0.070,0.346,
0.376,0.471,0.512,0.291,0.554,0.185,0.209,0.057,0.058,-0.157,-0.291,-0.509,
-0.534,-0.239,-0.389,0.060,0.250,0.279,0.116,0.052,0.201,0.407,0.360,0.065,
-0.167,-0.572,-0.984,-1.044,-1.039,-0.831,-0.584,-0.425,-0.362,-0.154,0.207,
0.550,0.677,0.687,0.856,0.683,0.375,0.298,0.581,0.546,0.098,-0.081)

I would like to find the position of the lowest number each time >=5 consecutive values are <-0.5. In the example that is the value -1.044.
How do I find this?
What I have done is this:
xx<-ifelse(x>.5,1,NA)
xx

aa<-rle(xx)
zz <- rep(FALSE, length(xx))
zz[sequence(aa$lengths) == 1] <- aa$lengths >= 5 & aa$values == 1
zz

But then I just find the position of the first value and not the extreme.
Any help?

A: Thanks for posting what you've tried.
I'd just use a logical comparison for xx:
xx <- x < -0.5

Then your rle logic becomes:
aa <- rle(xx)
zz <- aa$lengths >= 5 & aa$values

From there, identify which values of zz are true and use cumsum to get the indicies of x (this is oversimplified since there is only once instance but you get the picture):
first <- which(zz)
idxs <- cumsum(aa$lengths[1:first])
min(x[idxs[first-1]:idxs[first]])

In the instance where you have multiple matches, first will be a vector with length > 1.  In that case, make a function and you can apply it to your vector:
myfun <- function(y) {
    idxs <- c(0, cumsum(aa$lengths[1:y]))
    min(x[idxs[y]:idxs[y+1]])
}

set.seed(20)
x <- rnorm(100)
xx <- x < -0.5
aa <- rle(xx)
zz <- aa$lengths >= 3 & aa$values
first <- which(zz)

sapply(first, myfun)

A: A function with the apply function inside:
find.val <- function(x,threshold,n,all=T){
  tmp <- rle(x < threshold)
  cs <- cumsum(tmp$lengths)
  dfcs <- data.frame(indices=c(0,cs[-length(cs)])+1,l=cs)
  pos <- (apply(dfcs,1,function(y) which.min(x[y[1]:y[2]])+y[1]-1))[tmp$values==1 & tmp$lengths >= n]
  if(all==T) return(pos)
  pos[which.min(x[pos])]

}
if you set all=T you get all matches otherwise only the position of the lowest match.
Example:
find.val(x,-0.5,5,all=T)


text:
Q: Why this customTheme is not applied to my buttons
Why this customTheme is not applied to my buttons. I'm using the MUI 5. Please tell me where I'm making the mistakes & how to resolve this.

import React from 'react';
import NavBar from './components/NavBar';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { Button } from '@mui/material';

const customTheme = createTheme({
overrides: {
   MuiButton: {
     outlined: {
        backgroundImage: 'linear-gradient(to top, #d299c2 0%, #fef9d7 100%)',
        color: 'green'
      },
      text: {
        color: "red"
      }
    }
  }
})

function App() {
  return (
    <div id='appDiv2'>
      <ThemeProvider theme={customTheme}>
        <NavBar />
        <Button variant='outlined'> Test Button </Button>
      </ThemeProvider>
      <DirectionSnackbar />
    </div>
  );
}

export default App;

A: The structure of the theme object depends on the version of MaterialUI. If you use latest, the scheme should be
const theme = createTheme({
  components: {
    // Name of the component
    MuiButton: {
      styleOverrides: {
        // Name of the slot
        outlined: {
         backgroundImage: 'linear-gradient(to top, #d299c2 0%, #fef9d7 100%)',
         color: 'green'
        },
        text: {
         color: "red"
        }
      },
    },
  },
});

https://mui.com/customization/theme-components/#global-style-overrides


text:
Q: Standard Method TEXT is undefined when compiling jasper report When I package my stand-alone-java-application, that compiles, renders and prints Jasper-Reports, in a fat jar with all dependencies, I get the error that the function TEXT – a function used in the report and defined in the net.sf.jasperreports-functions-library is not found.
The method TEXT(Integer, String) is undefined for the type [...]
                value = IF(LEN(TEXT(((java.lang.Integer)parameter_X.getValue()),"#"))==2,"***",REPT("*",6-LEN(TEXT(((java.lang.Integer)parameter_X.getValue()),"#")))) //$JR_EXPR_ID=58$

Other functions from the same library work. When I run the application with gradle run, the function is found and the report can be printed. The library is on my classpath.
There are several similar questions on this site and Stackoverflow, but neither provided answers, that worked for me. In the following, I will explain what I tried:
In my build.gradle-File I defined dependencies to the following libraries:
implementation('net.sf.jasperreports:jasperreports:6.18.1')
implementation('net.sf.jasperreports:jasperreports-functions:6.18.1')

In my java-Files, I created a DesignFile and statically imported the functions into it. I tried two methods:
Method 1 as given in an answer in this thread: Unresolved symbols when compiling jasper report
/*…*/
designFile = JRXmlLoader.load(sourceFile.getAbsolutePath());

designFile.addImport("static net.sf.jasperreports.functions.standard.TextFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.MathFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.DateTimeFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.LogicalFunctions.*");

JasperReport compiledReport = JasperCompileManager.getInstance(ctx).compile(designFile);
/*…*/

Method 2: importing each function on its own
public static String[] textFunctions(){
        return new String[]{"BASE", "CHAR", "CLEAN", "CODE", "CONCATENATE", "DOUBLE_VALUE",
"EXACT", "FIND", /*"FIXED", */"FLOAT_VALUE", "INTEGER_VALUE", "LEFT", "LEN", "LONG_VALUE",
"LOWER", "LTRIM", "MID", "PROPER", "REPLACE", "REPT", "RIGHT", "RTRIM", "SEARCH", "SUBSTITUTE",
"T", /*"TEXT",*/ "TRIM", "UPPER"};
    }}
/*…*/
designFile = JRXmlLoader.load(sourceFile.getAbsolutePath());

for (String textFunction : textFunctions()){
            designFile.addImport("static net.sf.jasperreports.functions.standard.TextFunctions." + textFunction);
        }/* similarly for logical functions, numeric functions and datetime functions*/
        }
JasperReport compiledReport = JasperCompileManager.getInstance(ctx).compile(designFile);
/*…*/

As you can see, the function TEXT is commented out. That's because the program fails at runtime when run with "gradle run", when I comment it in:
net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file:
1. The import net.sf.jasperreports.functions.standard.TextFunctions.TEXT cannot be resolved
import static net.sf.jasperreports.functions.standard.TextFunctions.TEXT;

The same thing is true with most datetime-functions, in fact, only TIME can be imported to the DesignObject without error at runtime
In addition to that, when I type net.sf.jasperreports.functions.standard.TextFunctions. in my IDE, the content-assist shows a list of available functions, yet TEXT is missing.

I suspected, that the function is simply missing in the library, but it is there. In the .gradle/cache/modules-2/files-2.1/… directory, there is the jar with the TextFunctions.java, that contains the function TEXT:

When building the FatJar with dependencies, I have a TextFunctions.class-File in it, that contains the TEXT-Function as well.

In my jar, there are two jasperreports_extension.properties on the root level:

with the smaller one (from the jasperreport-functions-dependency) containing the following lines:
net.sf.jasperreports.extension.registry.factory.functions=net.sf.jasperreports.functions.FunctionsRegistryFactory
net.sf.jasperreports.extension.functions.datetime=net.sf.jasperreports.functions.standard.DateTimeFunctions
net.sf.jasperreports.extension.functions.math=net.sf.jasperreports.functions.standard.MathFunctions, net.sf.jasperreports.functions.standard.LogicalFunctions
net.sf.jasperreports.extension.functions.text=net.sf.jasperreports.functions.standard.TextFunctions
net.sf.jasperreports.extension.functions.report=net.sf.jasperreports.functions.standard.ReportFunctions

Funnily enough, commenting out TEXT, running it locally with gradle run, it works without problems. But packaging it and running it with java -jar it fails to find this function. And statically importing this function leads to gradle run failing as well.
What is happening and how can I fix this? I want to distribute my FatJar on a server and run it, but this problems makes it impossible for me.


text:
Q: User input required to update the date in my SQL file using Python UPDATE! I am still looking for some way that to indicate to the user to make an update to these dates but I went with this method:
I declared a variable in my SQL file so it looks like:
    declare @date date = DATE
    Select * from table WHERE date = @date

and then in my python it looks like:

    DATE = date(2022, 10, 31)
    def sql_data(sql_path, date):
     with open(sql_path) as sql_file:
      sql = sql_file.read()

    sql = sql.replace("DATE", "'{}'".format(date.strftime('%Y-%m-%d')))

    df = sql_data('sql_path', DATE)
     df.to_csv('csv path', index=False)

I have a Python script that will execute my SQL script and create a csv file. I need to run this csv file on a monthly basis -- I am trying to do two things:

*

*Before my Python code executes and runs the SQL to create a csv file, I need to replace the date in my SQL statement first and update it to whatever month I will run this report.

*Force the user who is running the Python to enter in a date that will replace the date in my SQL statement. I want a fail-safe that will not let the user move on with the code until the date is updated.

The SQL statement looks like:
select * from table as x
where x.date = '10/30/2022'
I need to replace the string 'MM/DD/YYY' to whatever date I want in the format of 'MM/DD/YYYY'. One issue is that the x.date value won't be the same since this SQL statement will be run on a monthly basis. I need the value of x.date to be based off what the user inputs.
So far I have this (ignore that I didn't establish a connection -- I just took it out of this description)
new_date = input("Enter in the reporting date here (format: 'MM/DD/YYYY')")

with open('myreport.sql', 'r') as sqlfile:
   str.replace(' .date = "XXXXX", 'new_date')

I'm unsure how to replace the string within my sql file since the date value is not necessarily consistent every time i run this report.
The SQL statement looks like:
select * from table as x
where x.date = '10/31/2022' (date isn't necessarily 10/31/2022)

A: You still have not posted any code requested, but I still give it a try.
What you want is a parameterised query
cursor.execute("select * from table as x where x.date = (?)", (user_input))

This way you can define user_input and use it as part of the query.
You could also simply format a string:
query = f"select * from table as x where x.date = {user_input}"

But this is problematic as the user could inject unwanted code into your query.


text:
Q: Vue.js: The route change but its repective component is not rendered. No errors in the console I have the vue-router instance working, I mean when i click in a button router-link, the url goes to another address and i have in the router.js file, the right pairs "route" and component". but here comes the problem: the route change but the component is not rendered and there is no error in the console
Component 1

Router.js

View-router


text:
Q: How to write test code before write source code when they are objects dependencies? I'l will take an example: requirement: construct a piece of material following these rule: among given < 100 => material is green
100 < among <300=> material is yellow
among > 300=> material is red
My test class:
        class MaterialTest{
          MaterialConstructor materialCons
          public void testBuild(){
                 materialCons.setAmount(150);
                 Material material=materialCons.build();
                 assertEqual(material.getColor(),"Yellow");
              }
    }

From know i don't how to implemented materialCons.build(); After design and analysis i've implemented MaterialCosntructor  as follow:
    public class MaterialConstructor {

         private Helper1 helper1;
         private Helper2 helper2

        MaterialConstructor (Helper1 help1, Helper2 help2){
      .................
    }

    public Material build(Double among){
         part1=helper1.builpart(among);
        return helper2.construct(part1);
    }

}

In my initial test class i must includes code like this:
helper1=createMock(Helper1)
helper2=createMock(Helper2)

materialCons=new MaterialConstructor (helper1, helper2)

.....................

expected(helper1.builpart(150)).andReturn(some result)
expected(helper2.construct(some result)).andReturn("Yellow")

as result we can get this updated class test:
  class MaterialTest{
         MaterialConstructor materialCons
        public void testBuild(){
            helper1=createMock(Helper1)
            helper2=createMock(Helper2)
            materialCons=new MaterialConstructor (helper1, helper2)
            expected(helper1.builpart(150)).andReturn(some result)
            expected(helper2.construct(some result)).andReturn("Yellow")
             materialCons.setAmount(150);
             Material material=materialCons.build();
             assertEqual(material.getColor(),"Yellow");

          }
            }

hence my test code will be update after writen my source code!
This will appear many time ( since it's difficult at specification time to know which dependencies class you must use to solve your problem). Then unit-test class will be always obsolete after written source code!

A: Following a strict TDD workflow such as the 3 Laws of TDD would definitely put an end to your hesitations.
With it you can't have such things as "After design and analysis i've implemented MaterialCosntructor ..." since you are supposed to

Write only enough production code to pass a test

Which basically means : just return "Yellow" as your first implementation.
Then you would add more tests (green, red material) and incrementally design your class to handle these additional cases.

A: No I think your idea is absolutely brilliant to have unit test cases for testing objects. I do not think the test class will be obsolete after written source code because in your case you have designed the class members and class methods.. the only thing that seems to be stopping you is to write the EasyMock testcases.. Here is some help material, maybe it will make things more clear for you IBM Developer Works Simulation Page ..
There is also one more hyperlink which is by EasyMock readme themselves EasyMock ReadMe


text:
Q: Updating field in a existing row Android Hello I'm in a situation as follows upon receiving an item for storing on DB I have to execute insert if the row matching a unique field doesn't exists else update a particular field in the row. I tried this and I'm facing an Exception of
android.database.sqlite.SQLiteConstraintException: column title is not unique (code 19)

How can I safely achieve the above scenarios without exception

A: You could use UPDATE OR IGNORE.
However if you are using the SQLiteDatabase update method, you cannot specify this.
You'd either use the updateWithOnConflict method. SQLiteDatabase - updateWithOnConflict

*

*with the conflict algorithm as CONFLICT_IGNORE.

*the method returns the number of rows updated.

Or you could pre-check for the uniqueness along the lines of
Cursor csr = dbhlpr.query(
    your_table,
    new String[]{your_column},
    your_column + "=?",
    new String[]{your_value_as_a_string},
    null,
    null,
    null
);
if (csr.getCount() < 1) {
    //.. do the update here using the `update` method
} else {
    //.. handle not able to insert as unique  here
}
csr.close();


text:
Q: How can I stop messages from printing more than once inside of an if statement? I am trying to create a hangman game where the user guesses a three-letter word. I have a variable called "guesses". I have my code set up to where if the user doesn't guess a letter that is in the word (chosen from a word list) then I have ++ for guesses. Depending on what guess the user is on, a message pops up saying that the letter is not in the word and they have however many guesses left. But what I noticed is that if a letter is guessed incorrectly, then after if it is guessed correctly, then the previous message still pops up
this is my code
I've tried incorporating a break or return statement, but it just stops it altogether. can anyone please help?
function hangManGame() {
  var wordList = ["cat"];
  var guesses = 0;

  var randomWord = wordList[Math.floor(Math.random() * wordList.length)];
  while (randomWord) {
    var letterGuessed = readLine("Please guess ONE lowercase letter at a time. ");
    if (letterGuessed == randomWord[0]) {
      println("Congratulations, you guessed a letter correctly!");
    } else if (letterGuessed == randomWord[1]) {
      println("Congratulations, you guessed a letter correctly!");
    } else if (letterGuessed == randomWord[2]) {
      println("Congratulations, you guessed a letter correctly!");
    } else {
      guesses++;
    }

     if (guesses == 1) {
      println("Sorry, that letter is not in the word, you have 2 guesses remaining.");
      add(head);
      add(body);
    }
     if (guesses == 2) {
      println("Sorry, that letter is not in the word, you have 1 guess remaining.");
      add(leftArm);
      add(rightArm);

    }
    if (guesses == 3) {
      println("Sorry, that letter is not in the word, you have 0 guesses remaining.");
      add(leftLeg);
      add(rightLeg);
    break;
    }

   }
  }

A: Your solution has some major flaws:

*

*It only works for 3 letter words

*You duplicate your code multiple times

*It also doesn't work at all you can type in letter "c" three times in a row and win.

this is my solution you can adapt it to your "needs" as I provided in comments

// the responseArray is to simulate the readLines as I wanted to run the code in the browser console
function hangManGame(word, tries = 3, responseArray = ['c', 'a', 't']) {
  // getting the first from array instead of reading user input
  while (responseArray.length > 0 && tries > 0) {
    const guessedLetter = responseArray.shift()
    // make it generic instead of having to rewrite the if over and over
    // if the word contains our letter
    if (word.indexOf(guessedLetter) != -1) {
      console.log(`correct guess: ${guessedLetter}`)
    } else {
      console.log(`Wrong latter: ${guessedLetter} tries remaining ${--tries}`)
    }
  }
}

hangManGame('cat', 3, ['x', 'a', 'f', 'g'])

AS provided in comments the response array is only there to simulate your user inputs so just remove it and instead of assigning guessedLetter variable to responseArray.shift() assign it to readLine(). If you have any questions add them in comment ;)
Still you should probably add a way for person to see the word they typing as in true hangman which would look something like this

// the responseArray is to simulate the readLines as I wanted to run the code in the browser console
function hangManGame(word, tries = 3, responseArray = ['c', 'a', 't']) {
  const correctLetters = [];
  // getting the first from array instead of reading user input
  while (responseArray.length > 0 && tries > 0) {
    const guessedLetter = responseArray.shift()
    // make it generic instead of having to rewrite the if over and over
    // if the word contains our letter
    if (word.indexOf(guessedLetter) != -1) {
      correctLetters.push(guessedLetter)
      console.log(`correct guess: ${guessedLetter}`)
      console.log(Array.from(word).map(letter => {
        return correctLetters.some(correctLetter => correctLetter === letter) ? letter : "_"
      }))
    } else {
      console.log(`Wrong latter: ${guessedLetter} tries remaining ${--tries}`)
    }
  }
}

hangManGame('cat', 3, ['x', 'a', 'c', 'g'])


text:
Q: How to add Bootstrap to my Symfony 4.1 project? I tried to find a similar case to mine but didn't succeed.
Here is the issue. I followed Symfony documentation to add Bootstrap to my project.
I indeed get a bootstrap folder in a new folder called "nodes_modules".
The thing is i can't find a global.scss file anywhere (as mentioned in the tutorial) then i don't know where to put the following command:

@import "~bootstrap/scss/bootstrap";

Do i have to create this file or does it exist somewhere in my Symfony project?
Thank you in advance.

A: Yes, global is your application scss file, it can be named different on you wish. You can refer this documentation in order to see how to configure it (it is app.scss in the example)

A: I understood what was wrong there! So if you are creating a Symfony 4.1 project on mac and you don't know where to import your bootstrap theme(s) since you don't have any assets folder here is the solution:
To have the assets folder you have to install the webpack "encore".
Please make sure you have node.js and yarn installed before that.
Then just run the following commands inside your root project directory:
 composer require symfony/webpack-encore-pack
yarn install
You might have now an "assets" folder inside your project with an assets/css/app.css file and a assets/js/app.js file.
Thank you for your time  ScayTrase.


text:
Q: Dblink to insert values i remote database with postgres I have to insert values of ABC into my_table in different DB connected via dblink  (both tables have the same columns but are unknown)
I have tried using record and cursors
 sql_str := 'select dblink_exec(''myconn'',''insert into my_table select * from abc'')';
 execute(sql_str);

error is abc table not found


text:
Q: How to write on an exiting spreadsheet with PHPSpreadsheet? I want to modify an existing spreadsheet with PHPspreadsheet and then save it.
I tried this code:
<?php

//load spreadsheet
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("yourspreadsheet.xlsx");

//change it
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'New Value');

//write it again to Filesystem with the same name (=replace)
$writer = new Xlsx($spreadsheet);
$writer->save('yourspreadsheet.xlsx');

I've found it on this question: here
but unfortunately it return this error:
 Uncaught TypeError: Argument 1 passed to PhpOffice\PhpSpreadsheet\Writer\Xlsx::__construct() must be an instance of PhpOffice\PhpSpreadsheet\Spreadsheet, null given

Any ideas?
Thank you.

A: Here is example code for spreadsheet:
    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
    $spreadsheet = $reader->load('yourspreadsheet.xlsx');

    $sheet = $spreadsheet->getActiveSheet();
    $last_row = (int) $sheet->getHighestRow();
    $new_row = $last_row+1;

    $sheet->setCellValue('A'.$new_row, "14");
    $sheet->setCellValue('B'.$new_row, "Alina");
    $sheet->setCellValue('C'.$new_row, "PG");
    $sheet->setCellValue('D'.$new_row, "$32");
    $sheet->setCellValue('E'.$new_row, "Pending");

    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
    $writer->save('yourspreadsheet.xlsx');


text:
Q: How do I insert a circle inside another circle with Piecewise? I need to create two circles, where one circle is inside the other using the Piecewise function. So far I have
f[x_, y_, z_, a_] := Piecewise[{{1, x^2 + y^2 <= 30}, {0, x^2 + y^2 > 30},}

I know by changing the radius, I can have a circle inside the other, but how do I go about it using Piecewise?

A: PolarPlot[Piecewise[{{1, θ < 2 Pi}, {2, θ > 2 Pi}}], {θ, 0, 4 Pi}]

Module[{i = 1}, % /. x_Line :> {ColorData[3][i++], x}]

Also implicit curves can be given in a list:
ContourPlot[
 {x^2 + y^2 == 1, x^2 + y^2 == 2^2},
 {x, -E, E}, {y, -E, E},
]

A: It should be noted that constructing "chimeric" curves, given their implicit Cartesian equations, is not too hard, and does not need a piecewise construction. Recall that if $f(x,y)=0$ and $g(x,y)=0$ are two non-identical curves, then the curve $f(x,y)\,g(x,y)=0$ is a curve composed of the two other curves. Thus, using the Wizard's example:
ContourPlot[(x^2 + y^2 - 1) (x^2 + y^2 - 2^2) == 0, {x, -3, 3}, {y, -3, 3}]

A: f[r1_, r2_] := Graphics[
  {Circle[{0, 0}, r1],
   Circle[{0, 0}, r2]}
  ]


text:
Q: Should questions about SQL query performance be migrated to codereview? There are many questions on SO regarding the performance of OP's SQL query, often with titles ending with "too slow" or "too long".
These queries return the right results, so the code "works", but often the approach is terrible and the fix is to basically rewrite the query from scratch.
Technically these would seem like candidates for migration to codereview, but due to the often extensive rework (way beyond "style" or "tweaks") they could be considered as "asking for code" with the OP's best effort posted in the question.
Should such questions be flagged for migration?
If so, should it depend on the amount of rework, or does "working code" alone qualify it for migration?

A: Many database performance problems have absolutely nothing to do with the code. If it's not a code problem, or it's a complex issue, why not migrate them to Database Administrators instead? Unless they're asking specifically about the code, I'm not sure why it would be more on-topic at code review.


text:
Q: Getting `Any` instead of Seq[DataFrame] I want to slightly improve the following code:
val filePathsList = Seq("path_1","path_2)

var seqdf = filePathsList.map(path => {
        try {
          sqlContext.read.format("json").load(path)
        } catch {
          case e: Exception => e.printStackTrace()
        }
})

Now seqdf has the type Any, because I added try ... catch. I need seqdf to be of the type Seq[DataFrame] while maintaining try ... catch for cases when json file does not exist at a path. How can I get it?

A: Use a flatMap and Option to automatically get rid of invalid values
var seqdf = filePathsList.flatMap(path => {
        try {
            Some(sqlContext.read.format("json").load(path))
        } catch { case e: Exception =>
            e.printStackTrace()
            None
        }
})

If you don't really care about the stack trace, then a more succinct version is shown below
var seqdf = filePathsList.flatMap(path => {
        Try(sqlContext.read.format("json").load(path)).toOption
})

A: Use Scala Try and getOrElse which more efficient than Java try catch. And you can return empty dataframe if the path is not found.
import sqlContext.implicits._

var seqdf = filePathsList.map(path => {
  Try(
    sqlContext.read.format("json").load(path)
  ) getOrElse Seq.empty[String].toDF()
})

Hope this is helpful


text:
Q: What is the complexity of solving this specific System of Diophantine Equations? Given a set of linear Diophantine equations such that:

*

*There are $3N$ equations.

*The equations consist of $4N$ unique variables.

*Each equation is of the form:

*

*($a_0$+$a_1$)=($a_2$+$a_3$) or

*($a_0$+$a_1$)=-($a_2$+$a_3$)
(where, $a_i$ is a variable)

Query 1: What is the computational complexity of solving this system of linear equations (assuming a solution exists).
Query 2: Given an additional constraint that: The sum of all 'pairs' in each equation must be a positive integer (i.e. in above examples ($a_0$+$a_1$) and ($a_2$+$a_3$) must be a positive integer). What is the computational complexity of this system of linear equations with the additional constraint (again, we are promised a solution exists).
I could not find any reference related to the above problem or its computational complexity. Can someone please help with this?


text:
Q: Uncaught SoapFault exception: [1062] Shipping method is not available Why only flatrate_flatrate in array shipping Method?
I set the customer and address is successfully.
Array
(
    [0] => Array
        (
            [carrier] => flatrate
            [carrier_title] => Flat Rate
            [code] => flatrate_flatrate
            [method] => flatrate
            [method_description] =>
            [price] => 5.0000
            [error_message] =>
            [method_title] => Fixed
            [carrierName] => Flat Rate
        )

)

Shipping method: flatrate_flatrate

Fatal error:  Uncaught SoapFault exception: [1062] Shipping
  method is not available in /var/www/html/market/mboh.php:118
      Stack trace:
      #0 /var/www/html/market/mboh.php(118): SoapClient->__call('call', Array)
      #1 /var/www/html/market/mboh.php(118): SoapClient->call('65d0a95484ac4eb...', 'cart_shipping.m...', Array)
      #2 {main}
        thrown in /var/www/html/market/mboh.php on line 118


text:
Q: Is there any difference between closure in Scheme and usual closure in other languages? I'm studying SICP right now. And I found the definition of closure in SICP is (maybe) different from closure definition in other languages.
Here's what SICP says:

The ability to create pairs whose elements are pairs is the essence of list structure's importance as a representational tool. We refer to this ability as the closure property of cons. In general, an operation for combining data objects satisfies the closure property if the results of combining things with that operation can themselves be combined using the same operation.

Here closure is more close to closure in Mathematics I think, not what I have seen in JavaScript, which means the ability of a function to access enclosed environment variables.
Am I wrong?

A: You're right; this text is not referring to "closures"--an implementation strategy to ensure that functions-as-values refer correctly to lexical bindings--but more generally to the mathematical notion of "closure", as for instance in the statement "the integers are closed under the addition operation". That is: applying the operation to any two elements of the set produces a result that is still a member of the set.

A: There is a difference in the use of "closure" in SICP from the way it is typically used in computing. From SICP Chapter 2, footnote 6:

The use of the word 'closure' here comes from abstract algebra,
  where a set of elements is said to be closed under an operation if
  applying the operation to elements in the set produces an element that
  is again an element of the set. The Lisp community also
  (unfortunately) uses the word 'closure' to describe a totally
  unrelated concept: A closure is an implementation technique for
  representing procedures with free variables. We do not use the word
  'closure' in this second sense in this book.

On the other hand, Schemer's use "closure" to refer to lexical closures just like programmers using other languages with lexical closures.


text: Q: How to design linear dynamic programming algorithm for shortest path? Given a weighed directed acyclic graph (G) and a vertex S of G. I want to design a linear time dynamic programming algorithm to find the length of the shortest path between S and every other vertex of G.


text:
Q: Causal Inference with unconfoundedness Consider an observational study with binary treatment. I denote treatment variable as $z_i$, denote observed outcome as $y_i$, denote potential outcome as $y_i(1),y_i(0)$, and denote covariates as $x_i$. Assume the unconfoundedness $P(Z | Y,X) = P(Z|X)$ holds in this problem.
I want to inference the sample average treatment effect on treatment group, i.e. $\frac{1}{\left| \{i|z_i = 1\} \right|} \sum_{i,z_i = 1} \left[Y_i(1) - Y_i(0)\right]$. A way to do this is to regress $Y(0) \sim X$ using data from control group, and directly apply the regression function $\hat{f}(X)$ to treatment group to estimate $Y_i(0)$ , finally, use $\frac{1}{\left| \{i|z_i = 1\} \right|} \sum_{i,z_i = 1} \left[Y_i(1) - \hat{f}(x_i)\right]$ to estimate $\frac{1}{\left| \{i|z_i = 1\} \right|} \sum_{i,z_i = 1} \left[Y_i(1) - Y_i(0)\right]$.
The method sounds weird, I actually want to estimate $Y(0)$ on the treatment group, but I only use data from the control group in regression. How can I improve it?

A: The units in the control group provide information about the relationship between the $X$ and $Y(0)$, because for those units, $Y$ (the observed outcome) is equal to $Y(0)$. If you want $Y(0)$ in the treated group, you can use that information to estimate it from $X$ in the treated group, just as you describe.
For the treated units, you have $Y_i(1)$ because $Y_i = Y_i(1)$ for them. It's not an estimate of $Y_i(1)$; it is $Y_i(1)$. From the treated group alone, we have half of the information required to estimate $\frac{1}{|{i|z_i=1}|} \sum_{i,z_i=1} [Y_i(1)-Y_i(0)]$, i.e., the SATT, because we have $Y_i(1)$ for $i$ where $z_i=1$ without doing any modeling. However, for these units, $Y_i(0)$ is missing. We don't know what would have happened had the treated units received control.
How could we get $Y_i(0)$ for the treated units? For those units, it's unobserved, so no modeling of just the treated units could tell you the relationship between $X$ and $Y_i(0)$. That information only exists in the control group. So even though we're interested in a quality of the treated group (i.e., the treated group SATT), we have to consult the control group because only the control group contains information that can help us fill in the other half of the estimate of the SATT.
There are, of course, other methods of estimating the SATT, including weighting and matching, that don't require you to estimate $Y_i(0)$ for each treated unit. But, because $Y_i(0)$ is only observed for the control units, we have to include them in the analysis.


text:
Q: How can I solve the TISE for a particle confined to a curve that isn't simple? I solved the TISE for different simple closed curves (e.g square, circle) as an exercise in finding and applying the correct boundary conditions but realised I don't know how to do it when the curve can't be continuously mapped onto an interval.
For example, what are the boundary conditions if a particle is confined to a square and its diagonal? (see picture)

I'm assuming the hamiltonian is of the form p^2/2m
Thank you :)


text:
Q: How can I search and replace a string from an undetermined number of columns and tables using MySQL? Using purely MySQL, I want to search and replace 'oldString' with 'newString' from and undetermined number of tables and columns.  A search for my table prefix in information_schema, reveals all the tables that I need to look for.
I have the following trials:
Querying DB table prefix on information_schema
SELECT TABLE_SCHEMA, TABLE_NAME
FROM information_schema.TABLES WHERE table_name LIKE  '%mysite_www%'

Results:
+-----------------+----------------------------+
| TABLE_SCHEMA    | TABLE_NAME                 |
+-----------------+----------------------------+
| myDB            | mysite_www_moredata        |
| myDB            | mysite_www_data            |
| myDB            | mysite_www_urls            |
| myDB            | mysite_www_pages           |
| myDB            | mysite_www_feedback        |
| myDB            | mysite_www_comments        |
| myDB            | mysite_www_links           |
+-----------------+----------------------------+
Query results yields about 200 tables or so.

I want to take the results, filter it for a particular string and replace it with a new one. Replace 'oldString' with 'newString'.
For each TABLE_NAME, search for any column WHERE column LIKE '%oldString%'.
WHERE CONCAT(table1, table2, ... tableN) LIKE 'oldString';

For each column result, update 'oldString' to 'newString'.
UPDATE tableN SET columnN = REPLACE (columnN, '%oldString%', 'newString') WHERE URL LIKE '%oldString%';

I need to do this in pure MySQL as it will be a store procedure.  Any assistance or tips is greatly appreciated.

A: So by using information_Schema you can query both the tables and columns to get a result. I have done something similar in this SO answer.
Essentially query the information_schema and let MySQL construct the SQL for you. The above link should get you going.
UPDATE:
You can use the following query to construct all the Update statements
SELECT CONCAT('UPDATE ',TABLENAME, 'SET ', COLUMN_NAME,'= REPLACE (',COLUMN_NAME, '''%oldString%'', ''newString'') WHERE URL LIKE ''%oldString%''')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE  '%somecriteria%' AND COLUMN_NAME LIKE '%somecriteria%'

Insert these resulting string into a temp table then loop through the rows executing the string by using the technique described here


text:
Q: Sub Queries How do you represent the sub queries in SELECT and WHERE clauses?

A: Statements that include subqueries usually take one of these formats:

*

*WHERE expression [NOT] IN (subquery)

*WHERE expression comparison_operator [ANY | ALL] (subquery)

*WHERE [NOT] EXISTS (subquery)

Subquery Fundamentals (SQL Server 2008 Books Online, January 2009)

A: You can use subqueries in SELECT and WHERE clauses like this:
select
  c.customerid,
  (
    select sum(i.amount) as totalspent
    from item i
    where i.customerid = c.customerid
  ) as totalspent
from customer c
where exists
(
  select *
  from purchase p
  where p.customerid = c.customerid
)

A: You've gotten some good anwsers, but try to see if you can change your logic such that the sub-query takes place in the from clause, so that it is only run once instead of once for each row returned by the main query.
Sub-queries really suck the performance out of a system.


text:
Q: Applet Web Deployment problems So basically I have made a Java applet that works 100% when I simply run the applet file directly, however when I attempt to have it run with a web service, it fails. I have discovered that by removing anything that uses external libraries seems to get it to function correctly.
I am using jClouds libraries and these seem to be the problem. Perhaps they are not being included the the .JAR used to run the applet in the web service. Is there any way to include all these external libraries so that the web service will function properly?
Im using netbeans to run and compile my programs in case that is relevent...

A: can you clarify the question on what exactly isn't working, and how you've isolated jclouds as the problem?  maybe a gist with code or how you are building things + an error?


text:
Q: passing the value in the textbox failed in selenium webdriver I am unable to pass the data in the textbox using selenium web-driver.
i have used xpath ,id,name but none of them are working.
driver.findElement(By.xpath("//input[@id='step2_portno_1']").sendKeys("80");
driver.findElement(By.id("step2_portno_")).sendKeys("80");

       > error:unable to locate the x path..

kindly help for the above issue.

A: The problem seems that selenium is not able to locate the element.
Once it gets the element, only then sendkeys would work.
Try below:

*

*Make sure that the element is appearing on the page when code is trying to locate it

*If the element is available but still 'unable to locate element' exception is thrown then make sure that the element is not inside any frame/iframe (You can check this by printing the page body on console using driver.getPageSource() and then manually searching element using ctrl + F.

*If the element is inside the frame then switch to that frame and then use finElement

*If the element is inside various Div then try to find div first and then search inside div.

Example:
   WebElement div1 = driver.findElement(By.id("myDiv"));
   WebElement myElement = div1.findElement(By.id("step2_portno_"));


text:
Q: Lumen first api request call take too much time After I deployed my Lumen project on a shared hosting server, I see that the first request takes too much time to give a response on the contrary of the upcoming requests.
After leaving the application for a while, it does the same thing again.
Please did someone have the same issue?
Ps: sorry for my bad English


text:
Q: Importing a SparkSession DataFrame on DSX I'm currently working on Data Science Experience and would like to import a CSV file as a SparkSession DataFrame. I am able to successfully import the DataFrame, however, all of the column attributes are converted to string type. How do you make this DSX feature recognize the types present in the CSV file?

A: Currently, the generated code for the actual creation of the pyspark.sql.DataFrame looks like this:
df_data_1 = spark.read\
  .format('org.apache.spark.sql.execution.datasources.csv.CSVFileFormat')\
  .option('header', 'true')\
  .load('swift://container_name.' + name + '/test.csv')
df_data_1.take(5)

You have to add the the following options, then the schema will be inferred:
.option(inferschema='true')\


text:
Q: Compiling CLD2 in Visual Studio I am trying to compile the chromium compact language detector in Visual Studio 2013. I am actually trying to create a .NET Wrapper for the library so I have added all the source files inside my CLR project.
Now whenever I compile I get these linking errors.
error LNK2005: "struct CLD2::CLD2TableSummary const CLD2::kCjkDeltaBi_obj" (?kCjkDeltaBi_obj@CLD2@@3UCLD2TableSummary@1@B) already defined in cld_generated_cjk_delta_bi_32.obj

These all seems to be related as I can see a relation between the 'generated' files.
Problem is I have a lot of these and I am not sure which ones I should exclude and which I should keep and use in my code.
Here is a list all the generated files that came with the CLD2 code.
cld_generated_cjk_uni_prop_80.cc
cld_generated_score_quad_octa_2.cc
cld_generated_score_quad_octa_0122.cc
cld_generated_score_quad_octa_0122_2.cc
cld_generated_score_quad_octa_1024_256.cc
cld_generated_cjk_delta_bi_4.cc
cld_generated_cjk_delta_bi_32.cc
cld2_generated_octa2_dummy.cc
cld2_generated_quad0122.cc
cld2_generated_quad0720.cc
cld2_generated_quadchrome_2.cc
cld2_generated_quadchrome_16.cc
cld2_generated_cjk_compatible.cc
cld2_generated_deltaocta0122.cc
cld2_generated_deltaocta0527.cc
cld2_generated_deltaoctachrome.cc
cld2_generated_distinctocta0122.cc
cld2_generated_distinctocta0527.cc
cld2_generated_distinctoctachrome.cc

The naming convention of these suggests that I should only be using one of each group. At least that how I think I should use it as I am not really an expert in encoding nor in how CLD2 works. And I could not find any references online explaining how to configure it.
I tried eliminating the linking errors by keeping only one of each generated group:
for example: from cld_generated_cjk_delta_bi_4 and cld_generated_cjk_delta_bi_32 I kept the 32 version. And so on for the rest of the files.
Now this made CLD compile yet when I tried testing it with languages I noticed that the scores were way way off and it was behaving inexplicably bad.
I am not trying to support all languages I only need to support latin languages along with hebrew, arabic, japanese and chinese.
Can someone please explain how to configure CLD2 to compile and work correctly.

A: I have created a CLR version of the Compact Language Detector 2.
You can either use it directly from the CLD2.Net nuget package or check the source.

A: Open the compile_libs.sh file in a text editor.  At the bottom, there are 2 g++ commands to compile the library, one for the regular CLD2 and another for the full version.  The files used will be listed with each.  Copy the header and source files for whichever library you are compiling (regular or full) into your project and build.  You may have to add _CRT_SECURE_NO_WARNINGS to eliminate errors.


text:
Q: System.Windows.Visibility Collapsed vs Hidden I have a control with Visibility set to "Collapsed" and a ToggleButton that changes the visibility between Visibility.Collapsed and Visibility.Hidden.  According to the  MSDN Documentation there should be no space allotted for the control within the layout when the control's Visibility is set to "Collaped," but there are no visual differences between the two enumerations. Additionally, the Visibility  of the control is initially set to Collapsed so the initial drawing of the controls should not allot any space for the control.
Is there a concept I am missing, or how do I get an element to take space only when visible?  My end-goal is to have controls appear on conditions based on user-selections that appear north of said display-varied controls, with consistent margins between all controls .
XAML Snippet:
<StackPanel>
    <TextBox Name="hideTest" DataContext="{StaticResource persistentMemoryBridge}"   Text="HIDETEST" Margin="0,327,31,491" Foreground="Black" Background="Orange" Visibility="Collapsed" />
    <TextBox DataContext="{StaticResource persistentMemoryBridge}"   Text="{Binding Path=PropertyTest}" Margin="0,386,31,432" Foreground="Black" Background="Yellow"/>
    <ToggleButton Name="tbVisibility" Content="Toggle" Click="ToggleButton_Click" Margin="0,445,65,391"></ToggleButton>
</StackPanel>

CodeBehind:
private void ToggleButton_Click(object sender, RoutedEventArgs e) {

        switch (hideTest.Visibility) {
            case System.Windows.Visibility.Collapsed: {
                hideTest.Visibility = Visibility.Hidden;
                tbVisibility.Content = "Hidden";
                break;
            }
        case System.Windows.Visibility.Hidden: {
            hideTest.Visibility = Visibility.Visible;
            tbVisibility.Content = "Visible";
            break;
            }
        case System.Windows.Visibility.Visible: {
            hideTest.Visibility = Visibility.Collapsed;
            tbVisibility.Content = "Collapsed";
            break;
            }
        }
    }

A: When contol's visibility is in Collapsed state its margins do not participate in the layout (contrary to Hidden state)
Can be verified easily:
<Window x:Class="MarginsRespectForCollapsedTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Button Margin="50,50" Visibility="Collapsed">I'm Collapsed</Button>
        <Button>I'm Visible!</Button>
    </StackPanel>
</Window>

I agree with HighCore that you XAML really looks like you just dragged controls from the toolbox panel. VS's XAML designer has this unpleasant feature: it tries to position controls with the help of margins.


text: Q: Can I send files using discord webhooks? So I'm coding an application in python which should send messages via Discord Webhooks. I would like it to be able to send files. Is it possible and how do I do it?


text:
Q: Problem with setLayoutParams method in android UI I am making an application in which I have to change the UI programmaticaly.
I needed to change the layout_height and layout_width XML attributes.
But when I use the setLayoutParams method, the app runs and then I give a message that it has unexpectedly stopped working and I have to force close.
I have tried setting the LayoutParams as ViewGroup.LayoutParams as well.
But nothing works. Kindly check the attached code and guide.
This is the Java Code.
private void fixLayoutVmain(){
    ListView lv;
    ImageButton rev,stop,play,forw;
    lv=(ListView)findViewById(R.id.ListMain);
    rev=(ImageButton)findViewById(R.id.rev);
    stop=(ImageButton)findViewById(R.id.stop);
    play=(ImageButton)findViewById(R.id.plpa);
    forw=(ImageButton)findViewById(R.id.forw);
    Log.d("DEV1","ID's have been assigned");
    LayoutParams lp=new LayoutParams(W, ((75*H)/100));
    Log.d("DEV1","param object created");
    lv.setLayoutParams(lp);
    Log.d("DEV1","ListView param set");
    lp.height=(int)(10*H)/100;
    lp.width=(int)(10*H)/100;
    Log.d("DEV1","Changes to param made");
    rev.setLayoutParams(lp);
    Log.d("DEV1","Reverse Button param applied");
    stop.setLayoutParams(lp);
    Log.d("DEV1","Stop button param applied");
    play.setLayoutParams(lp);
    Log.d("DEV1","forward button param applied");
    forw.setLayoutParams(lp);
    Log.d("DEV1","All imagebutton changes have been made");

}

This is the XML File
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListVieW
        android:id="@+id/ListMain"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="bottom">
            <ImageButton
                android:id="@+id/rev"
                android:src="@drawable/reverseimg"
                android:background="@null"
                android:scaleType="fitXY" />
            <ImageButton
                android:id="@+id/stop"
                android:src="@drawable/stopimg"
                android:background="@null"
                android:scaleType="fitXY" />
            <ImageButton
                android:id="@+id/plpa"
                android:src="@drawable/playimg"
                android:background="@null"
                android:scaleType="fitXY" />
            <ImageButton
                android:id="@+id/forw"
                android:src="@drawable/forwardimg"
                android:background="@null"
                android:scaleType="fitXY" />
    </LinearLayout>
</LinearLayout>

A: It looks like your application crashes because you have not supplied android:layout_width and android:layout_height to your ImageButtons.
Even if you are going to set the width and height in code, you need to add these parameters to your xml-file for each ImageButton:
<ImageButton
  android:id="@+id/rev"
  android:src="@drawable/reverseimg"
  android:background="@null"
  android:scaleType="fitXY"
  android:layout_height="0dp"
  android:layout_width="0dp"
    />

A: Any time you set LayoutParams, check the parent container of the View. In all your instances, the parent is a LinearLayout. You need to use LinearLayout.LayoutParams, like so:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
lv.setLayoutParams(lp);

Whether that's your particular force close issue or not, we have no way of knowing. As stated in the comments, you should check LogCat and post the exception details here. Give this a try though, and see if it fixes the problem.

A: I checked again and made both the changes as told in the above answers.
It still didn't work.
However i found out that i was executing the function before i used setContentView() method.
Since the view hadn't been created, alterations could not be made.
So putting my function after the setContentView() method made it work fine.
Thanks anyways.


text:
Q: How to develop SIP (VOIP) application I developed sip application in Android. and now I am developing it in Windows Phone 8. I am new in Windows phone and don't know anything that Which library should be use here? Do Microsoft provide free library for SIP?
Please any suggest me Which way will be best for developing or any source code or library or demo application?

A: I think you can start from this example.
There is a full sample app there.

A: Take a look at boghe, it's the SIP video client for Windows Phone 8 and Surface Pro. You'll learn a lot from there.
It also cover VoIP apps for Windows Phone 8, which teaches you to integrate VoIP into WP8 experience


text:
Q: Lombok sl4fj: How to change console logger lvl I started to work on a bot for binance treading. I am using this wrapper library.
This wrapper is using:
import lombok.extern.slf4j.Slf4j;

for logging it looks like this in code:
@Slf4j
@Data
public class BinanceApi {
...
}

Right now it is displaying a lot of information that I don´t want to be displayed. I want to  change consoleAppender level for displaying only error level logs.
I have found this Project Lombok @Slf4j external configuration
But it's not helping me.
How can I do that?

A: The log level for the output is not configured with Lombok, but with the used logging framework. SLF4J is a facade for Java logging frameworks. This is the explanation from  https://www.slf4j.org/

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.

To change the output log level, you have to figure out which of the logging frameworks is used and then look up on how to configure the log level for that log framework. Starting points could be the dependencies of the project or existing logging configurations.


text:
Q: How can I store lots of strings with different lengths in the same char array without specifying its size? I'll implement a dictionary that is basically an array of structures.
Here's the structure:
struct WORD {
    char* word;
    struct WORD* next;
};

And the array that'll help me reach them:
struct WORD* dictionary[26];

The number 26 stands for 26 letters of the alphabet. We need a linked-list for every single letter, bu that is irrelevant now.
The problem is, I need the char* variable in the structure to be able to store words of different lengths. If I leave it as char*, fscanf fuction doesn't work while reading the words from the file onto the structure. If I make it char word[10] for example, I'd be wasting space for shorter words.
What am I supposed to do?

A:
If I leave it as char*, fscanf function doesn't work

You need to leave it as char*, and dynamically allocate the string.
Start with a buffer of some large size, say, 1024. Read the word into that buffer using fscanf with a limit. After that, copy the buffer into a dynamically allocated space for the word:
char buf[1024];
WORD *head = NULL;
while (fscanf(f, "%1023s", buf) == 1) {
    size_t len = strlen(buf);
    if (!len) continue; // Ignore empty words
    WORD *node = malloc(sizeof(WORD));
    // Copy the word
    node->word = malloc(len+1); // One for '\0' terminator
    strcpy(node->word, buf);
    // Attach as the new head
    node->next = head;
    head = node;
}

Note: You can score some points for style with flexible array member: make word an array with no size, and allocate it together with the node itself, like this:
struct WORD {
    struct WORD* next;
    char word[];
};
...
char buf[1024];
WORD *head = NULL;
while (fscanf(f, "%1023s", buf) == 1) {
    size_t len = strlen(buf);
    if (!len) continue; // Ignore empty words
    WORD *node = malloc(sizeof(WORD)+len+1);
    // Copy the word
    strcpy(node->word, buf);
    // Attach as the new head
    node->next = head;
    head = node;
}

Now you have a single allocation instead of two.

A: You can use a temporary buffer with a fixed length and store the word there, so that you can figure out the length. Once you figured out the length, use malloc to allocate the exact number of bytes to the word pointer, and copy it. something like this:
char tempBuffer[20 + 1] = {0}; //Null terminates the string
fsanf(file, "%s", tempBuffer); // read the string
word = (char*) malloc(sizeof(char) * strlen(tempBuffer));  //allocate memory
strcpy(word, (char*) tempBuffer); //copy the string

A: You will need to allocate your string dynamically. The function scanf() can do this for you using the m format specifier (on POSIX systems that have implemented this feature).
Here is an example:
#include <stdio.h>  /* printf, scanf */
#include <stdlib.h> /* free, EXIT */

int main(void)
{
  char *str;

  fscanf(stdin, "%ms", &str); /* Replace stdin with your FILE * */
  printf("%s", str);
  free(str);
  return EXIT_SUCCESS;
}

Of course you may have noted you need to pass a pointer of your char array to the scanf function so the array can be allocated.
man 3 scanf

An optional 'm' character. This is used with string conversions (%s,
  %c, %[), and relieves the caller of the need to allocate a
  corresponding buffer to hold the input: instead, scanf() allocates a
  buffer of sufficient size, and assigns the address of this buffer to
  the corresponding pointer argument, which should be a pointer to a
  char * variable (this variable does not need to be initialized before
  the call). The caller should subsequently free(3) this buffer when it
  is no longer required.

Edit:
As mentioned in comments, the m flag does not exist in standard C.
The best way I can think of would be read the input using a buffer & realloc.
Or you could simply use POSIX's getline() function to get the input (which allocates the string by itself if you need it to).


text:
Q: How many RAM Hardfaults is too many? Trying to play BF3, sometimes seemingly randomly, it will start lagging.
I assumed despite 4GB of RAM, it might be hitting its max.
I just however noticed a lot of RAM Hardfaults. Is this a lot, or normal?
Would it affect my game, or is it lack of RAM?
Note: the game is loading up at this point, so is not at its near max. Which I think runs at 90+% at all times when plying bf3.


text:
Q: Establishing client VNC connection over SSH in one step (e.g., with the -via option) How do I reduce these two commands to one? I am connecting from my client to an x11vnc server and the two commands below already work. I just wish to do it in one step:
first command:
ssh -fNL 5901:localhost:5678 -i ~/.ssh/some_id_rsa rocky@example.com

and second:
vncviewer localhost:5901

From reading the man page, it seems like the -via option might do it. Unfortunately, the man page leaves me very confused. For reference (not that I understand it) here is what my man page says:
   -via gateway
          Automatically create encrypted TCP tunnel to the gateway machine before con‐
          nection, connect to the host through  that  tunnel  (TightVNC-specific).  By
          default,  this  option  invokes SSH local port forwarding, assuming that SSH
          client binary can be accessed as /usr/bin/ssh. Note that when using the -via
          option,  the  host  machine name should be specified as known to the gateway
          machine, e.g.  "localhost"  denotes  the  gateway,  not  the  machine  where
          vncviewer  was  launched.  The environment variable VNC_VIA_CMD can override
          the            default             tunnel             command             of
          /usr/bin/ssh -f -L "$L":"$H":"$R" "$G" sleep 20.  The tunnel command is exe‐
          cuted with the environment variables L, H, R, and G taken the values of  the
          local  port number, the remote host, the port number on the remote host, and
          the gateway machine respectively.

A: This is what the man page is trying to say. I have the following setup.
  vncviewer         .-,(  ),-.
   __  _         .-(          )-.           gateway           vncserver
  [__]|=|  ---->(    internet    )-------> __________ ------> ____   __
  /::/|_|        '-(          ).-'        [_...__...°]       |    | |==|
                     '-.( ).-'                               |____| |  |
                                                             /::::/ |__|

NOTE: The above diagram was done using asciio.
The vncviewer is running from my laptop. From my laptop I can run the following command and connect to the vncserver which is behind my router:
$ vncviewer vncserver_host:0 -via mygateway.mydom.com

This will instantly connect me to the vncserver. This command is shown on my laptop which helps to show what the man page is trying to explain:
/usr/bin/ssh -f -L 5599:vncserver_host:5900 mygateway.mydom.com sleep 20

This is the command that vncviewer is automatically constructing when you use the -via gateway switch.
including ssh configurations
You can make use of the ~/.ssh/config file and put entries in this file like this:
Host *
IdentityFile ~/.ssh/id_dsa

Or you can target a specific host like this:
Host mygateway
    User sam
    HostName mygateway.mydom.com
    IdentityFile ~/.ssh/someother_id_rsa

This will allow you to leverage the Host entries in this file like this:
$ vncviewer vncserver_host:0 -via mygateway


text:
Q: Is there a formal name for when the same word appears twice (or more) in a row? Sometimes I read, write or speak a sentence where a single word appears twice in a row. For example:

The book he had had a torn cover.

I was curious if there was a formal term for such a pattern.
Thanks

A: There is a name for it, anadiplosis, but it is often used for emphasis.
(i.e. Fear leads to Anger; Anger leads to Hate; Hate leads to suffering  ~ Yoda)

A: When it's done accidentally it is called 'dittography':

Dittography is the accidental, erroneous act of repeating a letter, word, phrase or combination of letters by a scribe or copyist.

A: Repetitious words.
Repetitious words used in a sentence are generally frowned upon unless used as a way of purposely trying to create emphasis. It is better for readability to vary the usage of words and leave out unnecessary repetitious words. Try to use any other word in its place.


text:
Q: Redirect command prompt output to a python generated window Developed a script which builds a project using msbuild. I have GUI developed using wxpython which has a button on which when user clicks would build a project using msbuild. Now, i want to open a status window when user click on that button and shows all the output which shows in the command prompt and command prompt should not be displayed i.e,redirecting the command prompt output to the user GUI status window. My build script is,
def build(self,projpath)
    arg1 = '/t:Rebuild'
    arg2 = '/p:Configuration=Release'
    arg3 = '/p:Platform=x86'
    p = subprocess.call([self.msbuild,projpath,arg1,arg2,arg3])
    if p==1:
        return False
    return True

A: I actually wrote about this a few years ago on my blog where I created a script to redirect ping and traceroute to my wxPython app: http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/
Basically you create a simple class to redirect stdout to and pass it an instance of a TextCtrl. It ends up looking something like this:
class RedirectText:
    def __init__(self,aWxTextCtrl):
        self.out=aWxTextCtrl

    def write(self,string):
        self.out.WriteText(string)

Then when I wrote my ping command, I did this:
def pingIP(self, ip):
    proc = subprocess.Popen("ping %s" % ip, shell=True,
                            stdout=subprocess.PIPE)
    print
    while True:
        line = proc.stdout.readline()
        wx.Yield()
        if line.strip() == "":
            pass
        else:
            print line.strip()
        if not line: break
    proc.wait()

The main thing to look at is the stdout parameter in your subprocess call and the wx.Yield() is important too. The Yield allows the text to get "printed" (i.e. redirected) to stdout. Without it, the text won't show up until the command is finished. I hope that all made sense.

A: I made a change like below,it did work for me.
def build(self,projpath):
    arg1 = '/t:Rebuild'
    arg2 = '/p:Configuration=Release'
    arg3 = '/p:Platform=Win32'
    proc = subprocess.Popen(([self.msbuild,projpath,arg1,arg2,arg3]), shell=True,
                    stdout=subprocess.PIPE)
    print
    while True:
        line = proc.stdout.readline()
        wx.Yield()
        if line.strip() == "":
            pass
        else:
            print line.strip()
        if not line: break
    proc.wait()


text:
Q: Interpolate between elements in an array of floats I'm getting a list of 5 floats which I would like to use as values to send pwm to an LED. I want to ramp smoothly in a variable amount of milliseconds between the elements in the array.
So if this is my array...
list = [1.222, 3.111, 0.456, 9.222, 22.333]

I want to ramp from 1.222 to 3.111 over say 3000 milliseconds, then from 3.111 to 0.456 over the same amount of time, and when it gets to the end of the list I want the 5th element of the list to ramp to the 1st element of the list and continue indefinitely.

A: do you think about something like that?
import time
l = [1.222, 3.111, 0.456, 9.222, 22.333]

def play_led(value):
    #here should be the led- code
    print value

def calc_ramp(given_list, interval_count):
    new_list = []
    len_list = len(given_list)
    for i in range(len_list):
        first = given_list[i]
        second = given_list[(i+1) % len_list]
        delta = (second - first) / interval_count
        for j in range(interval_count):
            new_list.append(first + j * delta)
    return new_list

def endless_play_led(ramp_list,count):
    endless = count == 0
    count = abs(count)

    while endless or count!=0:
        for i in range(len(ramp_list)):
            play_led(ramp_list[i])
            #time.sleep(1)
        if not endless:
            count -= 1
        print '##############',count

endless_play_led(calc_ramp(l, 3),2)
endless_play_led(calc_ramp(l, 3),-2)
endless_play_led(calc_ramp(l, 3),0)

A: another version, similar to the version of dsgdfg (based on his/her idea), but without timing lag:
import time
list_of_ramp = [1.222, 3.111, 0.456, 9.222, 22.333]

def play_LED(value):
    s = ''
    for i in range(int(value*4)):
        s += '*'
    print s, value

def interpol(first, second, fract):
    return first + (second - first)*fract

def find_borders(list_of_values, total_time, time_per_step):
    len_list = len(list_of_values)
    total_steps = total_time // time_per_step
    fract = (total_time - total_steps * time_per_step) / float(time_per_step)
    index1 = int(total_steps % len_list)
    return [list_of_values[index1], list_of_values[(index1 + 1) % len_list], fract]

def start_program(list_of_values, time_per_step, relax_time):
    total_start = time.time()
    while True:
        last_time = time.time()
        while time.time() - last_time < relax_time:
            pass
        x = find_borders(list_of_values,time.time(),time_per_step)
        play_LED(interpol(x[0],x[1],x[2]))

start_program(list_of_ramp,time_per_step=5,relax_time=0.5)


text:
Q: Show each array values in input box if they are set If i had enter all value in say four input boxes with name prod[] and when i click on the submit button, i want to show each values without loosing it if the array values are isset.
<?php for($i=1; $i<=8; $i++) { ?>

<input type="text" class="form-control" name="PprodName[]" />

A: @QaisarSatti
thanks bro but i think i just got the logic. here is my code :
<?php
    $j = 0;
    for($i = 1; $i<=8; $i++) {
?>

        <input type="text" class="form-control" id="Ppr<?php echo $i; ?>" name="PprodName[]" value="<?php echo isset( $_POST['PprodName'][$j] ) ? $_POST['PprodName'][$j] : ''; ?>" />

<?php $j++; } ?>

mark this checked if you found it useful. thanks !

A: $name = $_POST['PprodName'];

foreach( $name as $v ) {
echo $v;
}


text:
Q: Скрытие уведомления и остановка работы Location Manager при выключении навигатора Хочу повторить логику Google Map. Когда использую навигатор, нужно обновлять карту в background. Для этого использую NSLocationWhenInUseUsageDescription, и у меня появляется синяя шапка, которая говорит, что программа использует локацию:

Когда человек выключил навигатор, мне нет смысла отслеживать его передвижение. Как мне убрать эту синюю шапку и остановить работу Location Manager в background?
Когда навигатор не работает, мне нужно, чтобы локация обновлялась, только когда приложение активно.
Программу пишу на Swift, но Objective-C тоже знаю, так что можно это сделать на любом из этих языков.

A: Вам нужно в контроллере получить уведомление, о том, что приложение свернуто. Это часть показана тут https://stackoverflow.com/questions/25716012/triggering-a-specific-action-when-the-app-enters-foreground-from-a-local-notifi
В AppDelegate добавить 2 обработчика
func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    }


text:
Q: Link Email to Google Task I am creating tasks from email similar to this. In addition I want to link the corresponding message, just like it happens when you create a task from email manually.
This example creates as task with the correct title and due date, but no link to the message is incorporated.
//new Task
var newTask = Tasks.newTask();

//set Title
newTask.setTitle("Task Title");

//set DueDate
var dueDate = new Date();
newTask.setDue = (dueDate.toISOString());

//set Link
var taskLink = Tasks.newTaskLinks()
.setType("email")
.setLink("https://url-to-my-message");
newTask.setLinks(taskLink);

//insert task
newTask = Tasks.Tasks.insert(newTask, "MyListID");

I noted that the links property is readonly (why???). Any other way to achieve this?

A: It looks like at the moment, there's no way to link an email to a task via the API.  At the Tasks API level, it states that the links parameter is read-only, and since Google Apps Scripts use the API, there's no way for them to set this property.  Sad, I know.  You'll probably have to wait until they move the Tasks API out of "Experimental" status.
https://developers.google.com/google-apps/tasks/v1/reference/tasks#resource

A: Here is a work around to this issue, which I have been exploring.
Please note that the answer given by LukeGT is correct, and my answer below is work around to give you the ability to have the same functionality which currently Google has not exposed.
For those who want to know more about the whole concept of creating Google Tasks form a set of emails, I recommend this excellent tutorial which got my ball rolling on this topic.
The basic idea is to place the email link into the Task title rather than as the above 'email' links.
To make it a little more concise, I use the Google Url Shortener service so as to render the Task title shorter.  Works fine for me, here is the code... (please note that you can get the link to a mail via this example, you'll also need to authorise the Url Shortener service).
var emailURL = "https://url-to-my-message";
var url = UrlShortener.Url.insert({
  longUrl: emailURL
});
var taskDetails = {
  title: 'My email task: '+url.id,
  notes: "Check the link for details",
};
Tasks.Tasks.insert(taskDetails, "MyListID");

and here is what it looks like... ( i.stack.imgur.com/hZWHF.png, sorry, but can't post images as yet)

A: For those looking to see how Aurovrata's 'work around' would integrate directly into the gmail tasks solution linked in twjstoll's post, the following has worked well for me.
// Construct the url string
// Shorten the URL
var emailURL = "https://mail.google.com/mail/u/0/#inbox/"+thread.getId();
var url = UrlShortener.Url.insert({
  longUrl: emailURL
});

// Insert the task
addTask_(taskTitle + " " + url.id, taskNote, TASKLIST);

Thanks to all those who helped.


text:
Q: How can I control the frequency about how snakemake submitting the job? Now, I'm using snakemake cluster to execute with my own k8s.
When submitting the task, the command looks like:
export TMP=/k8s &&  snakemake --cluster "lsub" --cluster-config cluster-config.yaml -j 2
The brief lsub script logic:

*

*read the parameters from snakemake

*submit a k8s job via:
cat <<EOF | kubectl create -f -
xxxxxxxx
EOF
(the origin sub-step shell from snakemake is included in command section in xxxxxxxxx)

Due to the k8s environment's throttling policy, I cannot submit too many jobs concurrently. However, it seems that snakemake cannot control it's submitting behavior.(I can control the first step. However, I cannot control the follow-up step)
My idea is changing the lsub script to control the frequency. However, I have no idea about it since I don't know how snakemake read the job status.
So, any suggestion about this situation?

A: I think you are looking for the --max-jobs-per-second option.  If you set that to 0.1 snakemake will submit a job every 10 seconds.
If instead you mean the number of jobs snakemake will actively submit, you want to modify the --jobs option.  --jobs 100 will make sure only 100 jobs are running (submitted) at once.


text:
Q: $h \circ g $ is 1-1 and onto $g$ is 1-1 and onto $h$ is onto - how to prove that $h$ is 1-1 too? $h \circ g $ is 1-1 and onto
$g$ is 1-1 and onto
$h$ is onto
I am trying to prove that $h$ is 1-1 too.
$h \circ g(x1) $ =$h \circ g(x2) \rightarrow  x1=x2 $   And due to the fact that $g$ is onto, therefore h is 1-1 too.
I can not find the way to write "And due to the fact that $g$ is onto, therefore h is 1-1 too." in a formal way.
Thanks

A: Hint
Let $h(x_1)=h(x_2)$. Pick $y_1$ such that $g(y_1)=x_1$. Pick $y_2$ such that $g(y_2)=x_2$. Then, what can you say about $h(g(y_1))$ and $h(g(y_2))$?


text:
Q: why doesn't offset work in plotly go.Bar() when axis is datetime? With go.Bar() one can pass an offset parameter that shifts the position of a bar within the group (barmode is set to 'overlay' for traces with an offset).
This works fine when the x-axis is numeric:

but seems to not work when the x-axis is of datetime format:

Is this a bug or a feature? and can offsets work with datetime axes?
import plotly.graph_objects as go
import datetime
from datetime import timedelta
import pandas as pd
from random import random

# generage a datetime index

dates = [datetime.date(2022,10,10) + timedelta(x) for x in range(10)] # datetime index
# dates = range(10) # a list of int; uncomment to see offset

fig = go.Figure()

for i in range(3):
    s = pd.Series(
        [5*(random()-0.5) for x in range(len(dates))], # random values
        index = dates
    )

    fig.add_trace(
        go.Bar(
            x = s.index,
            y = s,
            offset = 0.15*(i-1),  # has no effect with datetime index
        )
    )

fig.show()

A: The offset is given in axis units.
When the axis is of type datetime, apparently the unit is a nanosecond (1ns = 1e-9 seconds)
So to notice an offset, you should adjust the magnitude of the offset accordingly.
If you set
offset = 1e7*(i-1),
width = 2e7 # also in axis units

you get:


text:
Q: I am getting the following exception while launching face book using chrome browser in Selenium can any one suggest me the solution for this
Exception in thread "main" java.lang.IllegalStateException: The path
  to the driver executable must be set by the webdriver.chrome.driver
  system property; for more information, see
  https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest
  version can be downloaded from
  http://chromedriver.storage.googleapis.com/index.html     at
  com.google.common.base.Preconditions.checkState(Preconditions.java:199)
    at
  org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:109)
    at
  org.openqa.selenium.chrome.ChromeDriverService.access$0(ChromeDriverService.java:1)
    at
  org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
    at
  org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:296)
    at
  org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
    at
  org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:116)
    at New.HelloWorld.main(HelloWorld.java:16)

A: You need to use this code to set the location of chromedriver before initializing the driver. Use the method setProperty(String key, String path):
System.setProperty("webdriver.chrome.driver", "/tpt/chromedriver.exe");


text:
Q: How to flag active customers who have at least one transaction per month? Objective is to create a flag for active customers.
An active customer is someone who has atleast one transaction every month.
Time frame - May 2018 to May 2019
Data is at transaction level
-------------------------------------
txn_id | txn_date | name | amount
-------------------------------------
101     2018-05-01  ABC    100
102     2018-05-02  ABC    200
-------------------------------------

output should be like this -

----------------
name | flag
----------------
ABC    active
BCF    inactive

A: You can use aggregation to get the active customers:
select name
from t
where txn_date >= '2018-05-01' and txn_date < '2019-06-01'
group by name
having count(distinct last_day(txn_date)) = 13  -- all months accounted for

EDIT:
If you want a flag, just move the condition to a case expression:
select name,
       (case when count(distinct case when txn_date >= '2018-05-01' and txn_date < '2019-06-01' then last_day(txn_date) end) = 13
             then 'active' else 'inactive'
        end) as flag
from t;


text:
Q: reading large file and splitby method I'm trying to use the splitby method in highland.js to extract the data between the begin and end delimiters.
        -----BEGIN DATA-----
        MIIEzDCCArSgAwIBAgIVCugKYzMN5ra8zPWxYE8pUU9SxjYSMA0GCSqGSIb3DQEB
        CwUAMHAxCzAJBgNVBAYTAkdCMRUwEwYDVQQIDAxXYXJ3aWNrc2hpcmUxEDAOBgNV
        BAcMB1dhcndpY2sxEDAOBgNVBAoMB0VudHJ1c3QxETAPBgNVBAsMCFBLSSBURUFN
        -----END DATA-----
        -----BEGIN DATA-----
        MIIETzCCAjegAwIBAgIVBShP2Mx74DZEyNKwYZZPGntRmSWnMA0GCSqGSIb3DQEB
        DQUAMHIxCzAJBgNVBAYTAkdCMRUwEwYDVQQIDAxXYXJ3aWNrc2hpcmUxEDAOBgNV
        BAcMB1dhcndpY2sxDDAKBgNVBAoMA0lCTTERMA8GA1UECwwIUEtJIFRFQU0xGTAX
        5/62
        -----END DATA-----

I can read the file into a stream like this:
        const readFile = _.wrapCallback(fs.readFile);
        stream = _(files).map(readFile).parallel(2);

        const blob = _(stream).splitBy('-----BEGIN DATA-----')

However, I can't seem to work out how to process the file and extract the data I need.

A: There are really three concerns here.

*

*Reading the content data from files

*Extracting the delimited chunks

*Getting the resulting data out of the stream

First you need to read the contents of each file. Note that wrapped readFile will emit Buffers, not Strings. To extract chunks you need to convert content of each file to a String. I assume files are encoded as utf-8.
Second you need to separate the data from the rest of the text. I assume that you only want chunks between the beginning and end delimiters, without delimiters themselves or anything that might be outside of the delimiters, for example:
-----BEGIN DATA-----
MIIEzDCCArSgAwIBAgIVCugKYzMN5ra8zPWxYE8pUU9SxjYSMA0GCSqGSIb3DQEB
CwUAMHAxCzAJBgNVBAYTAkdCMRUwEwYDVQQIDAxXYXJ3aWNrc2hpcmUxEDAOBgNV
BAcMB1dhcndpY2sxEDAOBgNVBAoMB0VudHJ1c3QxETAPBgNVBAsMCFBLSSBURUFN
-----END DATA-----
junky junk junk
-----BEGIN DATA-----
MIIETzCCAjegAwIBAgIVBShP2Mx74DZEyNKwYZZPGntRmSWnMA0GCSqGSIb3DQEB
DQUAMHIxCzAJBgNVBAYTAkdCMRUwEwYDVQQIDAxXYXJ3aWNrc2hpcmUxEDAOBgNV
BAcMB1dhcndpY2sxDDAKBgNVBAoMA0lCTTERMA8GA1UECwwIUEtJIFRFQU0xGTAX
5/62
-----END DATA-----

should result in:
[ '\nMIIEzDCCArSgAwIBAgIVCugKYzMN5ra8zPWxYE8pUU9SxjYSMA0GCSqGSIb3DQEB\nCwUAMHAxCzAJBgNVBAYTAkdCMRUwEwYDVQQIDAxXYXJ3aWNrc2hpcmUxEDAOBgNV\nBAcMB1dhcndpY2sxEDAOBgNVBAoMB0VudHJ1c3QxETAPBgNVBAsMCFBLSSBURUFN\n'
, '\nMIIETzCCAjegAwIBAgIVBShP2Mx74DZEyNKwYZZPGntRmSWnMA0GCSqGSIb3DQEB\nDQUAMHIxCzAJBgNVBAYTAkdCMRUwEwYDVQQIDAxXYXJ3aWNrc2hpcmUxEDAOBgNV\nBAcMB1dhcndpY2sxDDAKBgNVBAoMA0lCTTERMA8GA1UECwwIUEtJIFRFQU0xGTAX\n5/62\n'
]

To get this result I use regular expression with two non-matching groups for delimiters and a matching group for the data. First I extract the delimited chunks, then remove delimiters. This may not be very efficient, but should do the job.
Note that the callback of flatMap will return an array of strings. Using map here would result in a stream of arrays - one for every file. What we want is a single stream of strings. That's why flatMap` is used here.
Finally you need to get the stream flowing and get the data out of it. To do this you need to call a consuming method on the stream. In this example I use toArray. The callback provided to this method will be called with an array containing all elements of the stream - in this case all your data chunks.
Here is the thing in it's entirety:
const Stream = require("highland")
const FS = require("fs")

const files = [ "./input-1.txt", "./input-2.txt"  ]
const readFile = Stream.wrapCallback(FS.readFile);

const pattern = /(?:-----BEGIN DATA-----)((.|\n)+?)(?:-----END DATA-----)/gm

Stream(files)
  // 1. Read contents
  .map(readFile)
  .parallel(2)
  .invoke("toString", ["utf-8"])
  // 2. Process contents to extract data
  .flatMap((content) =>
    content
      // get an array of chunks (including delimiters)
      .match(pattern)
      // remove the delimiters from each chunk, leaving only the data
      .map((chunk) => chunk.replace(pattern, "$1")))
  // 3. Get the resulting data out of the stream
  .toArray((chunks) =>
    console.log(chunks) // will print an array of data chunks
  )