text:
Q: Added maven/intellij for existing java project and it's not rebuilding all jar files I'm new to intellij idea and maven, and we recently added/used it to build a legacy java project. The original developers have left the company and I haven't used java in 20 years and didn't use these tools, and frankly it was in college (things have changed).  We got the project building, and dependencies are resolved, and it has a pom.xml file now, and it generates a jar file according to the artifactId and version in the pom file, in the target dir, and it's 18 kb.  However, the original jar file has not rebuilt, and I can see it in a higher project dir and it's 5049 kb.  That 5049 kb jar file is what was living on the server (*and it's not rebuilding). We are updating the server name/cred in a file that, and I'm concerned that the 5049 kb file needs to rebuild to reflect the modified cred ini file.  I'm not sure if it makes a difference, but this is the project dir structure:
*ServiceNow
   DbCred.ini
   ServiceNowTask

   SourceCode

   ServiceNowTAsk
    src
       main>java>Task>ServiceNowTask>old java files to build
    target
      ServiceNowTAsk-1-snapshot.jar (new date, 18 kb)
    .classpath
    .project
    pom.xml
    ServiceNowTask.iml
    ServiceNowTask.jar (old date, 5049 kb)

(read this, ServiceNow is the main dir, with DbCred and ServiceNowTask under it, and under ServiceNowTask is SourceCode, and under that is ServiceNowTask, src, target, ServiceNowTask.iml, ServiceNowTask.jar. etc.)
There are other ServiceNow projects at the level of ServiceNowTask, and each contains java files with main, so I think they need to be built separately to create the separate jar files.
The pom file looks like this (do I need to add ServiceNowTask.jar to the pom file?):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>Task</groupId>
  <artifactId>ServiceNowTask</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>ServiceNowTask</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>18</java.version>
      <maven.compiler.source>18</maven.compiler.source>
      <maven.compiler.target>18</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1.1</version>
   </dependency>
      <dependency>
          <groupId>org.ini4j</groupId>
          <artifactId>ini4j</artifactId>
          <version>0.5.4</version>
      </dependency>

  </dependencies>
</project>

My question is, how do I get it to rebuild all jar files, specifically that 5049 kb one that isn't rebuilding?
Update
I changed the pom file to this but there are errors:
[ERROR] Malformed POM C:\Users\xxx\OneDrive - Company, Inc\Documents\2022\Java\ServiceNow\ServiceNowTask\SourceCode\ServiceNowTask\pom.xml: Unrecognised tag: 'packaging' (position: START_TAG seen ...</version>\r\n              <packaging>... @11:26)  @ C:\Users\xxx\OneDrive - Company, Inc\Documents\2022\Java\ServiceNow\ServiceNowTask\SourceCode\ServiceNowTask\pom.xml, line 11, column 26
[FATAL] 'groupId' is missing. @ line 2, column 102
[FATAL] 'artifactId' is missing. @ line 2, column 102
[FATAL] 'version' is missing. @ line 2, column 102
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project [unknown-group-id]:[unknown-artifact-id]:[unknown-version] (C:\Users\xxx\OneDrive - Company, Inc\Documents\2022\Java\ServiceNow\ServiceNowTask\SourceCode\ServiceNowTask\pom.xml) has 4 errors
[ERROR]     Malformed POM C:\Users\xxx\OneDrive - Company, Inc\Documents\2022\Java\ServiceNow\ServiceNowTask\SourceCode\ServiceNowTask\pom.xml: Unrecognised tag: 'packaging' (position: START_TAG seen ...</version>\r\n              <packaging>... @11:26)  @ C:\Users\xxx\OneDrive - Company, Inc\Documents\2022\Java\ServiceNow\ServiceNowTask\SourceCode\ServiceNowTask\pom.xml, line 11, column 26 -> [Help 2]
[ERROR]     'groupId' is missing. @ line 2, column 102
[ERROR]     'artifactId' is missing. @ line 2, column 102

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

    <build>
        <plugins>
            <plugin>
              <groupId>Task</groupId>
              <artifactId>ServiceNowTask</artifactId>
              <version>0.0.1-SNAPSHOT</version>
              <packaging>jar</packaging>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>assemble-all</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
</build>
  <name>ServiceNowTask</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>18</java.version>
      <maven.compiler.source>18</maven.compiler.source>
      <maven.compiler.target>18</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1.1</version>
   </dependency>
      <dependency>
          <groupId>org.ini4j</groupId>
          <artifactId>ini4j</artifactId>
          <version>0.5.4</version>
      </dependency>

  </dependencies>
</project>


text:
Q: Drawing altered by screen mode (portrait or landscape) I'm porting a game from JME to Android and I found an annoying problem. The next activity must draw a grid, and in fact it does. But the grid appear OK just in landscaping mode. When you put the phone vertical (in portrait mode) it appears strangely compressed.
The main code is the method used to draw a cells row, (getSquareRow)
Thanks in advance for any help.
Here is the code:
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class TraxActivity extends Activity {
    InternalView myView;
    private float shift, di;
    private float n, minim, redux, side;
    boolean first = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        myView = new InternalView(this);
        setContentView(myView);
    }

    private class InternalView extends View{
        public InternalView(Context context){
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint paint = new Paint();

            n=5;
            di=12;
            int ancho = getWidth();
            int alto = getHeight();
            minim = Math.min(getWidth(), getHeight());
            redux = minim*9/10;
            shift = (getWidth() - redux)/2;
            side = redux/n;

            //background
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.BLUE);
            canvas.drawPaint(paint);

            //grid
            for(int j=0; j < n; j++){
                getSquareRow( canvas, j, paint);
            }

        }

        public void getSquareRow(Canvas g, int row, Paint p){

            p.setColor(Color.BLACK);
            p.setStyle(Paint.Style.STROKE);
            p.setStrokeWidth(10);

            for(int i=0; i < n; i++){
                g.drawRect(shift+i*side, shift+row*side, side, side, p );
            }

        }

    }
}

A: Thanks guys, I'll be targeting the game just for landascaping mode. Althought  I agree with alextsc but in this case looks like Android platform doesn't redraw accurately in portrait mode.
I can't to publish an image because I'm newbie posting here, but running this code you can check the anomaly and seems be related with the method drawRect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I find the Prices for different RDS Instance Classes using the Pricing API in Boto3 AWS? So I started by trying to find the service code for RDS instances to use with the pricing API's .get_products() method. But when I used .describe_servies() and went through there list of services, I couldn't find a service for RDS instances. So is there a method through Boto3 to find the on-demand price of each rds instance?
I was trying to replicate something like this, but for rds: Use boto3 to get current price for given EC2 instance type
EDIT:
When I use:
>>> import boto3
>>> client = boto3.client('pricing', region_name='us-east-1')
>>> response = client.describe_services()
>>> for x in response['Services']:
...     print(x['ServiceCode'])

I get this list that doesn't include rds:

*

*A4B

*AMAZONROUTE53REGIONALCHINA

*AWSAmplify

*AWSAppRunner

*AWSAppSync

*AWSApplicationMigrationSvc

*AWSBackup

*AWSBudgets

*AWSCertificateManager

*AWSCloudFormation

*AWSCloudMap

*AWSCloudTrail

*AWSCodeArtifact

*AWSCodeCommit

*AWSCodeDeploy

*AWSCodePipeline

*AWSConfig

*AWSCostExplorer

*AWSDataExchange

*AWSDataSync

*AWSDataTransfer

*AWSDatabaseMigrationSvc

*AWSDeepRacer

*AWSDeveloperSupport

*AWSDeviceFarm

*AWSDirectConnect

*AWSDirectoryService

*AWSELB

*AWSElasticDisasterRecovery

*AWSElementalMediaConvert

*AWSElementalMediaLive

*AWSElementalMediaPackage

*AWSElementalMediaStore

*AWSElementalMediaTailor

*AWSEvents

*AWSFMS

*AWSGlobalAccelerator

*AWSGlueElasticViews

*AWSGlue

*AWSGreengrass

*AWSGroundStation

*AWSIoT1Click

*AWSIoTAnalytics

*AWSIoTEvents

*AWSIoTSiteWise

*AWSIoTThingsGraph

*AWSIoT

*AWSLakeFormation

*AWSLambda

*AWSMediaConnect

*AWSMigrationHubRefactorSpaces

*AWSNetworkFirewall

*AWSOutposts

*AWSQueueService

*AWSR53AppRecoveryController

*AWSResilienceHub

*AWSRoboMaker

*AWSSecretsManager

*AWSSecurityHub

*AWSServiceCatalog

*AWSShield

*AWSStorageGatewayDeepArchive

*AWSStorageGateway

*AWSSupportBusiness

*AWSSupportEnterprise

*AWSSystemsManager

*AWSTransfer

*AWSWisdom

*AWSXRay

*AlexaTopSites

*AlexaWebInfoService

*AmazonA2I

*AmazonApiGateway

*AmazonAppStream

*AmazonAthena

*AmazonBraket

*AmazonChimeBusinessCalling

*AmazonChimeCallMeAMCS

*AmazonChimeCallMe

*AmazonChimeDialInAMCS

*AmazonChimeDialin

*AmazonChimeFeatures

*AmazonChimeServices

*AmazonChimeVoiceConnector

*AmazonChime

*AmazonCloudDirectory

*AmazonCloudFront

*AmazonCloudSearch

*AmazonCloudWatch

*AmazonCognitoSync

*AmazonCognito

*AmazonConnect

*AmazonDAX

*AmazonDetective

*AmazonDevOpsGuru

*AmazonDocDB

*AmazonDynamoDB

*AmazonEC2

*AmazonECR

*AmazonECS

A: try
response = client.describe_services(
    ServiceCode="AmazonRDS"
)

The reason you are not seeing AmazonRDS printed is because the response probably contains NextToken and you are ignoring it. Read the documentation of what NextToken is and how to use it.
P.S.: Be polite to people who are trying to help you but has no obligation to do so whatsoever.


text:
Q: Undefined offset error when running SQL query Each time I run the the SQL statement:
SELECT * FROM tbl_accident WHERE progress = 'on hire' AND progress = 'vd'

But it returns an error:

Notice: Undefined offset: 2 in C:\xampp\htdocs\newclaim\cases.php on line 139
  Notice: Undefined offset: 1 in C:\xampp\htdocs\newclaim\cases.php on line 139

Alternatively when I run:
SELECT * FROM tbl_accident WHERE progress = 'on hire';

or
SELECT * FROM tbl_accident WHERE progress = 'vd';

There is no problem. What am I doing wrong? The code at line 138-140 reads:
<?php $caseOpen = explode("/", $row_cases['caseOpen']);
  $caseOpen = $caseOpen[2].'/'.$caseOpen[1].'/'.$caseOpen[0];
  echo $caseOpen;?>

A: try
SELECT * FROM tbl_accident WHERE progress='on hire' OR progress='vd'

You used AND instead of OR in your query. Using AND will never return any result because progress can't be vd and on hire at the same time.

A: Please check your sql. You are using progress in where clause more than on time using AND. YOu can use OR instead of AND

A: You are currently always getting 0 rows returned from your select.
Try this:
SELECT * FROM tbl_accident WHERE progress in ('on hire', 'vd')


text:
Q: Users cannot deploy to Nexus 3 using maven, only using the UI I am writing instructions on how to set up Travis CI to deploy to our local Nexus 3 maven repository. I am testing my own instructions to make sure everything works. I have discovered that I cannot upload any artifacts using maven unless I use administrator credentials. As a regular user, I can upload using the provided web UI, but not maven.
All the users have full admin rights over the hosted repositories as well as the nx-component-upload privilege which enables the UI upload.
I must be missing something. The error message I get when running maven deploy is:
   org.apache.maven.shared.transfer.artifact.deploy.ArtifactDeployerException: Failed to deploy artifacts: Could not transfer artifact nz.org.riskscape:rsum_api:jar:1.0 from/to juglab-release (https://dais-maven/repository/juglab-release/): Failed to transfer file https://dais-maven/repository/juglab-release/nz/org/riskscape/rsum_api/1.0/rsum_api-1.0.jar with status code 401

Thanx in advance for any help

A: I finally got it to work. The problem was in the settings file, the username had been misstyped.


text:
Q: Serializing a lucene query into JSON? Is there a best practice for serializing Lucene queries into JSON format?  I saw elastic search query dsl, but it looks like it strays from lucene terminology.  Also, Lucene appears to be moving away from maintaining serialization code.
I am looking to have a "standard" format in JSON.  I need to be able to save a query, but when users are saving queries on the web UI, they are not entering title:Matrix.  We also have to be able to search the saved searches, then edit the saved searches.  It would be nice if there was a standard json format for representing a query.  Specifically a lucene query.

A: I know very little of Elasticsearch but I'm guessing they are doing this (also) because they support extra query functionality other than Lucene normally does.
If you just need to marshall/unmarshall the query, just treat it whole as a single unescaped string. If you want to break it down to key-value (field name/value) elements, don't forget you can have conjuction/disjunction/etc. So this is not trivial.
As for your comment on serialization code - don't think this applies to queries. Query has abstract toString(String field) method which each query subclass should implement and provide a parseable string. toString() just calls that - and this hasn't change for a long while, nor I see this changing as Query does not provide any other way of getting String representation so changing it would break a lot of code.

A: Your standard query will have a tree-like structure, so i think translating that to Json should be trivial. Just create a recursive method that calls itself for boolean or dismax queries. The rest of the queries are (i think) terminal ones


text:
Q: cut out a specific part of an image with opencv in python I have an image of an IC die and I want to cut out the marking in the center.The marking is always at this specific position above the circle at the bottom left.
The idea is to first find the circle position which I already accomplished with the hough circle transformation. Now I want to cut out the part where the marking is. It should ideally be a not a square or rectangle but something more like in the image:

This is a part of my code:
        cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        circles = cv2.HoughCircles(morph_image, cv2.HOUGH_GRADIENT, 1.3, 20, param1=50, param2=25, minRadius=15,
                                   maxRadius=19)

        if circles is not None:
            circles = np.uint16(np.around(circles))
            for i in circles[0, :]:
                # Zeichne äußeren Kreis
                cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
                # Zeichne Kreiszentrum
                cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
                # Tupel mit x- und y-Koordinaten des Kreiszentrums
                circle_center = (i[0], i[1])
                print('Die Koordinaten des Kreiszentrums lauten: ', circle_center)
                """cv2.imshow('Kreis', cimg)
                cv2.waitKey(0)
                cv2.destroyAllWindows()"""
        else:
            circle_center = None
            print('Kein Kreis gefunden')
            """cv2.imshow('Kein Kreis', cimg)
            cv2.waitKey(0)
            cv2.destroyAllWindows()"""

so my cicle center has the center position of my circle (e.g. (124, 370)). How can I cut out this part of the image automatically? Can I somehow crop it out? Ideally I would want to crop the marking out into another image to inspect it separately but the normal cropping approach with marking_img = img[y:y+h, x:x+w] wouldn't work I guess.
EDIT:
Here is the original image:

The output should be like the first image and if it is possible something like this:

So in the end I would want to have 2 images: One image with just the die without the marking and one image with just the marking

A: Here is one way in Python/OpenCV.

*

*Read the image

*Read the mask (separately created one time from your other image)

*Convert the mask to gray and threshold it to binary, invert it and make it 3 channels

*Get the center of the circle from your own code. (I have just measured it manually)

*Set the expected x,y offsets of the bottom of the region of text from the center of the circle

*Compute the expected top left corner of the mask from the center of the circle, the offsets and the height of the mask image

*Put the mask into black image the size of the input at that location

*Apply the new mask to the image to make the rest of the image black

*Crop out the region of interest from the top left corner and the size of the original mask

*OPTIONALLY, crop the original image

*Save the results

Input image:

Prepared mask image:

import cv2
import numpy as np

# read image
img = cv2.imread('die.jpg')
ht, wd, cc = img.shape

# read mask as grayscale
mask = cv2.imread('die_mask.png', cv2.IMREAD_GRAYSCALE)

# threshold mask and invert
mask = cv2.threshold(mask,0,255,cv2.THRESH_BINARY)[1]
mask = 255 - mask
hh, ww = mask.shape

# make mask 3 channel
mask = cv2.merge([mask,mask,mask])

# set circle center
cx = 62
cy = 336

# offsets from circle center to bottom of region
dx = -20
dy = -27

# compute top left corner of mask using size of mask and center and offsets
left = cx + dx
top = cy + dy - hh

# put mask into black background image
mask2 = np.zeros_like(img)
mask2[top:top+hh, left:left+ww] = mask

# apply mask to image
img_masked = cv2.bitwise_and(img, mask2)

# crop region
img_masked_cropped = img_masked[top:top+hh, left:left+ww]

# ALTERNATE just crop input
img_cropped = img[top:top+hh, left:left+ww]

cv2.imshow('image', img)
cv2.imshow('mask', mask)
cv2.imshow('mask2', mask2)
cv2.imshow('masked image', img_masked)
cv2.imshow('masked cropped image', img_masked_cropped)
cv2.imshow('cropped image', img_cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite('die_mask_inserted.jpg', mask2)
cv2.imwrite('die_masked_image.jpg', img_masked)
cv2.imwrite('die_masked_cropped.jpg', img_masked_cropped)
cv2.imwrite('die_cropped.jpg', img_cropped)

Mask inserted in black image:

Masked image:

Crop of masked image:

(Optional) Crop of input image:


text:
Q: How to map some fields to their own columns and some to a single JSON column with JPA We have a class that we want to store to a table, for example:
@Entity
public class SomeClass {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    private String fieldA;

    private String fieldB;

    private String fieldC;
}

Is there a way to map some of the fields, e.g. id and fieldA to specific columns and the others to a single JSON column so that the result would be:
mysql> select * from SomeClass;
+----+--------+--------------------------------+
| id | fieldA | otherFields                    |
+----+--------+--------------------------------+
|  1 | aaa    | {"fieldB":"b1"}                |
|  2 | bbb    | {"fieldB":"b2", fieldC: "c2"}  |
+----+--------+--------------------------------+

We don't want to move fieldB and fieldC to a separate class.
I've tried to use the @Convert annotation with an AttributeConverter but the AttributeConverter can only be used for a single column.


text:
Q: How to show the numbers on the y-axis by 1 on HighCharts? I have couple of charts working but whenever the chart spline is on 1-3 the yAxis shows numbers like 0.25, 0.75, 1.50 etc.. The spline is correct but i want to show only full numbers on the yAxis e.g 1,2,3,4,5 etc..
Any way to do that?

A: Fixed with :
allowDecimals: false

Thanks.


text:
Q: JavaScript (Tubular video background) doesn't always load and run. Sometimes it does I have some JavaScript on my Weebly.com site. One is Tubular, which adds a video background to the element selected. But it doesn't always load correctly and doesn't always run. Sometimes it does, usually not when refreshing, but when I open a new window in Chrome and load the site.
What can be the causes of JavaScript not always being loaded and run?

*

*Code of Tubular and demonstration (works on JSFiddle though): JSFiddle
What i see in Chrome while pressing CTRL+SHIFT+J.
Calling CSSStyleSheet.insertRule() with one argument is deprecated. Please pass the index argument as well: insertRule(x, 0).

Consider using 'dppx' units instead of 'dpi', as in CSS 'dpi' means dots-per-CSS-inch, not dots-per-physical-inch, so does not correspond to the actual 'dpi' of a screen. In media query expression: only screen and (-webkit-min-device-pixel-ratio: 2), not all, not all, not all, only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx) (index):1

Consider using 'dppx' units instead of 'dpi', as in CSS 'dpi' means dots-per-CSS-inch, not dots-per-physical-inch, so does not correspond to the actual 'dpi' of a screen. In media query expression: only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi) (index):1

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://www.youtube.com') does not match the recipient window's origin ('https://www.youtube.com').

event.returnValue is deprecated. Please use the standard event.preventDefault() instead.

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://www.youtube.com') does not match the recipient window's origin ('https://www.youtube.com').

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://www.youtube.com') does not match the recipient window's origin ('https://www.youtube.com'). www-widgetapi-vflZ5Tu3E.js:26

My loading order of scripts on external files is just before the closing body tag, above the rest of the scripts.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="/files/theme/jquery_tubular.js"></script>
<script type="text/javascript" src="/files/theme/smoothscroll.js"></script>
<script type="text/javascript" src="/files/theme/bigtext.js"></script>

This is the script in my HTML file that calls for the video. The Tubular code is in jquery_tubular.js. See the code in the JSFiddle link above.
<script type="text/javascript">
        jQuery().ready(function() {
        jQuery('#video-bg').tubular({videoId: 'a2pu_xhBnzY'});
        });
</script>

A: "This issue is (I believe) to do with the YT api not firing its ready event."
Just change the window.onYouTubeIframeAPIReady = function() in a setTimeout Function
window.onYouTubeIframeAPIReady = function() {
     setTimeout(function(){
        player = new YT.Player('tubular-player', {
            width: options.width,
            height: Math.ceil(options.width / options.ratio),
            videoId: options.videoId,
            playerVars: {
                controls: 0,
                showinfo: 0,
                modestbranding: 1,
                wmode: 'transparent'
            },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    },600);
  };

I found the solution here:
https://code.google.com/p/jquery-tubular/issues/detail?id=31


text:
Q: C# lambda method, set the Name property of the generated MethodInfo? I have a few helper methods, that spit out lambda functions based on it's parameters, basically partial application like. Now there is another place, where these Func<>'s are used, where for log and debug clarity it would be nice if I could give custom names to the generated lambda's MethodInfo, is there any way for this?
Example:
    public static Func<IAttrProxy, IAttrProxy, bool> NumberListEquals(double tolerance = 0)
    {
        Func<IAttrProxy,IAttrProxy,bool> lambda = (a, b) =>
        {
            if (AsNumberList(a, out IReadOnlyList<double> aValue) == false)
                return false;
            if (AsNumberList(b, out IReadOnlyList<double> bValue) == false)
                return false;
            if (aValue.Count != bValue.Count)
                return false;
            for (int i = 0; i < aValue.Count; i++)
            {
                if (Math.Abs(aValue[i] - bValue[i]) <= tolerance)
                    return false;
            }
            return true;
        };
        MethodInfo methodInfo = lambda.Method;
        methodInfo.Name = "NumberListEquals with tolerance: " + tolerance;
        return lambda;
    }

Obviously the second to last line does not compile. Is there some way to achieve the intended effect?
So that later where I use the Func<> parameter, I can get .Method.Name and it contains "NumberListEquals with tolerance:..


text:
Q: ES6 Map: Why/When to use an object or a function as a key? I've read what a Map is, and understand the differences between in Object vs Map. What I don't understand is why I would ever use objects or functions as the keys which a Map allows.
Question: Why & When would I ever set an object or a function as a key?

A: Basically if you want to track any information related to an object that should for some reason not be present on the object itself, you could use a map.
A simple example could be to track how many times an operation was done relating to an object.
Here's a demonstration where we keep track of how much food each animal (instance) has eaten without affecting the animal itself:

function Animal(type) {
  this.type = type;
}

// now let's say somewhere else in our program
// we want to have a farm where animals can eat.
// We want the farm to keep track of how much each animal ate but
// the animal itself doesn't need to know how much food it has eaten.
const AnimalFarm = (() => {
  const mapOfAnimalToAmountOfFood = new Map();
  return {
    feedAnimal(animal, amountOfFood) {
      // if the animal is being fed the first time
      // initialize the amount to 0
      if (!mapOfAnimalToAmountOfFood.has(animal)) {
        mapOfAnimalToAmountOfFood.set(animal, 0)
      }

      // add amountOfFood to the amount of food already eaten
      mapOfAnimalToAmountOfFood.set(
        animal,
        mapOfAnimalToAmountOfFood.get(animal) + amountOfFood
      )
    },
    getAmountEaten: function(animal) {
      return mapOfAnimalToAmountOfFood.get(animal)
    }
  }
})()

const dog1 = new Animal('dog')
const dog2 = new Animal('dog')

AnimalFarm.feedAnimal(dog1, 300)
AnimalFarm.feedAnimal(dog1, 500)
AnimalFarm.feedAnimal(dog2, 1234)

console.log(
  `dog1 ate ${AnimalFarm.getAmountEaten(dog1)} total`
)

console.log(
  `dog2 ate ${AnimalFarm.getAmountEaten(dog2)} total`
)

In general, a main reason for creating a map of objects to some data is that you can maintain local information about an object which, although directly related to this object, is fully contained in your own module and doesn't pollute any other parts of the system (Separation of Concerns).
Another example could be a graph which has a map of objects representing the nodes to a list of other nodes they have a connection to (useful for example in Dijkstra's algorithm):
Map<Place, ListOfPlacesICanGoTo>

This allows you to have a more pure Place object by separating this relationship rather than putting a direct Place.listOfPlaces link within the object itself. This is particularly useful if a Place is used in other contexts where listOfPlaces is not needed or even doesn't make sense.
Another common usage of objects as keys in a map-like structure is when using a WeakMap, because it's also more memory efficient by allowing each key object to be garbage collected as soon as nothing else references it.
An example could be the underlying implementation for process.on('unhandledRejection') in node which uses a WeakMap to keep track of promises that were rejected but no error handlers dealt with the rejection within the current tick.

As far as using a function as a key, I would personally think this is less useful but certainly not useless.
One useful example could be to check if a certain function was already passed in before and not invoke it again but return a cached result. This could prevent repetitive execution of potentially expensive operations.

const map = new Map();
function invokeOrGetFromCache(fn) {
  if (map.has(fn)) {
    return map.get(fn);
  }
  const result = fn();
  map.set(fn, result);
  return result;
}

function exampleFn() {
  console.log('start');
  for (i = 0; i < 100000; i++);
  console.log('done');
  return true;
}

console.log(
  invokeOrGetFromCache(exampleFn) // runs exampleFn
);

console.log(
  invokeOrGetFromCache(exampleFn) // retrieves from cache
);

As with objects, using a WeakMap could be preferable in these situations as well, for efficiency reasons.

A: If you write a function that executes an expensive operation to copy / transform / wrap an object or a function, and you expect the function to be called multiple times for the same data, it's typically a performance improvement to do a precursory check in a WeakMap to make sure you haven't already run the expensive operation.
If you have, then you're able to return the result that's already been calculated, which saves a lot of time.
One real-world example is a utility I've published called di-proxy, but to demonstrate my point, the syntax is something like this (in Node.js):
const createInjector = require('di-proxy')
// pass dependency resolver to injector factory
const inject = createInjector(require)
// wrap IIFE with dependency injector
inject(({ http, express, 'socket.io': sio }) => {
  const app = express()
  const server = http.Server(app)
  const io = sio(server)
  …
})()

Internally, the createInjector() function will check to make sure it hasn't already generated a wrapper function for require. If it has, it will use the input function as a key to a WeakMap and return the wrapper function it already generated, to save time:
function createInjector (require, noCache = false) {
  …
  // if require function is weakly referenced and memoization is enabled
  if (!noCache && this.has(require)) {
    // return cached injector
    return this.get(require)
  }
  …
  // expensive operation to generate cached injector
  …
  // weakly reference injector with require function as key
  this.set(require, inject)

  // return wrapped function
  return inject
}.bind(new WeakMap())

A: for test cases for example :
const test= new Map();

test.set('isZero', (v) => console.log(v === 0));
test.set('isNumber', (v) => console.log(typeof v === 'number'));

const value = 10;

for(let [key, fn] of test){
  // console.warn(key);
  fn(value);
}


text:
Q: Is this valid CSS? Why or why not? .9-bucks {
    font-size:  60px;
}

This is the error I am getting when I push my app to Heroku:
ActionView::Template::Error (Invalid CSS after ".": expected class name, was "9-bucks {"
2012-06-07T11:42:45+00:00 app[web.1]:   (in /app/app/assets/stylesheets/application.css)):

A: CSS selector names (either IDs or class names) cannot begin with a number...
http://css-tricks.com/ids-cannot-start-with-a-number/
Try replacing with .nine-bucks {  }

A: I dont think css class or ID names can start with a number. Have you tried using 'nine' instead of '9'?

A:
W3C reference on naming classes in css and not using a number in the
  first position of the class name. Best thing to do is to use only an
  alpha character as the first letter in your class name (a-z). You can
  then use numbers after that.

A: yes change your html - class="9-bucks" to class="nine-bucks"
and change css file - .nine-bucks{ // }


text:
Q: Is saying "This was the best part of an otherwise incredible day!" a correct usage of 'otherwise'? I'm asking because I saw this tweet: https://twitter.com/chrissyteigen/status/910404003736854528, (""Otherwise" implies you did not like hangin with this baby."), which is criticizing the usage of the word "otherwise" in Ivanka Trump's tweet which reads "Cuddling my little nephew Luke... the best part of an otherwise incredible day!"
The way 'otherwise' is used there makes it sound like the cuddling with the baby part was not 'incredible' like the rest of the day, thus contradicting that it was the 'best part', but I'm not sure if it is actually technically correct.

A: It's perhaps less than ideal.
The audience can do the math on it and know that since it is differentiating best with incredible that the otherwise isn't contrasting opposites but things that differ only by degree.
And that's perfectly sensible and valid.
That otherwise is more often used for things that are actually opposed, and since it's redundant ("the best part of an incredible day" works just as well, indeed better) means the sentence would likely have been better writing without it, but it's not wrong.


text:
Q: Check table exists I need to check if a table exists in a database. I currently develop using Yii2.
My case is a bit different from this question because the table to be checked is not (and can not be) a model.
I have tried (new \yii\db\Query())->select('*')->from($mysticTable)->exists());
The above throws a yii\db\Exception because, according to question linked above, the yii\db\Query() class tries to ->queryScalar() when asked if ->exists(). Invariably, this method checks if the result-set exists.
How do I check if a table exists?

A: For Yii2 you can use:
$tableSchema = Yii::$app->db->schema->getTableSchema('tableName');

If the table does not exist, it will return null, so you can check returned value for being null:
if ($tableSchema === null) {
    // Table does not exist
}

You can find this method in official docs here.

A: Good that you get an exception. Simply parse the exception message. You would get a very very specific message and SQL error code for missing table.
That is what I do when checking e.g. IF an error was due to something that can be recovered, say a broken connection, versus some other error.
OR I see that many people have pointed out much more direct ways of getting that information.

A: A spin off @msfoster's answer got me closer to a solution in yii2
/**
 * @param $tableName
 * @param $db string as config option of a database connection
 * @return bool table exists in schema
 */
private function tableExists($tableName, $db = null)
{
    if ($db)
        $dbConnect = \Yii::$app->get($db);
    else
        $dbConnect = \Yii::$app->get('db');

    if (!($dbConnect instanceof \yii\db\Connection))
        throw new \yii\base\InvalidParamException;

    return in_array($tableName, $dbConnect->schema->getTableNames());
}

This also serves multiple databases.


text:
Q: Multiple layouts and multiple views Android Studio I am trying to build an app and I want to add multiple views in my app. I am struggling to find a way to handle the views properly. If you do it within one class (MainActivity) you need to do some hiding, which I think is not that neet and can be done in a more solid way, but I do not know how.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    editTextAddress = (EditText) findViewById(R.id.address);
    editTextPort = (EditText) findViewById(R.id.port);
    editTextMsg = (EditText) findViewById(R.id.msgtosend);
    buttonCalibrate = (Button)findViewById(R.id.calibrate);
    buttonMove0 = (Button)findViewById(R.id.Move0);
    buttonConnect = (Button) findViewById(R.id.connect);
    buttonDisconnect = (Button) findViewById(R.id.disconnect);
    buttonSend = (Button)findViewById(R.id.send);
    textViewState = (TextView)findViewById(R.id.state);
    textViewRx = (TextView)findViewById(R.id.received);

    buttonDisconnect.setEnabled(false);
    buttonSend.setEnabled(false);

    buttonConnect.setOnClickListener(buttonConnectOnClickListener);
    buttonDisconnect.setOnClickListener(buttonDisConnectOnClickListener);
    buttonSend.setOnClickListener(buttonSendOnClickListener);
    buttonMove0.setOnClickListener(buttonMove0OnClickListener);
    buttonCalibrate.setOnClickListener(buttonCalibrateOnClickListener);

For example this is my java code, some of these buttons are not from activity_main.xml but from another xml file. The app just returns a NULL pointer with those buttons, which is logical.
I have seen many ways but I cannot decide which one is the proper one.
What is the proper way?

A: you can use butterKnife to help you in this
and you can simply do this
public class MainActivity extends Activity {
@BindView(R.id.sample_text) TextView textView;
@BindView(R.id.sample_button) Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
textView.setText("You can change this view accordingly");

@OnClick(R.id.click_button)
void buttonClick() {
//..you don't even need the line @InjectView(R.id.click_button) if this
button isn't being used else where
}

}
}

A: If your want to show another layout in your activity layout you need to include that layout
Including another_layout.xml in activity_main.xml layout
...
<include
    android:id="@+id/included_layout"
    layout="@layout/another_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.1"
    android:gravity="bottom"/>
....

this code will set the layout of the bottom of main layout.
You can hide this layout as you wish
View view = (View) findViewById(R.id.included_layout);
view.setVisibility(View.INVISIBLE);


text:
Q: Saturating an operator norm inequality I read the following statement:

$\text{tr} [ A(B+C)] \leq \left\Vert B+C \right\Vert$. Since $B+C \geq 0$, one can always find $A$ s.t. the inequality is saturated.

Here, $A$ is a hermitian PSD matrix with $\text{tr}(A) = 1$, whereas $B,C \geq 0$ and also hermitian.
Regarding that, I have the following questions:

*

*Is it obvious what operator norm they are using?

*Why is $\text{tr} [ A(B+C)] \leq \left\Vert B+C \right\Vert$ true? Could I show that by saying $\text{tr} [ A(B+C)] \leq \left\Vert A \right\Vert \left\Vert B+C \right\Vert$, and as $\text{tr}(A) = 1 \Longrightarrow \left\Vert A \right\Vert \geq 1$, then the statement is true?

*Why $B+C \geq 0$ must be true so that we can find $A$ that saturates the inequality?

*How can I find such $A$ that saturates the bound? Is it related to the eigenvectors of $(B+C)$?

P.s.: I only know introductory linear algebra, so I'm sorry if these questions are obvious.


text:
Q: Accessing a class member variable by its name at runtime In the vein of more impossible-but-is-it-really questions:
Is it possible to access the member variable of a class, where the variable's name is stored in a string?
class Test
{
public:
int test = 0;
}
string name = "test"; // let's assume we know test is an int.

Any chance of getting the value of test, using the string?
One bit of cheating not allowed:
enum vartype {
INT,
..
}

No forcing the class to register all its variables in a std::map<string, std::pair<vartype, void*> >.
All other tricks welcome.
Thanks!

A: No.
To do this, you need to provide some mapping between member variables and the string names by which you intend to access them.

A: In the realm of really ugly kluges, you could build the program with debug information and have it use that to find the location of the variable in the same way a debugger would.  But other than that, you're out of luck.  C++ doesn't do reflection.

A: About why it's not available in C++ and an alternative: http://en.allexperts.com/q/C-1040/eval-function-javascript-C.htm
It's possible in MATLAB though...
As a very simple example, if you have a matrix updation to do, which goes like:
M1=1;
M2=2;
M3=3;

And you would prefer that the variable names could be altered so that you could use a for loop, then it can also be done this way:
for i=1:3
eval(['M' num2str(i) '=' num2str(i)]);
end

I used to do this in Actionscript. Was really glad to find that it's available in Matlab too


text:
Q: How to find an exact value on a plot? I have a plot which is drawn from points.
I can identify the coordinates values with the brush tool. However I'd be interested in the specific value of a certain x when y value is 0. With the brush tool I cannot pick it exactly.
Is there a way to have the specific y value for x = 0 approximated from the graph?


text:
Q: How to Get queryset not dict django aggregate i'm using this queryset for my requirements
invoices = Invoice.objects.aggregate(total_amount=Sum('order__order_items__amount'),number_of_invoices=Count('pk', distinct=True))

which returns dict--->
{'total_amount': Decimal('17700.00'), 'number_of_invoices': 2}

but I want queryset how can i do that..
Thanks for any help

A: This is what aggregate do :)
You can add a DecimalField to Invoice model, that aggregates total_amount during before every save. I suggest signals for that.
apps.py
class YourAppConfig(AppConfig):
    ...

    def ready(self):
        from . import signals

signals.py
from django.db.models.signals import pre_save
from django.dispatch import receiver

from .models import Invoice

@receiver(pre_save, sender=Invoice)
def total_amount_aggregation(sender, instance, *args, **kwargs):
    instance.total_amount = # aggregate desired amount here

You have to set similar signals for your Order, so if you change Order object, the related Invoice object will be recalculated.
After that QuerySet will stay as QuerySet and every object will have always caclulated field.

A: Instead of using .aggregate(...) use .annotate(...) this will return a QuerySet with given expression
from django.db.models import Sum, Count

invoices = Invoice.objects.annotate(
            total_amount=Sum('order__order_items__amount'),
            number_of_invoices=Count('pk', distinct=True)
           )

then to get Sum(...) & Count(...) of field do like this invoices[0].total_amount__sum & invoices[0].number_of_invoices__count


text:
Q: Call to undefined method Laravel\Lumen\Application::post() Im trying to implement passport in lumen by using dusterio repo.
But when i do a migrate command (php artisan migrate), i got an error looks like :
[Symfony\Component\Debug\Exception\FatalThrowableError]

Call to undefined method Laravel\Lumen\Application::post()
somebody could help, what's wrong here?


text:
Q: Inserting one row in a table with ODBC and C++ I would like to insert only one row in a Table, which is in MS SQL Server. I am using C++ and I want to do this job with ODBC. I have written a very basic example:
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>

int main()
{
 SQLHANDLE henv;
 SQLHANDLE hdbc;
 SQLHANDLE hstmt;
 RETCODE rc;

char Statement[80] = "INSERT INTO TK.dbo.Infos( Firstname,Lastname) VALUES ('Max','Musterman')";

char dsn[10] = {"TK"}; //Name of Database in MSSQL Server
char user[5] = {""}; //I have windows Authentication, not user name and password for loggin to DB
char pass[5] = {""};

rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER);
rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
rc = SQLConnect(hdbc, (SQLCHAR *)dsn, SQL_NTS, (SQLCHAR *) user, SQL_NTS, (SQLCHAR *) pass, SQL_NTS);
rc = SQLAllocHandle(SQL_HANDLE_STMT,hdbc,&hstmt);
rc=SQLExecDirect(hstmt,(SQLCHAR *)Statement,SQL_NTS);

return 0;
}

If I am running this code, I get no errors or bugs, but it doesn't work properly. If I run the code step by step, at the first rc=0 and in the last two lines rc=-1
Could you please help me to correct my code?
thnaks


text:
Q: Fix Compilation Error: stray \200 , stray \213 and stray \342? Here is a simple code that adds two numbers in each thread and then gives total balance in the end:
#include <pthread.h>
#include <stdio.h>
int currentBalance=100,newBalance=0,oldBalance=0;
pthread_mutex_t mutex;

void* thread1(){
pthread_mutex_lock(&mutex);
oldBalance = currentBalance;
newBalance = oldBalance + 10000;
currentBalance = newBalance;
pthread_mutex_unlock(&mutex);
}

void* thread2(){
pthread_mutex_lock(&mutex);
oldBalance = currentBalance;
newBalance = oldBalance + 5000;
currentBalance = newBalance;
pthread_mutex_unlock(&mutex);
}

void* thread3(){
pthread_mutex_lock(&mutex);
currentBalance = currentBalance;
newBalance = oldBalance + 5500;
currentBalance = currentBalance;
pthread_mutex_unlock(&mutex);
}

int main()
{
pthread_t trd1,trd2,trd3;
pthread_attr_t attr;
pthread_mutex_init(&mutex,NULL);
pthread_attr_init(&attr);
pthread_create(&trd1,NULL,thread1,NULL);
pthread_join(trd1,NULL);
pthread_create(&trd2,NULL,thread2,NULL);
pthread_join(trd2,NULL);
pthread_create(&trd3,NULL,thread3,NULL);
pthread_join(trd3,NULL);
printf("Current Balance: %d\n",currentBalance);
return 0;
}

I am trying to compile it using command
gcc -pthread task6.c

And here is the error:

I don't know what's wrong, the code is just fine. Please guide me a bit.
Thank You!


text:
Q: Symfony2 vendors and commit reset git I have a problem on my vendors using Symfony2.3
When I began my project I added vendors to my git repo, now I'd like to remove it.
so I do:
git rm --cached -r vendor/

This command remove all my vendors from the git repo but I got problems, so I do a git reset to get my vendors back.
Now I have a problem I don't know really why, when I'l trying to run a command line via app/console I got this error message:
[RuntimeException]
  The autoloader expected class "FOS\JsRoutingBundle\Command\Command\DumpCommand" to be     defined in file     "/Users/ant/Documents/projects/test/application/vendor/friendsofsymfony/jsrouting-    bundle/FOS/JsRoutingBundle/Command/Command/DumpCommand.php". The file was found but the class     was not in it, the class name or namespace probably has a typo.

So I tryed to remove jsrouting-bundle from my composer.json but when I run
composer.phar update

jsrouting-bundle is not removed
So I'd like in a first time to remove manually jsrouting-bundle to re-download it.
And remove without problems the vendors from my git repo
Thanks for your help
Edit:
I solve the first part:
I went to verdor>composer>autoload_namespace.php and I remove this line:
'FOS\\JsRoutingBundle' => array($vendorDir . '/friendsofsymfony/jsrouting-bundle'),

I also remove the JsRoutingBundle from the vendor folder
and composer reinstall JsRoutingBundle.
But I'd like to have a tip to remove my vendor folder properly

A: If you are using composer, the vendor folder should only contain composer-installed data. Remove completely the folder from your disk and git, remove composer.lock, and reinstall everything using composer.json.
composer.phar install

You may have to remove vendor folder and composer.lock file on every copies on every hosts.


text:
Q: How to clean up bitmap resources I wanted to ask this question that was asked a few times before. Sorry if I am re-itterating but it is not clear to me as to what is the best solution here.
The question is "how to clean ImageView bitmap resource after its been used so we don't have references to it in memory?".
Here is an example:

*

*Screen 1 redirects to Screen 2

*Screen 2 contains control A (preview of large photo)

*Control A contains ImageView B

*ImageView B is set when control A is initiated

Everything works fine the first time around. Once control A is done I redirect from Screen 2 to Screen 1. At this point all references of control A or ImageView B or Bitmap that its using should be dead. THEY ARE NOT!!!
I've tried all kinds of solutions including bitmap.recycle(), adding finalize() into Control A, System.gs() and nulling control in variouse places such as onStop() and onDestroy(),  and everything else that's on screen 2, nothing works!
The problem is when I revisit the screen second time around so going from screen 1 to screen 2 (i.e. creating preview of photo again) I get out of memory exception. It is my understanding that the reference of the previous bitmap is not cleaned up.
How do I KILL it just before I redirect back to Screen 1?
One thing I noticed. If I reduce the size of the photo by, say cropping or making a smaller size of the image everything goes smooth, few times... before I get same issue. So basically it just takes a bit longer to fill up.
I would really appreciate some solution here as this is critical.

A: You probably have a memory leak , this video might help you in finding the problem Google I/O 2011: Memory management for Android Apps.
Note : pre 3.1 bitmaps are store in VM heap memory but in native memory , which causes lot of problems in noticing leaks,for further info refer the video

A: Have a look at how WeakReference is used.


text:
Q: Finding reference allele for mendelian randomisation I am trying to perform an MR using summary statistics from this GWAS. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7026164/#MOESM1
Unfortunately, the summary stats in the supplemental only have an A1 allele and do not give an A2 reference allele or EAF and therefore I am unable to harmonise the data to my outcome data.
I am using MR package in R with code
x <- harmonise_data(
  exposure_dat =exposure_dat,
  outcome_dat = outcome_dat_all, action = 1)

and i am getting the error "error in A2[to_swap] <- A1[to_swap] :
NAs are not allowed in subscripted assignments"
I believe this is because it requires an A2 allele in the exposure dataset. Is there anyway I can perform the MR without it? Or alternatively, can anybody suggest how I can quickly find all of the reference alleles. There are around 400 SNPs so searching for them individually would not be ideal.
Thanks, I would appreciate any help.

A: I think you can fetch A2 from the column uniqID from the supplementary information. If they have not provided EAF, you can potentially use the 1000 Genomes data to calculate it.


text:
Q: How do I instantiate an empty workbook using Excel Interop? I have this code:
using Excel = Microsoft.Office.Interop.Excel;
var excelApp = new Excel.Application();

if (CurrentWorkbook.Version == "Release")
{
}
else
{
      if (File.GetLastWriteTime(CurrentWorkbook.DataPath + CurrentWorkbook.FileName + ".xlsm").Date != DateTime.Today)
      {
           var MRPData = excelApp.Workbooks.Open(@"H:\@Business_Reporting_Today\MRP\Blank MRP Workbook.xlsm", 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
      }
}

and then later in my project I have:
if (CurrentWorkbook.Version == "Release")
{
}
else
{
    excelApp.DisplayAlerts = false;

    MRPData.Close(0);
    Marshal.FinalReleaseComObject(MRPData);
    excelApp.Quit();
    Marshal.FinalReleaseComObject(excelApp);
}

However since I declared MRPData in an if code block, it of course, "Does not exist in current context," in the later code block.  I have tried to pull the declaring of the variable out of the code block with this:
var MRPData = new Excel.Workbook();

This gets rid of the compile errors but gives me a run time error that says,

'Retrieving the COM class factory for component with CLSID
  {00020819-0000-0000-C000-000000000046} failed due to the following
  error: 80040154 Class not registered (Exception from HRESULT:
  0x80040154 (REGDB_E_CLASSNOTREG)).'

How do I fix this problem, so that I can declare it outside of the if code block?


text:
Q: Optical character recognition in an image using Python I have an image file which Python reads and converts that to hexadecimal. The problem here is, even if I give an empty blank image its giving hexadecimal numbers as output. I need Python to process only the alphabets in the image and covert them to hexadecimal and give that as output.
Here is the program which I tired
import binascii

filename = 'a.png'
with open(filename, 'rb') as f:
    content = f.read()

print(binascii.hexlify(content))

A: This is OCR(Optical Character Recognition) problem, which is discussed several times in stack history.
Pytesserect do this in ease.
Usage:
import pytesserect
from PIL import Image

# Get text in the image
text = pytesseract.image_to_string(Image.open(filename))

# Convert string into hexadecimal
hex_text = text.encode("hex")


text:
Q: How to set several columns as the key in data.table package (r)? setkey() can be used to set a column as the key to a data table.
But now I have three column:
A         B          C

1         2          3
1         2          4
1         2          5

I want to set the ABC as the key. How to do it in data.table package?

A: Three simple alternatives:
# 1
setkeyv(dt, c("A","B","C"))

# 2
keycols = c("A","B","C")
setkeyv(dt, keycols)

# 3, or you can setkey for the whole data.table
setkey(data)

data for example:
library(data.table)

dt <- data.table(A=c(1,1,1), B=c(2,2,2), C=c(3:5))


text:
Q: Unicode Character U+0972 seems to be broken while rendering normally See this question on Ask Ubuntu: What are the key combinations for alphabets 'ऋ' and 'ॲ' on Hindi Bolnagari keyboard layout?
I am talking about Unicode Character 'DEVANAGARI LETTER CANDRA A' (U+0972). There seems to be rendering issues with it. The character displays perfectly fine in the raw input (ie; the body, title, comments - all in edit mode) but doesn't render correctly when posted. This happens everywhere - title, body, comments.
Examples: ॲ renders correctly in inline code but it is displayed as ॲ normally.
ॲ is also displayed correctly in Code Block

Wrapping it in <kdb> tag renders it correctly on AU but not on Meta.SO -- ॲ.
This is how it looks at my end:

I am using Firefox 19.0.2 on Ubuntu. Character Encoding is already selected as Unicode (UTF - 8). Is it happening only to me?

A: Encoding is not the problem, since you see the character in some instances.
The problem is clearly in the font your browser is using and in particular:

*

*It works when matching Consolas, Menlo, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', monospace, serif;

*It fails when matching Arial, Helvetica, sans-serif;

*It fails again when matching Arial, 'Liberation Sans', 'DejaVu Sans', sans-serif;
The problem is likely to be the default fonts on Firefox, which you can change - or you can install Microsoft fonts or Apple fonts.
For more info: (Ubuntu -Firefox- default font) How make default font arial in Firefox on Ubuntu 10.04?

A: This means that either your browser isn't reading the page with the right encoding or your system doesn't have a font with that character.


text:
Q: ReactJSL How to target a single element in a map function with a button I have a Component that renders a list of elements using the map function. Each element is rendered with a delete and edit button. I have added the delete functionality, but I'm having problem with the edit one.
The functionality that I want is: click on edit item, replace H3 element (which is the title) with an input field and let the user update the name. I've tried replacing an element with another but this only works for the first element of the list, because I get the element with 'getElementById' I have tried doing it with querySelector, but that selects only the last element of the array.
I have no idea what to do. I know the issue is selecting the particular element at the right index. I use an id as a key but I don't know how to properly replace the html element. Any help will be vastly appreciated.
Here is where the map function renders the elements:
class Donut extends Component {

  render(){

  const {donuts, deleteDonut, editDonut} = this.props;
  const donutsList = donuts.map((donut) => {
    return

{donut.name}

{donut.date}

{donut.price}

        {editDonut(donut.id)}} />
         {deleteDonut(donut.id)}} />

})
    return (

        {donutsList}

    )
  }
}

export default Donut

A: Try to avoid as much as possible directly manipulating DOM elements when you using React. In this case, you should use another approach:

*

*Add a field to this class's state: editingDonutId

*When you click in a donut, set the editingDonutId to corresponding id and when you finished it, reset the value.

*In render function, inside the map, do a condition render to check if current rendering donut has same id with editingDonutId, if true, we render an input instead.

A: You are using react, not jquery, so do not use getElementById, try react solution.
This is my solution:
class Donut extends Component {
    state = {
        donutsState: {}
    }
    setDonutState: (id, value) => {
        this.setState((preState) => {
            const predonutState = preState.donutsState[id] || {}
            return {
                donutsState: {
                    ...preState.donutsState,
                    [id]: {
                        ...predonutState,
                        ...value,
                    }
                }
            }
        })
    }
    getDonutState: (id) => this.state.donutsState[id] || {};
    render(){
        const {donuts, deleteDonut, editDonut} = this.props;
        const donutsList = donuts.map((donut) => {
            const donutState = this.getDonutState(donut.id)
            // when user input the name, save it in the state.
            const onChange = (e) => {
                this.setDonutState(donut.id, { value: e.target.value })
            }
            // when click edit, replace h3 with input.
            const onEdit = () => {
                this.setDonutState(donut.id, { eidt: true })
            }
            // when enter key, replace input with h3 and submit the name value.
            const onKeyDown = (e) => {
                if (e.key === 'Enter') {
                    this.setDonutState(donut.id, { eidt: false })
                    editDonut(donut.id, {
                        name: this.getDonutState(donut.id).value || donut.name,
                    })
                }
            }
            return (

                            {
                                donutState.edit
                                ? <input id="edit-donut-title" value={donutState.value || donut.name} onChange={onChange} onKeyDown={onKeyDown} />
                                :
{donut.name}

                            }

{donut.name}

{donut.date}

{donut.price}

                        {editDonut(donut.id)}} />
                         {deleteDonut(donut.id)}} />

            )
        })
        return (

                {donutsList}

        )
    }
}

export default Donut


text:
Q: how to show a blinking cursor on a hidden textbox as soon as it is visible I have a textbox which is initially hidden. But once when you click on a button it shows a textbox and i want the focus to automatically go to the textbox which is now visible. I want the cursor to start blinking there.
I tried autofocus but that did not work.

A: Let's say your HMTL is something like
<textarea id="ta"></textarea>
<button id="showta">Show the box</button>

then with jQuery
$('#showta').on('click',function(e){
    // display and focus
    $('#ta').show().focus();
});

with vanilla js
var ta = document.getElementbyId('ta'),
    btn = document.getElementbyId('showta');
btn.addEventListener( 'click', function(e){
    ta.style.display = 'block';
    ta.focus();
});

if it's not work, you might want to add a timeout for it. var timeout = 100; any number > 0. Then in handler:
clearTimeout(timeout);
timeout = setTimeout(function(){
    $('#ta').focus();
    // or ta.focus();
});

A: After your button click, which shows the textbox, make your input element focus by
$('yourinputfiled').focus();

Thanks !

A: Instead of using visibility: hidden/opacity=0, you can show/hide by using display block/none.
Hope it will work :)

$(document).ready(function(){
$('.span_click').click(function(){
    $('.show_search').addClass('visible_now');
        $('#set_focus').focus();
 });
});
.show_search {
    background: #fff;
    //opacity: 0;
    display:none;
    padding: 0 30px;
    //visibility: hidden;
    -webkit-transition: visibility 500ms ease 0.3s;
    -moz-transition: visibility 500ms ease 0.3s;
    -o-transition: visibility 500ms ease 0.3s;
    transition: visibility 500ms ease 0.3s
}
.visible_now {
    //opacity: 1;
    display:block;
    visibility: visible;
    -webkit-transition: visibility 500ms ease 0.3s;
    -moz-transition: visibility 500ms ease 0.3s;
    -o-transition: visibility 500ms ease 0.3s;
    transition: visibility 500ms ease 0.3s;
    z-index: 2
}

Search

    <input class="" id="set_focus" type="search" placeholder="Search"/>


text:
Q: How do you maintain focus when a particular aspect of programming takes 10+ seconds to complete? I have a very difficult time focusing on what I'm doing (programming-wise) when something (compilation, startup time, etc.) takes more than just a few seconds.  Anecdotally it seems that threshold is about 10 seconds (and I recall reading about study that said the same thing, though I can't find it now).  So what typically happens is I make a change and then run the program to test it.  That takes about 30 seconds, so I start reading something else, and before I know it 20 minutes have passed, and then it takes (if I'm lucky!) another 10+ minutes to deal with the context switch to getting back into programming.
It's not an exaggeration to say that some things that should take me minutes literally take hours to complete.
I'm very curious about what other programmers do to combat this tendency (or if I'm unique and they don't have this tendency?).  Suggestions of any type at all are welcome - anything from "sit on your hands after hitting the compile button", to mental tricks, to "if it takes 30 seconds to start up something to test a change, then something's wrong with your development process!"

A: I guess I'll be the one to say it but you should just sit there and wait for it to finish.
You need to retrain yourself to not feel the need to be constantly on and actively doing things. This is a very detrimental issue that affects not just developers but all people. Society has become obsessed with the need for constant stimulation (visual, audio, mental). It seems no one can stand to be idle for more than 30 seconds without pulling their phone out and texting, surfing the web, checking facebook, etc.
If you hit compile and it's going to take a minute or so consider that a great opportunity to just sit and let your brain relax. Resist the urge to do something stimulating and just enjoy a moment of non activity.
With time it will become easier and you'll find you will have a much better work experience when you stop trying to keep your brain firing at 100% all day long.

A: I agree with what @retracile is suggesting, but note that according to the Zen programming rules you should focus on only one task at a time. Answering to phone calls, browsing the Web, social networking, or even doing multitasking will most likely decrease your productivity. Use the short waiting delay to think about the existing task/solution and what you can do to improve it.

A: I have a bar attached to the doorpost

I can do only 5 pull-ups so it takes less than a minute. Or I make a cup of tea.

A: For me, the way to keep my focus is to be ruthless about maintaining a clean work space, whatever that workspace might be. Anything that isn't part of my current project is noise in the hallowed signal-to-noise ratio. A vital part of maintaining focus is about keeping the signal-to-noise ratio high.
When I'm coding, this means closing programs that I haven't used recently, regularly pruning my browser tabs, and keeping my desktop clear of items that aren't immediately relevant to my current projects. I use the ten second delays to "make the rounds", so to speak--closing tabs, closing programs, deleting temporary files and archiving what needs to be archived, etc.
Getting in the habit of "making the rounds" helps prevent rabbit trails, too, because it forces me to continually evaluate--and be reminded of--any current tasks.
There's a small price to be paid when you have to re-open a tab that you've already opened 5 times today or re-launch a command prompt with elevated privileges for the 15th time, but leveraging accelerators like keyboard shortcuts can cut this to a very small price indeed.

A: I find it helps to track the actual time I spend not working
You can use any number of things for this. I know there are many free apps out there you can download to do this for you (can't think of any off the top of my head right now, but if someone gives me some I'll add them to this answer), or it's very easy to create your own. I usually use one I created which is a tiny window in the corner of my screen with buttons for Working/NotWorking, and I just click whichever one I'm on whenever I switch focus.
A chess clock also works
The very act of tracking your time makes you more aware of how much time you are wasting that you should be spending working, and I find it makes me more productive because I'll force myself to leave that super-interesting stackoverflow question, or blog article, and get back to work

A: For keeping my attention up I use doodles. I always have a pen and a notepad lying behind my keyboard and doodle away. It isn't more then scrabbling on a piece of paper without any meaning but it keeps my attention up just enough and doesn't get me distracted so I can snap right back to what I was working on.
I've done this all my life unconsciously but recently found a wiki about it: http://en.wikipedia.org/wiki/Doodle

A: Whatever you do don't go on any of the StackExchange sites. They will suck you in :)
More seriously, browsing the web while waiting for something to finish it's not good for the productivity (unless you're researching something related to the current task).
I usually do few minor tasks that will not take longer than 1-2 min. (cleaning something, writing comments, notes).

A: Do something for your health:
Standup, walk away from your computer and do some hand and arm stretching exercises. This will take 2-5 minutes max. Your future self not suffering from RSI will thank you for this.
Also, regarding the 2-5 minute break, have a read through the Pomodoro technique. This is based on the idea of having frequent short breaks to take your mind off your current task and let things sink in a little. It's a short enough break not to loose your train of thought completely but long enough to give your brain a breather.

A: Development is a creative process. You can't be constantly productive, especially if there are lots of distractions in your office. That's why the Joel Test suggests quiet working conditions.
Joel Spolsky also explains what it means to "not being in the zone". Each time something prevents you from doing your work, you have to spend ten minutes, often more to get back in the zone and become productive again.
There are lots of distractions:

*

*A phone call from your wife,

*A phone call to the business person in the office space close to yours,

*A colleague asking you for help,

*Being hungry,

*Having personal problems,

*Having to work on legacy code written by an inexperienced developer ten years ago and never refactored,

*Having a slow PC or a slow Internet connection,

*Having a long compile process,

*etc.

There is nothing to do with it. The only thing you can do is to remove the distractions themselves:

*

*No phones in your office,

*Quiet working conditions,

*Fast computer and Internet access,

*Fast compile process,

*etc.

In your case, if it's the compiler which distracts you, try to reduce the compile time by:

*

*Reducing the size of your program (some IDEs for example let you unload some projects from a solution, strongly reducing the compile time),

*Using nightly builds and compiling less during your work,

*Buying a faster machine (if there is nothing else to do),

*etc.

A: I wrote a little commandline utility called 'alert' which will cause the computer to beep / play a sound / etc.  Then, when I have a lengthy command to run such as a make, I run make; alert.  Where I can, I will also have it take an argument so it makes a different sound depending on the argument.  Thus I can do make; alert $? and I'll know a) the build is done, and b) it passed or failed.  You don't have to be that fancy with it; just an echo -e "\a" can be enough.
If you wanted to get really fancy/annoying, use some text-to-speech package and trigger a dialog popup.
The main idea here is to interrupt your distraction as soon as the work-related task completes.

A: I have the same problem, and the solution for me has been to spend the time doing something which will not get you sucked in. For me, this is usually either (1) filling up a water bottle, or (2) standing up and taking a 30-second walk around the office to stretch my legs, which need the movement anyway. You can get lost browsing the internet; you rarely get lost walking around your own cubicle.

A: During those 10-30 seconds go and do something :

*

*that doesn't require lots of mental activity

*open the code you are compiling, and check it again (you might find something wrong, or a way to improve it)

During that time, do not do stuff that you know it is going to take you long (unless you can afford to spend some time) like :

*

*starting to read a book

*read emails if you know it can take you long

*etc

Also, do not install some audio alarm to signal the end of compilation. Your colleagues will appreciate it.

A: In your case, get up and walk around a little. If it's hard to get back in "the zone" it's probably because you're too far in. Doing stuff on the web is just another zone and one that's easy to lose track of time in. Give your brain the break it clearly wants and go for a walk, take a wiz, ideally in a restroom, or talk to a random co-worker. We do a lot of stuff behind the scenes on auto-pilot. Breaks are not bad for  coding, they are good, but the idea is to stop firing on all cylinders for a while and see what your back burners come up with while the more conscious part of your mind gives it a rest. Good devs aren't human calculators. Let the parts of your brain that do all the intuitive and pattern-matching stuff on autopilot do their thing for a while.
If this isn't just a coding problem, you might want to consider ADD.

A: The suggestions to get up and walk around etc. are good if your cycles are long (an hour or so).  But when cycle times get short, and I find myself popping back and forth between vim and make every few minutes, then I stay in the zone by staying in the pipeline:  While the build or test suite is running, I tend to go back and review the code, then start working on the next chunk that I'd be doing anyway if the build or tests do succeed.

A: Make a plan at the beginning of each day as to how to use this "spare time".  It might involve

*

*catching up on some documentation tasks,

*working out unit test cases for the class that you're going to write next,

*studying some new piece of technology that you've been meaning to learn,

*writing a letter to your favourite aunt,

or just about anything really.
Have this secondary task always open in a window somewhere on your desktop.  As soon as you hit the "compile" button (or whatever it is that's taking you more than 30 seconds), switch to the secondary task, and put in enough time to actually move forwards on it, which could be a couple of minutes, or could be less.
While you're doing the secondary task, keep it in the back of your mind that this not what your brain should be focussed on.  Keep thinking about programming.  This isn't easy; you'll still suffer from the context switch more often than not.
If you do this, even if you lose context many times, your lost time isn't actually wasted time, and you've got something to show for it at the end of the day.  But the most important thing is to plan, at the beginning of the day, what the day's secondary task is going to be.

A: I suppose we can use the compile time to document the code, code cleanup, aligning the code properly, so that we dont move away from our IDE and still improving the quality of code.

A: I usually just try to look for bugs, typos, or ways to improve the style of the code in the meantime. That keeps me looking at the code, but I don't (always) get distracted by something interesting. Also, this!

A: It's conceivable you've got a bit of ADHD. Lots of people do. Coping mechanisms are as given in the other answers (or possibly medication).

A: For internet distraction during work in general, i suggest The Pomodoro Plugin if you are using Google Chrome
I personally think that you can't be productive during all your working time ! since you are compiling, it means that you made enough efforts to take a breath ... to not abuse or get out of the context, keep thinking on the next step if the compilation doesn't generate errors ... Or clean your working area : Desktop, Tabs, Explorer ...

A: What you are describing is perfectly normal.
When we were doing usability studies, we would look at delays by order of magnitude. When a user clicks a button, how long do they have to wait?

*

*0.1 sec: no perceived delay

*1 sec: no change in focus

*10 sec: attention lost

*1 min: user switches to another task

*10 min: user will get up and leave

There are plenty of exceptions, such as compound operations, like typing.
When we were doing performance work, we often asked the question "how fast should operation X be?" The answer is, as long as the user can perceive a delay, faster would be better.
In your case, you're hitting that 10s threshold, and your attention drifts away. The best thing you can do is reduce the delay. The shorter the delay, the greater your productivity. Imagine you had the code on the left side of your screen, and the running app on the right. As you edit the code, the app changes in real time. Until you're there, you have room to improve.
See also Jeff's recent blog post (the tons of good content it leads to): http://www.codinghorror.com/blog/2012/03/visualizing-code-to-fail-faster.html
If you are going to switch to something else, pick something that doesn't engage your brain in the same way as the work you were doing. Clean your desk, meditate, stretch, push-ups, art, look out the window.

A: When doing ad-hoc work in SAS, I find the following line very useful:
dm log 'postmessage "Code finished"' continue;

This produces a pop-up dialogue box once all preceding code has finished executing. I'm sure there are equivalents in other languages. I would have posted this as a comment to retracile's answer but I don't have enough reputation.


text:
Q: replacing an item (tensor) in a list with another tensor but of different shape, using pytorch I have a list of tensors
t_list=[tensor([[1],
         [1],
         [1]]),
 tensor([[1],
         [1],
         [1]]),
 tensor([[1],
         [1],
         [1]])]

and want to convert it to
[tensor([[1,0,0],
         [1,0,0],
         [1,0,0]]),
 tensor([[1,0,0],
         [1,0,0],
         [1,0,0]]),
 tensor([[1,0,0],
         [1,0,0],
         [1,0,0]])]

I tried this code
import torch
z= torch.zeros(1,2)
for i, item in enumerate(t_list):
    for ii, item2 in enumerate(item):
        unsqueezed = torch.unsqueeze(item2,0)
        cat1 = torch.cat((unsqueezed,z),-1)
        squeezed = torch.squeeze(cat1,0)
        t[i][ii] = squeezed

But got this error
RuntimeError: expand(torch.FloatTensor{[5]}, size=[]): the number of sizes provided (0) must be greater or equal to the number of dimensions in the tensor (1)

I am not sure how to get around this

A: You should use list comprehension, and a little "outer product" trick:
t_list = [x_ * torch.tensor([[1, 0, 0]]) for x_ in t_list]

A: Well, I stored them in a new list. Maybe it is not the best way but this is how I made it


text:
Q: compute Visible property for a button, based upon length of a textarea field I would like to calculate the visibility of a button based upon the content of a text area field (multi line edit box). it should contain at least some text.
I could use the onkeypress event (server) and perform a partial refresh on the button BUT I notice that the partial refresh spinner appears then when users are writing in the field. I would like to avoid this.
What options do I have?

A: You would be best off writing a client side script for that event.  This script should show the button when there are more than 200 characters in the textarea.  You will need to set the style visibility to hidden for the button initially.  If the form can be edited multiple times, you will need to write this as a function and call it on page load as well as in the keypress event.
If you can use the keyup event instead of keypress, this may be better.
var textareaID = '#{id:textareaID}';
var buttonID = '#{id:buttonID}';
var textareaValue = document.getElementById(textareaID).value;
var visibility;

if (textareaValue.length > 200) {
    visibility = 'visible';
}
else
{
    visibility = 'hidden';
}
document.getElementById(buttonID).style.visibility=visibility;


text:
Q: Need to Display Admob Ad Through MoPub I want to display an admob Ad Through mopub sdk in one of my iPhone application but i am not able to find the API Password And API Key through Ad Mob.
Can anyone please help me to integrate Admob network in mopub account?

A: API Password and API Key are for the Legacy AdMob integration and are now deprecated. Please use OAuth for Network Revenue Reporting.
You should still be able to display AdMob ads even though Network Revenue Reporting is not enabled on MoPub.
I'd reach out to MoPub Support if you have any issues.
Edward


text: Q: lenovo yoga 300 hard drive error to boot ubuntu I have a laptop Lenovo yoga 300-11 and I'm having trouble installing ubuntu. I'm booting perfectly fine from the usb and everything works perfect with the installation but when the laptop is restarting then it says that it cant see the hard drive to boot and open Ubuntu. Thanks is advance.


text:
Q: For Loop in Django Template I am working on a Django project. It has two Apps, one for explaining the topic, which has its own model, and views, and the second app is a quiz app, which has its own model and view, which will test the ability / learning of the students on each topics.
The main idea is that for each topic of each book, there will be a quiz to test the ability of the students.
my book explanation model is as follows:
class book_explination(models.Model):
    title = models.CharField  (max_length = 255)
    slug = models.SlugField(max_length= 250, null = True, blank = True, unique= True)
    lesson_no = models.CharField  (max_length = 255)
    book_text = models.TextField  (blank=False, null=False)
    book_text_explination = models.TextField (blank=False, null=False)
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, null= True, blank=True)
    timestamp = models.DateField(auto_now=False, auto_now_add=True)

    def __str__(self):
        return self.title

my view for the course model is as follows:
def maths_topics(request):
    content_list = book_explination.objects.filter(title = "maths")
    return render(request, 'blog/maths_topics.html', {'content_list': content_list})

my url on url.py file is as under:
path('nahwa_meer_topics/', maths_topics, name = 'maths_topics'),

my quiz model is as follows:
class Quiz(models.Model):
    title = models.CharField(max_length=255)
    book_name = models.CharField(max_length=255)
    slug = models.SlugField(blank = True)
    topic = models.CharField(max_length=255)
    number_of_questions = models.IntegerField()

    class Meta:
        verbose_name_plural = 'Quizes'

    def __str__(self):
        return self.title

my view for the quiz app is as follows:
def maths_quiz(request):
    maths_quiz = Quiz.objects.filter(book__name = "maths")
    return render(request, 'blog/maths_topics.html', {'maths_quiz': maths_quiz})

my django HTML template is as under:
{% for c in content_list %}

        {% if c.title == "maths"  %}

  {{ c.title }}

  {{ c.lesson_no }}

  {{ c.book_text }}

        {% endif %}

{%endfor%}

{% for c in maths_quiz %}

        {% if c.name == "maths"  %}

  {{ c.topic }}

  {{ c.title }}

        {% endif %}

{% endfor %}

the HTML template is reflecting the maths book explanation, however, it is not showing the quiz part of the data.
My aim is to show the topics of a book in an html page, and in front of each topic there should be the quiz, related to that topic, bearing in mind that each topic will have it own separate quiz.
Thanks for your support and help. Looking forward for a positive response from your end.
Regards

A: If I understand this correctly, the maths_quiz variable holds a queryset of Quiz instances. In your template logic, you display a list item, if an instance's name attribute is "maths". However your Quiz model has no name field at all. Could it be that you meant to check the book_name attribute instead?
{% for c in maths_quiz %}

        {% if c.book_name == "maths"  %}
        ...
        {% endif %}

{% endfor %}

Additionally, I think you made an error in your query to begin with:
...
maths_quiz = Quiz.objects.filter(book__name = "maths")

There are two underscores in book__name, but your field has only one:
class Quiz(models.Model):
    ...
    book_name = models.CharField(max_length=255)

Moreover, I just noticed that your whole if condition in the template seems to be redundant since you are doing that exact filtering in your query in the view function before passing the results to the template. So there is really no need to check the book_name again in the template. Every instance in that queryset will have book_name == "maths".
Same goes for the maths_topics view.

Finally, I assume that either the HTML is actually two separate templates or if not, that you are aware that only one of the two sections will ever be displayed depending on the view that is called, maths_topics or maths_quiz, not both.

As a side note: I would suggest using more descriptive variable names, if possible. Seeing as you are working with multiple Quiz instances, I would name the variable something like maths_quizzes and for the iteration I would use a name like quiz instead of c:
def maths_quiz(request):
    maths_quizzes = Quiz.objects.filter(book__name = "maths")
    return render(request, 'blog/maths_topics.html', {'maths_quizzes': maths_quizzes})

{% for quiz in maths_quizzes %}
...
{% endfor %}

EDIT
OK, now that you explained a bit more, it seems you do think that both querysets should appear somehow. You have two separate views. They render separate responses. If you want both querysets passed to your template data, then you should do that in one view:
def maths_view(request):
    content_list = book_explination.objects.filter(title = "maths")
    maths_quiz = Quiz.objects.filter(book_name = "maths")
    return render(
        request,
        'blog/maths_topics.html',
        {'content_list': content_list, 'maths_quiz': maths_quiz}
    )

Then obviously you need to adjust your URL route to point to that view, something like this (for example):
path('yoururlpath/', maths_view, name = 'maths_view')

Also, it seems to me that if your two models are so intimately connected, you may want to consider creating some sort of a relationship between them. Namely, if a quiz is always related to exactly one book, this seems to call for a foreign key relationship from quiz to book.
I mean something like this:
class Quiz(models.Model):
    book = ForeignKey(to=book_explination, ...)
    ...

This would allow you to get all the related objects in the same query.
You can read up on relationships in the Django documentation.


text:
Q: adddate(curdate(), -(day(curdate())-1)) and concat(last_day(curdate()),' 23:59:59') What exactly is this mysql script means time BETWEEN ?
     ADDDATE(CURDATE(), -(DAY(CURDATE())-1)) AND CONCAT(LAST_DAY(CURDATE()),' 23:59:59')

A: DAY(CURDATE())-1 is the current day of the month, less 1. For today (Aug 15, 2013), the value would be 14. Subtract 14 days from August 15 and you have August 1. In other words, ADDDATE(CURDATE(), -(DAY(CURDATE())-1)) gives you the first day of the month.
LAST_DAY(CURDATE()) gives you the last day of the month. If you call it today it will return August 31, 2013. Append the 23:59:59 and you have the last second of the last day of the month.
In other words, if called on August 15, 2013, the values come out as 2013-08-01 and 2013-08-31 23:59:59. If this range is applied against a DATETIME value, it means "anything in the month of August 2013".
This is actually a pretty good way to check for date/time values within a month because it avoids using a function on the MySQL column that holds the date/time. If the column has an index, the index will (probably) be used for optimization. One approach I often see is this:
WHERE DATE_FORMAT(myDateTime, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m')

This reads a little better, but it kills optimization. I'd stick with the expression you already have.


text:
Q: fancybox opening on refresh not click I've been sitting for days going through blogs, code, forum anything that would help me solve the problem.
What I'm trying to do is show a thum image on a page with a summary of information, that on click a bigger image opens in fancybox.
But I have all images in a mysql database and a php page that calls them, here's the code and scripts I'm using.

<link rel="stylesheet" type="text/css" href="../source/jquery.fancybox.css?v=2.1.5" media="screen" />

I have the thumb showing and on page refresh it goes to the fancybox, but on click goes to the /images/big_pic.php?id=905.
I am wanting to use fancybox on several sites and want to buy the licence, but there's no point in buying it if it won't work! Going absolutely nuts with this.
Hoping someone can help me.

A: 1). You need to have at least this jQuery code :

2). If you also want the link to show fancybox on page load, just trigger a click on the same selector like :

... and you will have the double functionality you are looking for.
3). On the other hand, if you have a gallery and you are triggering it on page load, use the method .eq() to make sure that the first element of the gallery will be triggered like

See JSFIDDLE

A: I'm pretty sure the line $.fancybox({... triggers the lightbox on load but you're not actually making specific links "lightbox" links yet. Add the extra line pointed out below to your JS section to resolve this problem.


text:
Q: Show WiFi List and Connect WiFi from command line interface in Ubuntu 16.04 I use ubuntu 16.04. I have design one webpage,in webpage They show wifi list Then I select one wifi network and enter password of this network.
So I will make 2 scripts,they running in background on my system.
in first script they show wifilist of my system in json form.
In second script, I store ssid and password in json file and then i write on my wifi-config file.
Please guide me to making two scripts, what command I use to connect my wifi and where I store my wifi password?


text:
Q: C++ Thread safe queue shutdown I'm using this class for producer-consumer setup in C++:
#pragma once

#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <atomic>

template <typename T> class SafeQueue
{
public:
    SafeQueue() :
    _shutdown(false)
    {

    }

    void Enqueue(T item)
    {
        std::unique_lock<std::mutex> lock(_queue_mutex);
        bool was_empty = _queue.empty();
        _queue.push(std::move(item));
        lock.unlock();

        if (was_empty)
            _condition_variable.notify_one();
    }

    bool Dequeue(T& item)
    {
        std::unique_lock<std::mutex> lock(_queue_mutex);

        while (!_shutdown && _queue.empty())
            _condition_variable.wait(lock);

        if(!_shutdown)
        {
            item = std::move(_queue.front());
            _queue.pop();

            return true;
        }

        return false;
    }

    bool IsEmpty()
    {
        std::lock_guard<std::mutex> lock(_queue_mutex);
        return _queue.empty();
    }

    void Shutdown()
    {
        _shutdown = true;
        _condition_variable.notify_all();
    }

private:
    std::mutex _queue_mutex;
    std::condition_variable _condition_variable;
    std::queue<T> _queue;
    std::atomic<bool> _shutdown;
};

And I use it like this:
class Producer
{
public:
    Producer() :
        _running(true),
        _t(std::bind(&Producer::ProduceThread, this))
    { }

    ~Producer()
    {
        _running = false;
        _incoming_packets.Shutdown();
        _t.join();
    }

    SafeQueue<Packet> _incoming_packets;

private:
    void ProduceThread()
    {
        while(_running)
        {
            Packet p = GetNewPacket();
            _incoming_packets.Enqueue(p);
        }
    }

    std::atomic<bool> _running;
    std::thread _t;
}

class Consumer
{
    Consumer(Producer* producer) :
        _producer(producer),
        _t(std::bind(&Consumer::WorkerThread, this))
    { }

    ~Consumer()
    {
        _t.join();
    }

private:
    void WorkerThread()
    {
        Packet p;

        while(producer->_incoming_packets.Dequeue(p))
            ProcessPacket(p);
    }

    std::thread _t;
    Producer* _producer;
}

This works most of the time. But once in a while when I delete the producer (and causing it's deconstructor to call SafeQueue::Shutdown, the _t.join() blocks forever.
My guess is the that the problem is here (in SafeQueue::Dequeue):
while (!_shutdown && _queue.empty())
        _condition_variable.wait(lock);

SafeQueue::Shutdown from thread #1 gets called while thread #2 finished checking _shutdown but before it executed _condition_variable.wait(lock), so it "misses" the notify_all(). Can this happen?
If that's the problem, what's the best way to solve it?

A: Since the SafeQueue object is owned by the producer, deleting the producer causes a race condition between the consumer being notified and the SafeQueue being deleted out from under it when ~Producer completes.
I suggest having the shared resource being owned by neither the producer nor consumer, but passed as a reference to the constructor of each.
Change the Producer and Consumer constructors;
Producer( SafeQueue<Packet> & queue ) :
    _running(false), _incoming_packets(queue) {}

Consumer( SafeQueue<Packet> & queue ) :
    _running(false), _incoming_packets(queue) {}

Use your instances this way;
SafeQueue<Packet> queue;
Producer producer(queue);
Consumer consumer(queue);

...do stuff...

queue.shutdown();

This also resolves a poor design issue you have in the Consumer class being so tightly coupled to the Producer class.
Also, it's probably a bad idea to kill and join threads in a destructor, as you do for ~Producer. Better to add a Shutdown() method to each thread class, and call them explicitly;
producer.shutdown();
consumer.shutdown();
queue.shutdown();

Shutdown order doesn't really matter, unless you are concerned about losing unprocessed packets that are still in the queue when you stop the consumer.

A: In your SafeQueue::Dequeue, you are probably using std::condition_variable the wrong way... Change this:
bool Dequeue(T& item)
{
    std::unique_lock<std::mutex> lock(_queue_mutex);

    while (!_shutdown && _queue.empty())
        _condition_variable.wait(lock);
    if(!_shutdown)
    {
        item = std::move(_queue.front());
        _queue.pop();
        return true;
    }
    return false;
}

to
bool Dequeue(T& item)
{
    std::unique_lock<std::mutex> lock(_queue_mutex);
   _condition_variable.wait(lock, []{ return _shutdown || !_queue.empty() });
    if(!_shutdown)
    {
        item = std::move(_queue.front());
        _queue.pop();
        return true;
    }

    return false;
}

Secondly, the order of initialization of the data members in Consumer isn't right with regards to its constructor
class Consumer
{
    Consumer(Producer* producer) :
        _producer(producer),
        _t(std::bind(&Consumer::WorkerThread, this))
    { }
    ......
    // _t will be constructed first, regardless of your constructor initializer list
    // Meaning, the thread can even start running using an unintialized _producer
    std::thread _t;
    Producer* _producer;
}

It should be reordered to:
class Consumer
{
    Consumer(Producer* producer) :
        _producer(producer),
        _t(std::bind(&Consumer::WorkerThread, this))
    { }
    ......
    Producer* _producer;
    std::thread _t;
}

Another part of your problem is covered by CAB's answer


text:
Q: How can I get the document from Firebase Firestore with particular value in field? I'm creating todo list in which I'll have two lists one for incomplete tasks and another for completed tasks...I'm able to retrieve the data from Firestore by pulling the whole data without any condition, but for the uncompleted list, I want to retrieve the document only with particular field values. For example, each document contains the following fields as shown in the picture:
Here is the code which I've used to get the data from firebase firestore:
static List<Task> getTasks() {
    //convert firebase collection to list
    List<Task> tasks = [];
    FirebaseFirestore.instance.collection('Todos').snapshots().listen((data) {
      data.docs.forEach((doc) {
        tasks.add(Task.fromMap(doc.data()));
      });
    });
    return tasks;
  }

I want similar function like this to retrieve only documents with taskStatus == true. So, I can store all those tasks which have taskStatus of true on separate list and display them accordingly.

A: You can use the where function. It works like below.
For more: Cloud FireStore Filtering
FirebaseFirestore.instance
  .collection('Todos')
  .where('taskStatus', isEqualTo: true)
  .snapshots().listen((data) {
    data.docs.forEach((doc) {
      other_tasks.add(Task.fromMap(doc.data()));
    });
  });


text:
Q: Is the radical of an irreducible ideal irreducible? I originally posted this to math.stackexchange.com
here.  I got a partial answer, but I now suspect that the complete answer is much harder than I thought, so I'm posting it here.
Fix a commutative ring $R$.  Recall that an ideal $I$ of $R$ is irreducible if $I = J_1 \cap J_2$ for ideals $J_1$ and $J_2$ only when either $I = J_1$ or $I = J_2$.
Question : Assume that $I$ is an irreducible ideal.  Must the radical of $I$ be an irreducible ideal?
On math.stackchange.com, I learned that the answer is "yes" if $R$ is Noetherian.  My guess is that there is a counterexample if $R$ is not assumed to be Noetherian, but I have no idea how to construct it.

A: I construct a counterexample for your question in the non-noetherian case:
(1) Let $A = k[[X,Y]]/(XY) = k[[x,y]]$, where $k$ be a field. Notice that $(0) = (x) \cap (y)$ so $(0)$ is reducible in $A$.
(2) We consider the injective hull $E(k)$ of $k$, and set $m \in E(k)$ be the element such that $mA \cong k$. Notice that every non-zero submodule of $E(k)$ contains $mA$ and $(0)$ is irreducible in $E(k)$
(3) Set $R = A \ltimes E(k)$ be the indealization. We have that $(0 \ltimes E(k))^2 = 0$ so $\sqrt{(0)R} = 0 \ltimes E(k)$ is reducible by (1).
(4) We can prove that for every non-zero element $(a,s)$ of $R$, we have $0 \ltimes mA \subseteq (a,s)R$. So the ideal $(0)$ is irreducible in $R$.
EDIT (13/02): It should be noted that this example is also a counterexample for a non-noetherian ring with an ideal is irreducible but not primary. Indeed, we have $(0)$ is irreducible as above. However
$$(x,0).(y,m) = (0,0) \in R,$$
and $(x,0)$ and $(y,m)$ are not nilpotent so $(0)$ is not primary in $R$


text:
Q: Add a custom attribute to socket.io and get this value in the server I'm trying to extend a property to my socket.io in the client side, with a custom value, like:
var socket = io();
socket.customAttr = "123"

and get this value in a node server, but I'm extending this functionallity in the client side, but in the server is always undefinded.
Exist a way to add customAttributes to the my socket.io?

A: For some one who finding a solution for this old question: Now (v4.x) you can use socket.handshake.query.
Client:
import { io } from "socket.io-client";
const socket = io({ query: { x: 42 } });

Server:
io.on("connection", (socket) => {
console.log(socket.handshake.query); // prints { x: "42"}
});