text:
Q: Compile error on if else condition in trigger  create or replace
  TRIGGER TRG_DEPT_ID BEFORE INSERT ON DEPT FOR EACH ROW
  BEGIN
  IF NOT EXISTS (SELECT * FROM DEPT cd WHERE cd.st_num = :new.ST_NUMBER AND cd.td_NUMBER = :new.TD_NUMBER)
  THEN
        SELECT SEQ_DEPT_ID.NEXTVAL INTO :new.ID FROM dual;
  ELSE
        SELECT ID FROM DEPT INTO :new.ID WHERE cd.st_num = :new.ST_NUMBER AND cd.td_NUMBER = :new.TD_NUMBER;
  END IF;
  END ;

I am trying to check for duplicate entry. If not exists, then I will create a new Id from sequence. Else I will put the same id.
  And the SaveOrUpdate(dept); will do the remaining.
But it gave me compile error.Error(8,9): PL/SQL: SQL Statement ignored.
UPDATE:
When I tried the following query:
CREATE OR REPLACE TRIGGER TRG_DEPT_ID
BEFORE INSERT ON DEPT FOR EACH ROW
BEGIN
     BEGIN
          SELECT ID
          INTO :NEW.ID
          FROM DEPT
          WHERE cd.st_num = :NEW.ST_NUMBER
          AND cd.td_NUMBER = :NEW.TD_NUMBER;
     EXCEPTION WHEN no_data_found THEN
          SELECT SEQ_DEPT_ID.NEXTVAL INTO :new.ID FROM dual;
     END;
END;

Getting the error:
ORA-01422: exact fetch returns more than requested number of rows
How to handle this error?

A: You can simply code your trigger like this,
CREATE OR REPLACE TRIGGER TRG_DEPT_ID
BEFORE INSERT ON DEPT FOR EACH ROW
BEGIN
     BEGIN
          SELECT ID
          INTO :NEW.ID
          FROM DEPT
          WHERE cd.st_num = :NEW.ST_NUMBER
          AND cd.td_NUMBER = :NEW.TD_NUMBER
          AND rownum = 1;    --Use rownum = 1 to avoid selecting too many rows.
     EXCEPTION WHEN no_data_found THEN
          SELECT SEQ_DEPT_ID.NEXTVAL INTO :new.ID FROM dual;
          --:NEW.id = seq_dept_id.nextval; -- Or you can use this if you are using 11g or higher versions.
     END;
END;

Edited:
You can modify your trigger code as below if duplicate entries are there in your table.
CREATE OR REPLACE TRIGGER TRG_DEPT_ID
BEFORE INSERT ON DEPT FOR EACH ROW
DECLARE
     l_id DEPT.id%type;
BEGIN
     BEGIN
          SELECT ID
          INTO l_id
          FROM DEPT
          WHERE cd.st_num = :NEW.ST_NUMBER
          AND cd.td_NUMBER = :NEW.TD_NUMBER
          AND ROWNUM = 1;    --Use rownum = 1 to avoid selecting too many rows.
          IF l_id IS NOT NULL THEN --If same st_number and td_number exists.
               raise_application_error( -20001, 'Duplicate entry.');
          END IF;
     EXCEPTION WHEN no_data_found THEN
          SELECT SEQ_DEPT_ID.NEXTVAL INTO :new.ID FROM dual;
          --:NEW.id = seq_dept_id.nextval; -- Or you can use this if you are using 11g or higher versions.
     END;
END;

A: try adding rownum in the where section :
CREATE OR REPLACE TRIGGER TRG_DEPT_ID
BEFORE INSERT ON DEPT FOR EACH ROW
BEGIN
    BEGIN
       SELECT ID
       INTO :NEW.ID
       FROM DEPT
       WHERE cd.st_num = :NEW.ST_NUMBER
       AND cd.td_NUMBER = :NEW.TD_NUMBER
       AND ROWNUM =1;
 EXCEPTION WHEN no_data_found THEN
      SELECT SEQ_DEPT_ID.NEXTVAL INTO :new.ID FROM dual;
 END;
END;

That will make the query to just return 1 row in case cd.st_num and cd.td_NUMBER are repeated in more than one row.
On the other hand, if you need to detect that there are more than one row for these two columns , you can catch the exception TOO_MANY_ROWS in the exceptions section
     EXCEPTION WHEN no_data_found THEN
      SELECT SEQ_DEPT_ID.NEXTVAL INTO :new.ID FROM dual;
     when TOO_MANY_ROWS then
         -- your logic to do when there are too many rows
 END;


text:
Q: Connect a Manifest Version 3 Chrome Extension to a firestore database The Problem
I'm writing a chrome extension that users will use to fill forms using content hosted in a firestore database.  The core problem I'm facing is that Chrome Extension's Manifest Version 3 does not appear to support any of google's mechanisms for interacting with firestore.
Previously, with Manifest Version 2, you'd link to the CDN hosted firebase scripts in your background.html file like so:
<script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-firestore.js"></script>

With MV3, remotely hosted code is no longer allowed for security reasons, despite the fact that the script I'm trying to link to is google's, and attempting to do so throws errors as soon as you load the unpacked extension.
My question:
How can I connect a Manifest Version 3 Chrome Extension to a firestore database?
What I've tried
I spent quite a lot of time experimenting with pulling the cdn scripts locally and then importing them directly into my background.js like so:
try {
    importScripts('firebase/firebase-firestore.js');
} catch (error) {
    console.log(error);
}

This approach led me deep down a rabbit hole because this also did not work but apparently for different reasons.  Specifically, with MV3, XMLHttpRequest is not supported in a service worker.
Possible next steps
From the reading I've done, and I really hope somebody here can point me to something I've missed, it appears that it will not be possible to connect firestore to an extension directly.  I have read elsewhere that the firebase realtime data base can be accessed via a MV3 chrome extension.
Setting up some link between firestore and the realtime database for the relevant content our users need to be able to access with the chrome extension and then connecting the realtime database to the extension seems like it is the next step.  Is this viable?
Why not use Manifest Version 2?
Simply to future proof our app, we don't want to be left scrambling when MV2 is deprecated.  While no deprecation date for MV2 appears on any official channel, the chromium blog says:

"While there is not an exact date for removing support for Manifest V2
extensions, developers can expect the migration period to last at
least a year from when Manifest V3 lands in the stable channel."

Which puts MV2's end of life sometime early in 2022.
Edit to add:
They announced some hard dates, January 2022 they stop accepting new MV2 extensions but maintenance of those already existing may continue until January 2023 when all extensions must be MV3.

A: I've just seen this question because I'm just doing an extension with manifest v3 and firebase and I've been with the same problem for about two days but I think I've finally reach a solution.
Import the firebase files
First of all there's the problem of manifest v3 not accepting extern files. In their doc they say that you can use npm install firebase and follow their doc in order to connect it but this is still broken.
What I've done is download the files from the urls of firebase and create a folder with all of them inside.
Those URLS have this pattern:
https://www.gstatic.com/firebasejs/VERSION/firebase-SERVICE.js --> (where VERSION is the SDK version such as 9.6.4 and SERVICE is an SDK name such as firebase-firestore)
All these files can be in a folder just like this:

Connect to firebase
Then you must create your background file. In my case I've called it firebase.js . In this file the first lines will be the imports
import { initializeApp } from "/firebase/firebase-app.js";
import { HERE YOU WRITE THE SERVICES YOU WANT } from '/firebase/firebase-auth.js';
import {HERE YOU WRITE THE SERVICES YOU WANT} from '/firebase/firebase-firestore.js';

As you can see you must use the relative path to the files.
One important thing you must know is that all service files of firebase depends on firebase-app.js so you must edit its imports to the relative path of the firebase-app.js in your project.
Then you must declare the firebase config:
const firebaseConfig = {
    apiKey: "///////",
    authDomain: "///////",
    projectId: "///////",
    storageBucket: "///////",
    messagingSenderId: "///////",
    appId: "///////",
    measurementId: "///////"
};

(You can find this information in the project settings page of firebase)
Finally you must initalize your firebase app and all the services just like this (example with the auth and firestore services):
const firebase = initializeApp(firebaseConfig);
const auth = getAuth(firebase);
const db=getFirestore(firebase);

Adapt the manifest file
Because you are using imports, your background.js (firebase.js in my case) must be module so in your manifest.json file write the following:
"background": {
    "service_worker": "firebase.js",
    "type": "module"
  }

The next steps depends of the service you want to use. From here the documentation is good enough.
Finally one quick warning. Because of how manifest v3 works I think some services don't work at all but I'm not quite sure.
Hope this helps you or anyone with this problem :D

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pygame Scrolling Map Advanced I'm working in a rogue-like and I've manage to implement a camera on the player, the camera shows just the players surroundings and is fixed in the side of the windows.
The problem is, when the player is close to the sides of the map there's a black space in the surface.
Like so:

How do I make the camera 'snap' to the side and don't go any further?
To draw the map

*

*I took the Camera Rect positions [topleft and bottomright];

*Converted it to World Position;

*Iterate over it, with a enumerator too;

*Did any lit/visited FOG calcunations with X and Y;

*And Blited in the screen using the enumerators 'i' and 'j'.

Here's the code:
topleft = Map.toWorld(camera.rect.topleft)
bottomright = Map.toWorld(camera.rect.bottomright)
for i, x in enumerate(xrange(topleft[0], bottomright[0])):
    for j, y in enumerate(xrange(topleft[1], bottomright[1])):
        tile = mymap.tileAt(x, y)
        object = [obj for obj in Object.OBJECTS if obj.pos == (x,y)]
        if tile:
            lit = field_of_view.lit(x, y)
            visited = field_of_view.visited(x, y)
            graphic = tile.graphic
            if lit:
                color = tile.color
            elif visited:
                color = GRAY
            else:
                color = BLACK
            renderedgraphic = myfont.render(ch, 1, graphic)
            screen.blit(renderedgraphic, Map.toScreen((i + 1, j)))
        if object:
            Draw.drawObject(object[0], Map.toScreen((i + 1, j)))

I'm bashing my head in this problem for the whole day and that's the further I got.
I saw HERE a exemple of this but I couldn't adapt the code to my game because it uses sprites.

A: I guess that your camera object is not tied to a player in any way.
The is no problem to stop the camera at the corners. You can have a big rect representing the world map, and call cameraRect.clamp_ip(mapRect).
The real issue, is returning the camera to have the player at the center. With the simple check above, the player would stay on the corner of the camera.
If you change the camera to follow, the player when possible, it would work. A bit of pseudocode:
Check if player is not in the center of camera
    Check direction of player movement - if moving towards the center of camera
        do nothing
Else
    Check direction of player movement
    Try to move camera


text:
Q: Convert Array into Object and paste values into a different column I have a column that contains a text like this on each row (text is different) - ABC1 London - ACompany: Ground Floor, Main Tower, 127 Bridge Street, London AB1 1JZ.
The script I have extracted the city name from that text and store it into a new array.
When I try to write those values into a new column I get Cannot convert Array to Object[][]. (line 18, file "Code").
I have tried to loop through that array again, but it returns 101 arrays (I have 101 rows) so when I set cities[0].length as width it pastes it on 101 column.
All I need is to get the city name from the text and paste it on the same sheet to a different column - Ex. the text is on column B12 and I want to paste just the city name into R12 - hope it makes sense.
Please see below the code I have
function getCity() {
  var ss = SpreadsheetApp.openById('ID');
  var sh = ss.getSheetByName('Response Data');
  var range = sh.getDataRange();
  var values = range.getValues();
  var cities = [];
  var newCity = []
  for (var i=1;i<values.length;i++)
  {

    var cellText = values[i][11];
    if(typeof cellText === 'number') {continue;};
    cities.push(cellText.substring(5, (cellText + " -").indexOf("-") - 1));
  }

  Logger.log(cities);

  sh.getRange(2, 18, cities.length, 1).setValues(cities);

}

Thank you!

A: Try this code and see if you're getting the same error,
function getCity() {
  var ss = SpreadsheetApp.openById('ID');
  var sh = ss.getSheetByName('Response Data');
  var range = sh.getDataRange();
  var values = range.getValues();
  var cities = [];
  var newCity = []
  for (var i=1;i<values.length;i++)
  {
    var cellText = values[i][11];
    if(typeof cellText === 'number') {continue;};
    cities.push([cellText.substring(5, (cellText + " -").indexOf("-") - 1)]);
  }
  Logger.log(cities);
  sh.getRange(2,18,cities.length,1).setValues(cities);
}


text:
Q: Portable Class Library assembly reference problems in MonoDroid and MonoTouch I have problem in my project where I have PCL for .Net 4.5, Windows Phone 8, WinRT, MonoTouch and MonoDroid, when I try to build MonoDroid or MonoTouch project that have reference to that PCL errors are following:

*Error 1 The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime,
  Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Error 2 The type 'System.Enum' is defined in an assembly that is not
  referenced. You must add a reference to assembly 'System.Runtime,
  Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

I have done suggested command (sn -Vr *,b03f5f7f11d50a3a), but it didn't help. I am using the following profile:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile78

A: If you set the compability to from .NET 4.5 to .NET 4.0.3 it will work.

A: When I've encountered similar errors in profile 104, then I've built fake System assemblies like System.Windows.dll and System.Net.dll which type forward the classes in question. I've delay signed these fake assemblies - fortunately MonoDroid and MonoTouch don't seem to check these delay signings too carefully.
The examples of these are at: https://github.com/slodge/MvvmCross/tree/v3/PortableSupport
I would guess you could do the same thing with 2 System.Runtime assemblies linked against MonoDroid and MonoTouch and type-forwarding System.Object and System.Enum.
Hopefully Xamarin's PCL support will ship soon - and will include official version for these shim assemblies.


text:
Q: Does SingleOrDefault() query remotely? Consider an environment with various computers at different locations. These computers have a Windows application running and a timer checking for new data to sync every 5 minutes. Information is synced to a centralised location over an internet connection. The database on both the client computers and the centralised server is an SQL Server database.
Before writing into the remote (centralised) server, the SingleOrDefault() method is used to check whether a record with the same ID exists remotely or not. The client has reported a surge in internet data used. I am wondering whether the centralised database has grown too large and the SingleOrDefault returns the whole queryable data over the connection and does the querying client side. Could this be the case? And what would be an alternate solution that does not do the same thing?

A: If you are using Queryable.SingleOrDefault then it will be processed on the server (if you log the database queries you can see the use of top 2 in the select1).
However if you are using Enumerable.SingleOrDefault then it will be processed on the (database) client.
You need to avoid converting from IQuerable<T> to IEnumerable<T> (eg. by use of AsEnumerable).
Detecting this can be done with code inspection or by looking at the generated SQL.
1 top 2 is used to detect more than a single result, which is an error when using SingleOrDefault.


text:
Q: NodeJS SyntaxError: Unexpected token '.' Beginner to Node JS and NPM. The following code throws a Syntax error and can't figure out the issue.
Node version: v12.18.3
NPM version: 7.15.1
Error
LayerObj.options?.["displayName"] != undefined
                       ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/Applications/MAMP/htdocs/nft-generators/hashlips_art_engine-main/index.js:2:39)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)

Code
const layersSetup = (layersOrder) => {
  const layers = layersOrder.map((layerObj, index) => ({
    id: index,
    elements: getElements(`${layersDir}/${layerObj.name}/`),
    name:
      layerObj.options?.["displayName"] != undefined
        ? layerObj.options?.["displayName"]
        : layerObj.name,
    blend:
      layerObj.options?.["blend"] != undefined
        ? layerObj.options?.["blend"]
        : "source-over",
    opacity:
      layerObj.options?.["opacity"] != undefined
        ? layerObj.options?.["opacity"]
        : 1,
    bypassDNA:
      layerObj.options?.["bypassDNA"] !== undefined
        ? layerObj.options?.["bypassDNA"]
        : false,
  }));
  return layers;
};

A: Optional chaining (?.) was added in Node.js 14 and is not directly available in Node 12.

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

Use a more recent version of Node or use Node 12 compatible code.
New JS features in Node.js v14.0 discusses some new language constructs in Node 14.


text:
Q: hibernate component annotation table is it possible to configure Hibernate annotations to store a component class in a separate table?
Take the following example:
@Table(name = "A")
@Entity
public class A implements Serializable {
@Id
public String id;

@OneToMany
@JoinColumn(name="ENTITY_ID", insertable=false, updatable=false)
@NotFound(action=NotFoundAction.IGNORE)
private Set<ComponentObj> components;
....
}

For the component table...
@Table(name = "C")
public class ComponentObj implements Serializable {

@JoinColumn(name="ENTITY_ID")
public String entity_Id;

....
}

When I start to perform unit testing with the above annotations, I get the following exception:
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: ComponentObj

I have declared both classes as annotated classes...

A: I would advise making ComponentObj a real entity, with an identifier, and simply using a OneToMany association.
It's possible to have a colelction of components, but not the way you tried.

*

*the component class must be annotated with @Embeddable

*the collection must be annotated with @ElementCollection

*the component must not have an entity_Id field

*the table to use must be specified using a CollectionTable annotation on the collection

A complete example is available in the javadoc.


text:
Q: How to configure SSL encryption in SQL Server I want to enable the SSL encryption on SQL Server but I am facing the issues on step 8.
Which certificate how have to request?
How can I get the certificate?
Ref link: https://www.mssqltips.com/sqlservertip/3299/how-to-configure-ssl-encryption-in-sql-server/
1.Open the Microsoft Management Console (MMC): click Start, then click Run and in the Run dialog box type: MMC
2.On the File menu, click Add/Remove Snap-in...
3.Select Certificates, click Add.
4.You are prompted to open the snap-in for your user account, the service
account, or the computer account. Select the Computer Account.
5.Select Local computer, and then click Finish.
6.Click OK in the Add/Remove Snap-in dialog box.
7.Click to select the Personal folder in the left-hand pane.
8.Right-click in the right-hand pane, point to All Tasks, and then click
Request New Certificate...
9.Click Next in the Certificate Request Wizard dialog box. Select certificate type 'Computer'.
10.You can enter a friendly name in text box if you want or leave it blank, then complete the wizard.
11.Now you should see the certificate in the folder with the fully qualified computer domain name.


text:
Q: Issue with SQL Join & Exclude Query I have a set of queries that I am trying to run but I am having issues getting them to run together.
My set up is as follows with column names in parantheses:

*

*Table 1 (Email / Date)

*Table 2 (Email / Date_Submitted)

I have written 3 queries which each work perfectly, independent of each other, but I cannot seem to figure out how to connect them.
Query 1 - Distinct Emails from Table 1 (rfi_log)
SELECT DISTINCT email, date_submitted
FROM rfi_log
WHERE date_submitted BETWEEN '[start_date]' AND '[end_date]'

Query 2 - Distinct Emails from Table 2 (masterstudies)
SELECT DISTINCT email
FROM orutrimdb.mastersstudies
WHERE date BETWEEN '[start_date]' AND '[end_date]'

Query 3 - Join Query looking for duplicate emails from Table 1 & Table 2
SELECT rfi_log.email as emails, orutrimdb.mastersstudies.email
FROM rfi_log
    CROSS JOIN orutrimdb.mastersstudies
    ON orutrimdb.mastersstudies.email=rfi_log.email
    WHERE date_submitted BETWEEN '[start_date]' AND '[end_date]';

My issue now is that I need to combine these queries by some fashion so that I can get a count of DISTINCT emails from both tables during the date range while EXCLUDING the emails identified from Query 3.
I need the following:

*

*Query 3 = Count of Distinct Emails

*Query 2 = Count of Distinct Emails (not identified in Query 3)

*Query 1 = Count of Distinct Emails (not identified in Query 3)

Ultimately I need to get a total count of distinct emails during the date range that is "de-duplicated" since there are duplicates located in both tables.
How can this be accomplished?

A: One method for doing this is union all with aggregation.  The following gets duplication information about each email:
select email, sum(isrfi) as numrfi, sum(isms) as numms
from ((select email, 1 as isrfi, 0 as isms
       from rfilog
      ) union all
      (select email, 0, 1
       from orutrimdb.mastersstudies
      )
     ) e
group by email;

An aggregation on top gives you the information you are looking for:
select numrfi, numms, count(*), min(email), max(email)
from (select email, sum(isrfi) as numrfi, sum(isms) as numms
      from ((select email, 1 as isrfi, 0 as isms
             from rfilog
            ) union all
            (select email, 0, 1
             from orutrimdb.mastersstudies
            )
           ) e
      group by email
     ) e
group by numrfi, numms;

Note that this also finds duplicates within a single table.


text:
Q: Required file 'alink.dll' could not be found while building projects I got this error in everyproject I have when I try to build .Im using vs2013 and also vs2012 ,they all give this error and do not build any project.Anyone who had this error before? I tried to reinstall visual studios but didnt change.
any help is appreciated.

A: Either your alink.dll is corrupted in the .net framework folders or the application manifest files are corrupted.
You can try building the application without creating the manifest file.

*

*Open the project properties window

*click Application Tab

*locate the manifest dropdown

*choose the option 'Create application without a manifest'

Save and Rebuild

A: Do check your .net framework. I got same error and i found that it was because other prog/software was suppressing the required .net framework version.


text:
Q: Magento 2 is only displaying some products on catalog page I have 17 products added to my magento store all of which are enabled to display on Catalog and Search, but on the catalog page, only 10 products are being displayed and there isn't any pagination  either to display more products. When I looked at the grid.phtml which loads the products, I see these lines
$block->getProductCollection()->getSize()
$block->getProductCollection()->getItems()

When I echo the output of the getSize(), I get 17 , however when I execute
count($block->getProductCollection()->getItems());

I get only 10. I'm not sure what exactly the issue is and why there is a difference in the two outputs and what I need to do to get all the products listed. I'm using the luma theme and running magento 2.2.5.


text:
Q: How to add noise to row/column selection in python I want to select a specific row/column of a matrix i have, the twist however is that i want an added noise in the selection of the chosen row.
Example
I have a matrix m of size 100x100. I now want to select row 40 i.e. m[40,:].
What is actually wanted however is not an array with all values of row 40, but an array along the same axis with a small noise in the row selection. I.e. random values of row 38,39,40,41,42
[[1,2,3,4],
[5,6,7,8],
[9,1,2,3],
[4,5,6,7]]

noisy_selection = m[2,:]

i.e. noise_selection: [4,7,1,6]

A: Assuming this 10x10 input and getting column 3 ± 1:
# setting up example
np.random.seed(0)
a = np.arange(100).reshape(10, 10, order='F')

# target column
col = 3

# noise (+ -1/0/1)
rand = np.random.randint(-1, 2, a.shape[0])
# example:
# array([2, 3, 2, 3, 3, 4, 2, 4, 2, 2])

out = a[np.arange(a.shape[0]), col+rand]
# array([20, 31, 22, 33, 34, 45, 26, 47, 28, 29])

used input:
array([[ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90],
       [ 1, 11, 21, 31, 41, 51, 61, 71, 81, 91],
       [ 2, 12, 22, 32, 42, 52, 62, 72, 82, 92],
       [ 3, 13, 23, 33, 43, 53, 63, 73, 83, 93],
       [ 4, 14, 24, 34, 44, 54, 64, 74, 84, 94],
       [ 5, 15, 25, 35, 45, 55, 65, 75, 85, 95],
       [ 6, 16, 26, 36, 46, 56, 66, 76, 86, 96],
       [ 7, 17, 27, 37, 47, 57, 67, 77, 87, 97],
       [ 8, 18, 28, 38, 48, 58, 68, 78, 88, 98],
       [ 9, 19, 29, 39, 49, 59, 69, 79, 89, 99]])


text:
Q: How making work eslint-plugin-react-native with Atom? I try to make the linter work on Atom, but nothing happens :/
(I get used to work with eslint on Atom but for a new React Native project I'm totally stuck ...) I work with linter and linter-eslint packages for Atom.
Thanks for any help :)
Here is my package.json, configured as it is said here:
https://github.com/intellicode/eslint-plugin-react-native
{
  "name": "RNApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "eslint": "^3.4.0",
    "eslint-plugin-react": "^6.2.0",
    "eslint-plugin-react-native": "^2.0.0",
    "react": "15.3.1",
    "react-native": "0.32.0"
  },
  "plugins": [
    "react",
    "react-native"
  ],
  "ecmaFeatures": {
    "jsx": true
  },
  "rules": {
    "react-native/no-unused-styles": 2,
    "react-native/split-platform-components": 2,
    "react-native/no-inline-styles": 2,
    "react-native/no-color-literals": 2
  }
}

A: I had to replace this:
"ecmaFeatures": {
  "jsx": true
},

by this:
"eslintConfig": {
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    }
  }
},


text:
Q: React Native Android: how to resolve this build error with compileSdkVersion? I'm trying to build my React Native app after adding the react-native-vision-camera library, and I get the following build error:
Execution failed for task ':app:checkDebugAarMetadata'.
> Multiple task action failures occurred:
   > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
      > The minCompileSdk (30) specified in a
        dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
        is greater than this module's compileSdkVersion (android-29).
        Dependency: androidx.camera:camera-view:1.0.0-alpha27.

My android/build.gradle includes the following:
buildToolsVersion = "30.0.2"
minSdkVersion = 21
compileSdkVersion = 31
targetSdkVersion = 31

My understanding from the error is that my compileSdkVersion isn't high enough, and it's saying that it's 29, but in build.gradle I have it at 31.
How can I address this?

A: Try to use the compileSdkVersion and targetSdkVersion with the same version of the buildToolsVersion
try:
buildToolsVersion = "30.0.2"
minSdkVersion = 21
compileSdkVersion = 30
targetSdkVersion = 30

or:
buildToolsVersion = "31.0.0"
minSdkVersion = 21
compileSdkVersion = 31
targetSdkVersion = 31


text:
Q: How to dynamically change the color of text on a material angular2 tab on click? I am using angular2/4 and material
http://material.angular.io/guide/getting-started
My issue is, I want the color of the tab text to change as soon as I click on it.
[ngStyle] appears to not work on the tabs dynamically. I want to customize the color of text in a tab as soon as I click the text on the tab, but nothing changes! How can I get around this?
Note: I do notice that if I click a button to route to another page of my app, then click on another button to come back to the page with the mat-tabs, that I see the color of the text changed.
It appears the backend variable is being updated in variable "listoftabs", but the text color just doesn't change on the fly unless you 're-render' the tabs somehow.
Is there a way around this?
Typescript:
thetab = {isYellow: false, tabname: 'Hello'}

changecolor(tabclicked) {
    tabclicked.isYellow = !tabclicked.isYellow;
}

TEMPLATE
            <mat-tab-group>
                <mat-tab>
                    <ng-template mat-tab-label>
                        Text I Want to Change Color {{thetab.tabname}}
                    </ng-template>

                    Tab Content Here

                </mat-tab>
           </mat-tab-group>

A: You can use the (selectedTabChange) event to tell when the tab has changed and set the style on a tag in the label. See working StackBlitz.
StackBlitz example


text:
Q: How to resize PDF in Acrobat (CS3)? Easy question - I have PDF, which is high resolution, but set to small page.
I just want to take the PDF and resize it.
I have Adobe Acrobat 8 Professional (mac os x version).

A: OK, I answered it myself...
As I said, I use OS X. In OS X, you can print anything from almost any application to PDF.
However, it doesn't work in Acrobat (it tells you to use Save instead of PDF printing). Therefore, I had to open it in Preview and print it to PDF - with different page size - from preview.
...and that's pretty much it.


text:
Q: pentadactyl - Set external editor to be vim termnial Is there nay way we can set vim terminal to be external editor of pentadactyl ? Thanks
I've tried this but it seems to not work:
set editor='vim -f +<line> +"sil! call cursor(0, <column>)" <file>'

P/S: My OS is Mac

A: Since vim is a terminal application, it relies on being run inside a terminal so that it can show its user interface. The terminal is then responsible for rendering all that in the context of the desktop you're using. So, all you need to add to this command is the terminal invocation.
Here's what works for me. I'm using Debian 6 with Gnome, FF20 and the nightly Pentadactyl build (hg6923 today):
set editor='gnome-terminal -e "vim +<line> +\"sil! call cursor(0, <column>)\" <file>"'

You can also (eek!) make it work on Windows, like so:
set editor='cmd /c vim +<line> +"sil! call cursor(0, <column>)" <file>'

We have to add an extra layer of quotes to pass the whole vim execution string to non-Windows terminals, but other than that, it's pretty much the same command. Vim automatically moves to the right file, line, and column when you open the file. It then waits until you exit vim, and, if you're editing an input field, updates that field with the new text.
As a warning, though, the doc does say that there might be problems with some terminals:
:help faq-editor-fork

Why doesn't external input field editing work with my 'editor' setting?
Unfortunately, external editors which return immediately, before editing is complete, are not supported. This means that gvim, for instance, must be run with the -f flag, and editors run from a terminal must not connect to a remote process. In the case of Rxvt-unicode, this means that the urxvtc program is not an option, and Gnome Terminal is very likely not useable under any circumstances.

Confusingly, as we've just seen, gnome-terminal works just fine for me. Caveat editor.


text:
Q: How to choose the right dataType and contentType value for AJAX request? I have written some jQuery + PHP code that takes the HTML from an element on a webpage and saves it on server. Here is the code that I am using:
var page = {
    'html': document.querySelector("article").innerHTML,
    'url': 'path/current/webpage.php' or (<?php echo "'$current_page'"; ?>)
    // Both give same 'url' value. This is not an issue.
};

$.ajax({
    url:'https://example.com/update.php',
    type:'post',
    data: page,
    success:function(data){
        window.location.reload();
    }
});

Here is my code for update.php:
$content = $_REQUEST['html'];
$page = $_REQUEST['url'];
file_put_contents($page, $content, LOCK_EX);

I am not very comfortable with dataType and contentType so I skipped them initially. However the request succeeded sometimes but gave 403() error other times.I did a little research and found that this might be due to lack of dataType and contentType. So, I used the following values:
contentType: 'text/plain; charset=utf-8',
dataType: 'html'

I no longer get any errors but the pages are not actually updating. I also tried setting the values to:
contentType:'application/json',
dataType: 'html'

This time too, I did not get any 403() errors but the page would not actually update.
Does the post data needs to be accessed differently based on the value of contentType like 'application/json' or 'text/plain; charset=utf-8'? Because the updates don't seem to show up on the webpage even with a 200 response code.
Using application/x-www-form-urlencoded; charset=UTF-8 updates some pages but gives 403() error for others.

A: As Rory said (as did I, in an answer I wrote then deleted when I saw his comment; he was right to comment instead), a 403 response code probably doesn't mean there's a problem with either dataType or contentType. You should look for other reasons the server would refuse to satisfy the request. For instance, as you're posting HTML, perhaps you (or your web host) has some kind of anti-script-injection protection going on. You'll have to track that down, perhaps with your hosting company.
But two things: Some info for completeness, and a potential workaround:
dataType is the type you expect back from the server. contentType is the type of data you're sending to the server.
For the request you're sending, leaving off contentType is correct, because the default jQuery will use is what PHP will expect to see.
You shouldn't have to specify dataType at all; instead, you should ensure the response carries the correct Content-Type header. That means ensuring that your server is configured correctly (for static content) and that your PHP code sets the correct header if necessary via header("Content-Type: data/type-here") The only reason for specifying dataType is if you don't control the server and you know it sends back the wrong type.
If you need to try to work around it, first ask: What if someone sends me malicious HTML directly, not through my web page? The answer is: You need to be careful with what you do with the HTML. For example: If you are going to store this HTML and then display it (as HTML) to a user, that's a Cross-Site Scripting vulnerability and you have to rigorously sanitize that HTML before doing that.
Do not proceed with any workaround until you've answered that question for yourself.
Okay, so in terms of working around it (once you have robust safeguards in place): You might send JSON rather than a standard form, in hopes that whatever is rejecting the forms won't look at it. To do that, you'd change your ajax call:
var page = {
    html: document.querySelector("article").innerHTML,
    url: <?php echo "'$current_page'"; ?>
};
$.ajax({
    url:'https://example.com/update.php',
    type:'post',
    data: JSON.stringify(page),
    contentType: 'application/json; charset=UTF8',
    success:function(data){
        window.location.reload();
    }
});

Then on the PHP side, you'd read that JSON and parse it (reading code below taken from this answer):
$entityBody = json_decode(stream_get_contents(STDIN));
$content = $entityBody['html'];
$page = $entityBody['url'];
file_put_contents($page, $content, LOCK_EX);

Again: Please do not use this unless you have robust anti-XSS safeguards in place. And again, if you do haev robust anti-XSS safeguards in place, you might be able to just use a normal form by changing your server config.


text:
Q: WPF BeginInvoke and EntityFramework I have a search through database. Search works in separate thread.
When entity is found I have to show it and some of related data into WPF UI.
I use EntityFramework. Main idea of search process is:
foreach (var item in _currentEntitySet)
{
    Items.Add(item);
    OnItemFound(item);
}

Where _currentEntitySet is an ObjectQuery
But I have met some problems. When OnItemFound is fired, I try to use BeginInvoke() to display found item and some related object in UI.
    private void OnCatalogueItemFound(CatalogueItem item)
    {
        Application.Current.Dispatcher.BeginInvoke(new Action<object>((param) =>
        {
            var model = new CatalogueResultItemViewModel(param as CatalogueItem);
            TitlesResultViewModel.Add(model);
        }), System.Windows.Threading.DispatcherPriority.Background, item);
    }

The problem is that navigation properties of item are NULL
When I use Invoke() instead of BeginInvoke() then things works fine.
I have to use exactly BeginInvoke() because of some other reasons.
Does anyone knows how can I use BeginInvoke() in my situation? Thanks :)

A: I think that this may be because you are generating your object with a lambda function.
BeginInvoke is called asynchroimously and possibly by the time it is actioned the object locatedis no longer in scope.
By using Invoke you force the call to be performed synchronously, when the object is still in scope.


text:
Q: Mobile (Chrome) browser notifications I'm trying to push notifications to a mobile browser.
I followed the documentation from https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API
It's working on Chrome on desktop, but it is not working on mobile, even though the documentation says it should.
I also tried this example https://jsbin.com/ziwod/2/edit?html,js,output as well but it still does not work.
Below you can find my code:

This works on desktop, but not on mobile.
Thank you for your time!

A: Today anyway you can only call Notification.requestPermission from a user-initiated event, like click on this here:
 alert(r))">Yes, allow notifications!


text:
Q: Deal with sudo/interactive input in StartProcess Deal with sudo/interactive input in StartProcess

There is a example in document page of StartProcess
command = "";
process = StartProcess[$SystemShell];
Pause[.1];
processString = ReadString[process, EndOfBuffer];

Column[{
  Pane[Dynamic[processString],
    ImageSize -> {800, 400}, Scrollbars -> True, ScrollPosition -> {-1, -1}],
  InputField[Dynamic[command], String],
  Button["Go!",
    WriteLine[process, command];
    Pause[.1];
    processString =processString <> ReadString[process, EndOfBuffer];]
}]

This is useful, but not enought by now.
How can I do a cmd which need typing password? for example sudo?
For example, one of my purpose is to use this to batch check my hbase, and I need switch to root with ssh, and ssh to the server.
su root, if I do this in the Terminal, I need to type the password
Anyone extented this example of StartProcess?


text:
Q: Android Studio shortcut for autocomplete Toast(Kotlin) I have a problem with the newest version of Android Studio(> 3) to use the autocomplete for Toast with Kotlin.
In older versions with Java, it was like typing "Toast", then pushing "Tab" button on keyboard to autocomplete this.
Now, in the versions of Android Studio > 3 and Kotlin it is not working.
Anyone know how to achive this?

A: Go to Settings > Live Templates. Under Android, find Toast and select it. At the bottom of settings dialog, it says Applicable in Java. Click Change button next to it and select Statement under Kotlin. Done.

A: This is not an exact answer for your question but if you are using the anko
library from Jetbrains (and why wouldn't you?) you can simply show a toast with the line toast("some text")


text:
Q: How can i build string variable of the next file should be created from the known last file? This is the last file:
last_file = fi[fi.Length -1].FullName;

In this case the last_file contain the directory and the file name:
C:\Users\bout0_000\AppData\Local\mws\My Weather Station\radar_temp_directory\radar010286.gif
Now i want to create what should be the next file:
string nextfile =
File.Copy(combinedTemp, nextfile);

combinedTemp is allways the file name untitled.gif
I want to copy this file to C:\Users\bout0_000\AppData\Local\mws\My Weather Station\radar_temp_directory\
As radar010287.gif

A: Assuming fi contains all files named radarNNNNNN.gif where N is 0-9 and the list is ordered, you have a few steps to do:
// Obtain the file with the highest number, but only the filename, not the path
string lastFile = fi[fi.Length - 1].Name;

// Take the number part of the filename
string lastFileNumber = lastFile.Substring(5, 6);

// Parse it as int
int lastNumber = int.Parse(lastFileNumber);

// Increase it by one
lastNumber++;

// Build a new filename
string newFileName = string.Format("radar{0:D6}.gif", lastNumber);

// And make it a full path again by prepending the directory name
newFileName = Path.Combine(radarImagesDirectory, newFileName);

Of course you'll have to include some error handling and include code to make this work when no files are present in the directory.


text:
Q: Passing a function as a prop in Vue js to fetch data I have a component that I would like to be decoupled from the fetching data implementation. So that I can pass fetching data callback as a prop.
I would like to do that so that I can mock the fetching data in storybook.
Request.js
export const endpoints = {
  fetchProducts: page => `https://some-end-point-here?page=${page}`
};

export const fetchProducts = async (page = 1, endpoint = endpoints.fetchProducts(1)) => {
  const response = await fetch(endpoint);
  return await response.json();
};

(storybook) Where component is being used
import {fetchProducts} from "./request";
export const someCPM = ()=> ({
    components: {SomeCPM},
    props: {
        fetchProducts: {default: fetchProducts},
    },
    template: `<product-grid v-bind="$props"></product-grid>`
});

Prop type of component
  fetchProducts: {
    type: Function,
    required: true
  }

Problem is that I keep getting warned about the wrong prop type. Meaning it is getting Promise.
Thus failing to execute as fetch products is not a function.
Even if a make fetchProducts to return number and remove async nature, like this:
const fetchProducts = () => 9999

I am then getting that fetch product is a number, not a function!
This means that even tho I am passing a reference to the function somewhere somehow it is being executed.

A: I had to use factory function to make it work.
export const fetchProducts = () => async (page = 1, endpoint = endpoints.fetchProducts(1)) => {
  const response = await fetch(endpoint);
  return await response.json();
};


text:
Q: Average day values of last month as a SQL statement I got a table with two columns, timestamp (like '1405184196') and value.
I've saved some measured values.
$day= time()-84600;
$result = mysql_query('SELECT timestamp, value FROM table WHERE timestamp >= "'.$day.'" ORDER BY timestamp ASC');

This is how I get all values for the last 24h.
But is it possible to get average day values for the last month with a SQL statement or do I have to select all values of the last month and calculate the average of each day via PHP?

A: Several issues with Anish's answer:
1) This won't work if date+time is being stored in the timestamp field.
2) It assumes the OP means last month i.e June, May etc and not the last say 30 days.
This solves those issues:
SELECT DATE(`timestamp`) as `timestamp`, AVG(value)
FROM table
WHERE `timestamp` >= CURDATE() - INTERVAL 1 MONTH
GROUP BY DATE(`timestamp)

EDIT
Since the timestamp is a unix timestamp and the OP would like a calendar month:
SELECT DATE(FROM_UNIX(`timestamp`)) as `timestamp`, AVG(value)
FROM table
WHERE MONTH(FROM_UNIX(`timestamp`)) = MONTH(NOW() - 1)
GROUP BY DATE(FROM_UNIX(`timestamp))

A: You can do this:-
SELECT timestamp, AVG(value)
FROM table
GROUP BY timestamp
HAVING MONTH(timestamp) = MONTH(NOW()) - 1;

This query calculates average for last month.
DEMO


text:
Q: php server - java client - post and echo i'm completely new to java, php and so on ... so please forgive my stupid question.
I want to write a PHP server application which receives a name from a Java client application. It should respond printing the name on the output and sending a status message (Write failed/success).
How would I get the Java client send the name and receive the reply from the PHP program, and how would the PHP program receive and print the name and send the reply? I have googled a lot: i have found several code examples but the script doesn't work still.
Trying to make it work i've written the following:
Server Side
    <html>
        <head>
            <title>PHP Giulio</title>
        </head>
        <body>
            <?php
$username = "Giulio";
echo "$username";
$username = $_POST['username'];
print "$username";
            ?>
        </body>
    </html>

in this way i thought that before the server had received the name from the client "Giulio" was printed, while, after having received it, the received name would have been printed.
On the other side
Client Side
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.*;

public class JavaPHP {
    public static void main(String[] args){
        URL url;
        try {
            url = new URL("http://www.mydomain.com/myfile.php");
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write("username=NameToBeWritten");
            out.flush();
            out.close();
            InputStream in=connection.getInputStream();
            in.read();
            in.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

well ... i obtain that on the output i see only the name Giulio.
How can i make it receive and print the sent name?
Please help me
Thanks in advance.
Giulio!!

A: You need to set the request method to POST from Java. You can do this by casting connection to an HttpURLConnection and call setRequestMethod("POST") on it:
HttpURLConnection urlCon = (HttpURLConnection) connection;
urlCon.setRequestMethod("POST");

Add it before you call setDoOutput.

A: URL Parameters require a question mark character to successfully interpret your requests.
try to replace
out.write("username=NameToBeWritten");

with
out.write("?username=NameToBeWritten");

And see if that solves the problem, also you might want to add a sleep before opening the input stream since you are immediately opening the input stream to receive the data, and the server might not be done flushing the output to your client side ode... just a thought.
I know the question is old, but let us know if you had any success.


text:
Q: Javascript with HTML *and* input field data I have this script code in a current page I'm working on - it returns the HTML for the document.  The alert was just debug to see if this code was running.  The current HTML it returns is only the last part of the document, but at least it returns something...
<script type="text/javascript">
    function getHtml() {
        var html_source = document.createElement("INPUT");
        html_source.type = "hidden";
        html_source.name = "html_source";
        html_source.value = document.documentElement.outerHTML;
        document.forms[0].appendChild(html_source);
        alert('getHtml(): completed...');
    }
</script>

What I need this code to actually do is return the entire page as the HTML string (this page has lots of text fields and other controls), and I need the HTML to actually be marked up with all field data that is currently filled out on the form.  I think this would mean that the value fields for all text inputs would be modified to contain what the control currently contains, returning the HTML as a string like above.
Does anyone have code that will do this?  The reason I need the HTML like that with all fields filled out is so I can convert the HTML form to a PDF document that already has input field data entered, as if the form was already filled out.
The above script will return the HTML, but if I add data to some of the fields in that section of the HTML document, that data isn't evident in the string that code returns.  I need that code to return all the data as well, associated with each field.
I hope this makes sense; basically I'm trying capture to a 100% an HTML document as a string that was already filled out by a user, at the time they click Submit.  Once I have that string, I can do whatever I want with it including send it to another browser instance where it would be rendered as already filled out, or more to the point for me, to a PDF file renderer, converting the HTML form into a PDF file that is already filled out.


text:
Q: Creating GUI for matrix vector multiplication I am writing a script to perform matrix vector multiplication with GUI using Tkinter of Python. I am new to TKinter and I am trying to learn. I have written the following code for this purpose. The generate_data function gets a a number (e.g. m) and creates a mxmmatrix. In GUI, the user should enter an integer for matrix and an integer for vector and press compute so the matvec function performs the calculation.
I think I have not understood properly some parts but I would need some explanations at this stage. My main challenge is to insert the generate_data function in a way that can be used in GUI to create a random matrix. At the end of code, I have copied the error. Thanks in advance.
import sys
from Tkinter import *
import dotprod

base = Tk()
resultStr = StringVar()
resultStr.set("Enter Matrix1 and Matrix2")

matrixLabel = Label(text = "Enter the size of the matrix:")
matrixLabel.pack()
matrixBox = Entry()
matrixBox.pack()

vectorLabel = Label(text = "Enter the size of the vector:")
vectorLabel.pack()
vectorBox = Entry()
vectorBox.pack()

def generate_data(m):
    test_data = []
    for i in range(m):
        test_data.append([])
        for j in range(m):
            test_data[i].append(random())
    return test_data

def matvec():
    m = int(generate_data((matrixBox.get())))
    v = [2] * len_m
    vec = [0] * len(m)
    for i in range(len(m)):
        vec[i] = dotprod.dotprod(m[i], v)
    resultStr.set("Matrix vector product is " + str(vec))
    return vec

Computebutton = Button(text = "Compute", command = matvec)
Computebutton.pack()
base.mainloop()

Error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
    return self.func(*args)
  File "<stdin>", line 2, in matvec
  File "<stdin>", line 3, in generate_data
TypeError: range() integer end argument expected, got str.

A: What you get from an Entry field is a string type, but range takes an integer type.
Therefore, when you call generate_data(matrixBox.get()), you pass a string to generate_data.
You can solve this by calling generate_data(int(matrixBox.get())) or by adding m = int(m) as the first line of your generate_data function.


text:
Q: What does "Seeding to 3 of 4 connected peers 7kB/s ▲" mean? This is Transmission BitTorrent Client:

What does the "Seeding to 3 of 4 connected peers 7kB/s ▲"?
What is seeding and what are peers? And why does this only appear after it has downloaded? Before it says "Downloading from 60 of 60 peers - 785 kB/s ▼"

A: Some torrent terminology:

*

*Peer: A user who is participating in the torrent.

*Seeder: A peer who keeps the torrent available for uploading. They can be the people who initially uploaded the torrent or those who have finished downloading it and kept it alive.

*Seeding: To keep a torrent alive for uploading once you have finished downloading (either the bits you want or the complete torrent).

Usually, peer just means a peer who isn't a seeder.
In this case, you are seeding. You have a target Upload/Download ratio of 2.0 on both torrents. Once you have uploaded twice as much as you downloaded for the torrent, the application will cease seeding that torrent.

A: Seeders are the peers who have completed downloading the file 100%
A seed is a peer that has a complete copy of the torrent's contents and keeps uploading it.  That can be done by leaving the task running after completing the download.  The more seeders there are, the better the chances of getting a higher download speed.
Peers are people who are downloading the file off the seeders, they also upload a parts of the file too.
Running torrent clients that transfers data to and from other clients, is called a peer. A peer does not have the complete file; only parts of it.
Sometimes peers are also called leeches, which mean downloaders.
some information courtesy of ABIT.CDA11


text:
Q: How to replace switch statement with more flexible code in PHP? I have table called posts in my DB. Each post has field called social_network
When I get all posts into array in my code I need to create instances for each one based on it's social_network field.
Right now I use switch statement for this but I don't like it as it is not flexible.
$posts = DataBase::getPosts(); // pseudocode
foreach($posts as $post) {
  switch($post->getSocialNetwork()){
    case 'Facebook':
      $social = new FacebookPost($post->getId());
      break;
    case 'Twitter':
      $social = new TwitterPost($post->getId());
      break;
    // .... other social networks
  }
}

A: Add an interface to the classes FacebookPost and TwitterPost (eg SocialPostInterface) that has defined same basic necessary methods like getId(), postToNetwork() Then you can add as many new social networks as you want, without having to change this piece of code. They just have to implement the interface
Then experience the power of polymorhpism:
foreach ($posts as $post) {
    $className = $post->getSocialNetwork() . 'Post';
    // lets check if such class exists
    if (!class_exists($className, false /* do not attempt autoload */)) {
        throw new Exception("Unknown social network post class $className");
    }
    $social = new $className($post->getId());
    $social->doSomeStuffThatTheInterfaceHasDeclared();
}

A: I dont think you can avoid this sort of code.  however you may want to move it into an abstract factory, so you don't have to look at it in your controller.
$posts = DataBase::getPosts(); // pseudocode
foreach($posts as $post) {
    $social = SocialFactory::post($post);
  }
}

A: $socialClass = $post->getSocialNetwork() . 'Post';
$social = new $socialClass($post->getId());

You can make a new object from a string holding its name.


text:
Q: Nested Stencil Routes/Components I've been trying to implement nested routes/components. Can someone just please explain to me how to nest routes/components. The stencil route docs aren't of much help.
Say In my component I have on the left a sidenav with a couple of stencil-route-link then on the right I should show the routed component.

A: StencilJS docs state:

You should have one single stencil-router component in your project. This component controls all interactions with the browser history and it aggregates updates through an event system.

So there's going to be one place to define your routes. There's also an example on their webpage:
<stencil-router>
  <stencil-route url="/" component="landing-page" exact={true}/>
  <stencil-route url="/demos" component="demos-page"/>
  <stencil-route url="/demos/rendering" component="fiber-demo"/>
</stencil-router>

Entering /demos/rendering would render both demos-page and fiber-demo components. They won't be nested though.
The docs also mention the routeRender attribute, which can be used to do some sort of nesting. For example:
<stencil-route url="/" exact={true} routeRender={(props) => (
  <app-root history={props.history}>
    <app-sidebar />
    <app-content />
  </app-root>
) />

A: As the Stencil team has still not released a wiki entry for this, here's a little update to this topic using @stencil/core: 1.3.2 and @stencil/router: 1.0.1.
The trick is to use the routeRender property in combination with slots and inline child routes:
<stencil-router>
  <stencil-route-switch>
    <stencil-route url="/"
                   exact={ true }
                   component="app-home"
    />
    <stencil-route url="/me"
                   routeRender={ () => (
                     <app-me>
                       <stencil-route url="/me/login"
                                      component="app-login"
                       />
                       <stencil-route url="/me/profile"
                                      component="app-profile"
                       />
                     </app-me>
                   ) }
    />
  </stencil-route-switch>
</stencil-router>;

If you define the child routes inside your component (in this example app-me) the route may not be recovered after a reload or by navigating directly to it. Thus you have to define them inside your global stencil-route-switch.

A: I know this is kind of old question but took me some time to figure this out, so I want to share here in case someone run into similar issues.
<stencil-router>
  <stencil-route-switch scrollTopOffset={0}>
    <stencil-route url="/" component="app-home" exact={true} />
    <stencil-route url="/profile/:name" component="app-profile" />

    <stencil-route>
      <stencil-route-switch scrollTopOffset={0}>
        <stencil-route url="/" component="app-home" exact={true} />
        <stencil-route url="/profile/:name" component="app-profile" />

        <stencil-route url="/docs" routeRender={()=>

Document Heading

          <stencil-route-link url="/docs/setup">Setup</stencil-route-link>
          <stencil-route-link url="/docs/todo">TODO</stencil-route-link>
          <stencil-route-link url="/docs/profile">Profile</stencil-route-link>

          <stencil-route url="/docs/setup" routeRender={()=>

Set up document
}>
          </stencil-route>
          <stencil-route url="/docs/todo" routeRender={()=>

TODO document
}>
          </stencil-route>
          <stencil-route url="/docs/profile" component="app-home" />

        }>
    </stencil-route>
  </stencil-route-switch>
</stencil-router>

Some quick explanation:

*

*As titsjmen shared, looks like it is important to have only one  component within your app

*You can, however nest "stencil-route" and hopefully with the code example above you can see it how it works. I tested it with both using routeRender as well as component approach (both works!)

Hopefully this will be useful to someone :)
EDIT (additional note):
In case this is not clear, this code block represents the area where you want to swap components based on the URL - back to original question, to achieve what you want, side nav can be just a matter of having bunch of "stencil-router-link" (which doesn't have to be placed in the same component - I have separate component called "sidenav-item" and seem to work well)


text:
Q: Permission denied raised from decorator django I have an Image model that has a user field foreignkey from django user
class Image(models.Model):
    image = models.ImageField()
    user = models.ForeignKey(User)
    #more specific model fields

I want media files to be served only to users that are logged in and uploaded the media. So I used X-SendFile header in apache using the following view
@owns_media
def media_xsendfile(request, path):
    print "inside media_xsendfile view"
    print os.path.join(settings.MEDIA_ROOT,path)
    response = HttpResponse()
    response['Content-Type']=''
    response['X-Sendfile']= smart_str(os.path.join(settings.MEDIA_ROOT, path))
    return response

The owns_media is a decorator that checks if the user logged in is the user that has uploaded the picture and permitts the view to run or raise a PermissionDenied exception. This is the decorator
def owns_media(view):
    """Decorator to check if users has permission to access media"""
    def wrapper(request, *args, **kw):
        path = kw['path']
        user = request.user
        image = Image.objects.get(image=path)
        image_user = image.user
        if user==image_user:
            return view(request, *args, **kw)
        else:
            raise PermissionDenied
    return wrapper

But it won't work. I loggedn in to a user got the picture, then logged out and tried to access it and it did serve the picture while it shouldn't. Am I doing something wrong?


text:
Q: Suppressing default output from gdb when stepping between instructions When I step through a debugging session with gdb, it prints out some information for me. How do I stop this. Here's an example:
Breakpoint 1, 0x100000d4 in ?? ()
(gdb) si
0x100000d8 in ?? ()
(gdb) si
0x100000dc in ?? ()
(gdb)

Here I want to remove the lines that say 0x100000d8 in ?? (). I can't find anything in the documentation about suppressing this output. Any ideas?
Thanks
Tim

A: A bit arcane solution is to define a function that turns on "logging redirect", then steps the instruction and lastly, turns off logging. Example:
define stepix
   set logging redirect on
   set logging file /tmp/whatever
   set logging on
   si
   set logging off
end

but that solution will suppress all output, not just the 0x100000d8 in ?? (). Might not fit your need/taste. I don't think suppressing that output is possible.

A: you can suppress printing the 0x100000d8 with set print address off. looking at the source (search for static void print_frame (...)), i don't think that suppressing the rest possible.

A: It is now 2016, and I have an ugly solution for those who want to selectively disable a command output. I don't know how recent your gdb should be.
Instead of
(gdb) stepi

try this
(gdb) python gdb.execute("stepi", to_string=True)

It feels like such a basic feature, please share if you have a better way, in particular one which doesn't rely on python. I'd really like to avoid the (likely) performance hit when running the stepi in a loop.


text:
Q: Vector graphics using arbitrary functions (other than bezier, arcs etc) to create shapes Is it possible to create vector graphics with latex or an external program that allows the usage of more or less arbitrary functions (other than beziers and standard shapes like circles etc) to define shapes?
It would, for example, to actually use the function Y=sin(1/x) instead of having to use piecewise linear functions with finite steps. Of course the functions has to be evaluated for presentation on screen/printer, but then the steps could be adjusted to the given resolution.
If its impossible, is there a limitation in the PDF/PostScript specification that prevents it or why isn't it possible?

A: You can transform many functions into piecewise Bezier approximations by using the derivative to calculate the inner control points (which represent tangent vectors for the curve at the end-points).
A very good write-up is Bill Casselmann's Mathematical Illustrations, ch. 6 Curves and ch. 7 Drawing Curves Automatically, which I will be re-reading before saying more. But, effectively, any system which implements Bezier curves can be used to approximate other functions by sampling and interpolation.
Here's a postscript illustration. It's sometimes necessary to invent an interpretation of x/0 to allow the calculation to procede using /div{dup 0 eq{pop pop 100000}{div}ifelse}bind def. Edit: modified to show endpoints of each curve.
N=10:

N=100:

%!

/circ { % draw a circle at current point, radius: 3*linewidth
    gsave
        currentpoint newpath % cx cy
        currentlinewidth 3 mul % cx cy r
        0 360 % cx cy r ang^ ang$
        arc fill %draw and fill the circle
    grestore
} def

% x0 x1 N  sin1x  -
% approximate sin(1/x) in N segments with piecewise Bezier curves
% N: number of segments,
% x0,x1: endpoints (x- ordinates)
%
/sin1x { 16 dict begin
    {N x1 x0}{exch def}forall   %give names to the arguments
    /f { 1 exch div sin } def   %f(x) = sin(1/x)
    /f' { 1 exch div cos } def  %f'(x) = cos(1/x)
    /h x1 x0 sub N div def      %dx
    /x x0 def                   %x = x0
    /y x f def                  %y = f(x)
    /s x f' def                 %s = f'(x)
    x y moveto               %place initial point at x0,f(x0)
    N {                         %repeat N times ...
        circ                    %draw circle to show endpoint
        x h 3 div add
        y h 3 div s mul add  % x+(dx/3) y+(dx/3)*s           ctrl pt 1
        /x x h add def          %x = x + dx
        /y x f def              %y = f(x)
        /s x f' def             %s = f'(x)
        x h 3 div sub
        y h 3 div s mul sub  % x+dx-(dx/3) f(x+dx)-(dx/3)*s  ctrl pt 2
        x y                  % x+dx f(x+dx)                  end pt
        curveto                 %draw curve segment, end pt becomes start of next seg
    } repeat
} def

% translate origin to roughly the center of US letter paper
300 400 translate

% scale by 200, but reduce linewidth by same proportion
% ie. scale the *drawing*, not the *image*
1 200 dup dup scale
div currentlinewidth mul setlinewidth

%x0 x1 N
-1 1 100 sin1x stroke
showpage


text: Q: Получить число 24 используя 4 числа от 1 до 9 и знаки +-*/() На входе 4 числа от 1 до 9 (могут повторяться). Необходимо написать программу, которая определит, можно ли из данных чисел и арифметических знаков: сложение, вычитание, умножение, деление и скобки, составить число равное 24.


text:
Q: Large image on Left Side and two vertically place image in bootrstrap
I'm unable to produce above Need code.. As I have tried several way not able to place images properly find difficult to place images as expected..
here is the code I have tried...

Css here:
 .img-cont {
  width: 100%;
  height: 100%;
  background-size: cover;
  flex: 1;
 }

 .right-cont {
    display: flex;
    flex-direction: column;
    flex: 0 0 50%;
  }

  .gd-cont {
    padding: 0px 0px, 0px 0px;
   }
  .right-img {
     width: 190px;
     height: 190px;
     background-size: cover;
     flex: 50%;
   }

A: You can use Bootstrap's img-fluid class to fit your images, and the configure the containers, rows, and columns to get the layout you need.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>

Sunshine Resort

Relax and unwind yourself

Sold Out!

                    This adventure is currently sold out. But there’s a lot more to explore.

One note — you don't need to repeat the column size (you had col-lg-9 col-md-9 in one place). The col-md-9 is enough.

A: Please see if this works for you.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


text:
Q: Add Multiple Lists  To DataTable I'm struggling to figure out how I can add (in my case 3 lists) to a DataTable so I can output it on my GridView.
I have the following Lists

*

*List Name  (Content number of string)

*List Number   (Content number of integers)

*List Status (Content number of string)

Ideally I would like to have the following result in DataTable
Name (Column 1)  : Content Of List 1
Number(Column 2) : Content of List 2
Status(Column 3) : Content of List 3
I would really appreciate if someone could guide me here, as I haven't found much on the net. Please do ask if it isn't clear what I'm trying to do.

A: That depends on couple of things,

*

*All the list have same number of items

*The order of elements in the lists are same as well, for example, on index 0, you have Name in NameList, on index 0 of NumberList, you have relevant number and so on.

With this you can use a single loop and add rows to your DataTable (dt) like:
for (int i = 0; i < NameList.Count; i++)
{
    dt.Rows.Add(NameList[i], NumberList[i], StatusList[i]);
}

Assuming you have DataTable in place with three columns like:
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof (string));
dt.Columns.Add("Number", typeof (int));
dt.Columns.Add("Status", typeof (string));

A better approach, would be to have list of a custom object, where your object would have properties, Name, Number, Status. Populate that List, instead of maintaining three different lists based on index.


text:
Q: In-practice ideal timeout length for idle HTTP connections In an embedded device, What is a practical amount time to allow idle HTTP connections to stay open?
I know back in the olden days of the net circa 1999 internet chat rooms would sometimes just hold the connection open and send replies as they came in. Idle timeouts and session length of HTTP connections needed to be longer in those days...
How about today with ajax and such?
REASONING: I am writing a transparent proxy for an embedded system with low memory. I am looking for ways to prevent DoS attacks.
My guess would be 3 minutes, or 1 minute. The system has extremely limited RAM and it's okay if it breaks rare and unpopular sites.

A: In the old days (about 2000), an idle timeout was up to 5 minutes standard. These days it tends to be 5 seconds to 50 seconds. Apache's default is 5 seconds. With some special apps defaulting to 120 seconds.
So my assumption is, that with AJAX, long held-open HTTP connections are no longer needed.

A: How about allowing idle HTTP connections to remain open unless another communication request comes in?  If a connection is open and no one else is trying to communicate, the open connection won't hurt anything.  If someone else does try to communicate, send a FIN+ACK to the first connection and open the second.  Many http clients will attempt to receive multiple files using the same connection if possible, but can reconnect between files if necessary.


text:
Q: Leaderboard system for Python game As part of my 20 hour gcse computing project I need to create a leaderboard system. I have got to this so far, and I don't know what to do from here:
elif Player1_Score > Player2_Score:
    print("\nCongratulations", name1, "You have won")
    leaderscore = [name1, Player1_Score]
    else:
        print("\nCongratulations", name2, "You have won")
        leaderscore = [name2,Player2_Score]
leaderboard = open("leaderboard.txt", "w")

leaderboard.write(leaderscore[0] + ',' + str(leaderscore[1]) + '\n')

leaderboard.close()

with open ("leaderboard.txt") as leaderboard:
    for leaderscore[1] in leaderboard:
        leaderboard.append(leaderscore[1].strip())

leaderboard.sort(int(leaderscore[1]))
print(leaderboard)

with open ("sorted_leaderscore.txt", 'w') as u:
    for leaderscore[1] in leaderboard:
        u.write(leaderscore[1] + "\n")

I get this error message:
ing\NEA\NEA code.py", line 162, in <module>
    leaderboard.append(leaderscore[1].strip())
AttributeError: '_io.TextIOWrapper' object has no attribute 'append'

And finally I need help outputting the top 5 scores into my main program.
Thanks in advance!


text:
Q: Windows Store App/Metro on closed/suspend event does not work I have this game I'm making which involves two online players. If one quits the application, the other should be notified. I'm using the onsuspend event but it's not working. Here's my code:
    public MainPage()
    {
        this.InitializeComponent();

        Application.Current.Suspending += Current_Suspending;
        // and a bunch of other stuff
    }

    private async void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
    {
        await game.leaveGame();
    }

Any help would be strongly appreciated. I am 100% sure the game.leaveGame() function works -- I've tested it.

A: As soon as you return from suspending event application is suspended, so in your case async method game.leaveGame() won't finish.
Try to change  your code to (assuming game.leaveGame is sync method):
public MainPage()
{
    this.InitializeComponent();

    Application.Current.Suspending += Current_Suspending;
    // and a bunch of other stuff
}

private void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
    game.leaveGame();
}

For more details about application lifecycle here.


text:
Q: $\log_a(3x-4a)+\log_a(3x)=\frac2{\log_2a}+\log_a(1-2a)$; $0
Given that
  $$\log_a(3x-4a)+\log_a(3x)=\frac2{\log_2a}+\log_a(1-2a)$$
  where $0<a<\frac12$, find $x$.
My question is how do we find the value of $x$ but we don't know the exact value of $a$?

A: Hint. Recall the main properties of the logarithm.
Then we have that $\frac{1}{\log_2a}=\log_a 2$.
Moreover for $x>4a/3>0$ (the argument of the logarithm should be positive),
$$\log_a((3x-4a)\cdot 3x))=\log_a(2^2\cdot(1-2a))$$
which is equivalent (logarithm is an injective function) to
$$(3x-4a)\cdot 3x=2^2\cdot(1-2a)$$
or the quadratic equation
$$9x^2 - 12ax - 4(1-2a)=0.$$
Can you take it from here?
P.S. We expect to find two solutions. At end remember to check the condition $x>4a/3$!

A: $$\log_a(3x-4a)+\log_a(3x)=\frac2{\log_2a}+\log_a(1-2a)$$
$$\log_a(3x(3x-4a))=\frac2{\log_aa/\log_a2}+\log_a(1-2a)$$
$$\log_a(3x(3x-4a))=2\log_a2+\log_a(1-2a)$$
$$\log_a(3x(3x-4a))=\log_a4(1-2a)$$
$$3x(3x-4a)=4(1-2a)$$
$$9x^2-12ax+8a-4=0$$
$$x=\frac{12a\pm\sqrt{144a^2-4\cdot9(8a-4)}}{18}$$
$$=\frac{12a\pm12(a-1)}{18}=\frac{2a\pm2(a-1)}3=\frac{4a-2}3\lor\frac23$$

A: Put $u=3x-2a$ to exploit the symmetry and note that $\frac 1{\log_2}a=\log_a 2$:
$$\begin{align}
\log_a(3x-4a)+\log_a(3x)&=\frac2{\log_2a}+\log_a(1-2a)\\
\log_a (\underbrace{3x-4a}_{u-2a})(\underbrace{3x}_{u+2a})&=\log_a 2^2(1-2a)\\
(u-2a)(u+2a)&=4(1-2a)\\
u^2-4a^2&=4(1-2a)\\
u^2&=4(a-1)^2\\
u=3x-2a&=\pm 2(a-1)\\
x&=\frac {4a-2}3 \text{ or }\frac 23 \\
\end{align}$$
Note that
$$0<a<\frac 12\\
0<4a<2\\
-2<4a-2<0\\
-\frac 23<\frac {4a-2}3<0$$
Hence $$\color{red}{-\frac 23<x<0, \;\; x=\frac 12}$$

A: $x$ might come out as a function of $a$.
$$(3x-4a)(3x) = 4(1-2a) \implies 9x^2 - 12ax - 4(1-2a) = 0$$
Solve this quadratic equation.


text:
Q: YII2 Model for an OrderObject I am trying to create a high-performance model in YII2. I have 2 databases connected (MSSQSL: own and ERP-System) - it works. Now I try to load an order from the ERP system. The system distributes all order information across different tables.
table: order
CREATE TABLE [dbo].[Order](
    [ID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [orderid] [int] NULL,
    [name] [varchar](10) NULL,
    [type] [tinyint] NOT NULL,
    [lastupdate] [smalldatetime] NOT NULL,
....

table: order information1
CREATE TABLE [dbo].[Order_Information1](
    [ID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [Parameter] [int] NULL,
    [Value] [varchar](255) NULL,
....

table: order information2
CREATE TABLE [dbo].[Order_Information2](
    [ID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [Parameter] [int] NULL,
    [Value] [varchar](255) NULL,
....

I have created for all models and can also individually access the tables. In the order model, I have built a class GetInformationData:
public function getInformationData ()
{

    $description = Order_Information2::find()->select('Value')->where(['ID' => $this->id, 'Parameter' => 'txt_ description'])->one();
    //...
    $this->description =  !empty($description) ? $description->Value : '';
    //...
}
    //...

It works, but it is very slow. Each order has about 500 parameters
and it takes half an eternity until everything is loaded ;-(
I tried to connect the model, but unfortunately without success.
class Order extends ActiveRecord
{
    // ...

    public function getOrder_Information1()
    {
        return $this->hasMany(Order_Information1::className(), ['id' => 'id']);
    }
}

class Order_Information1 extends ActiveRecord
{
    // ...

    public function getOrder()
    {
        return $this->hasOne(Order::className(), ['id' => 'id']);
    }
}

A: You didn't share much details, but you can query all parameters in one query and avoid creating model (which seems to be unused, since you need only Value):
public function getInformationData () {
    $data = Order_Information2::find()
        ->select(['Parameter', 'Value'])
        ->where(['ID' => $this->id])
        ->asArray()
        ->all();
    foreach ($data as ['Parameter' => $parameter, 'Value' => $value]) {
        $this->$parameter = $value;
    }
    //...
}


text:
Q: Replace empty dicts in nested dicts I have a nested dictionary whose structure looks like this
{"a":{},"b":{"c":{}}}

Every key is a string and every value is a dict.
I need to replace every empty dict with "". How would I go about this?

A: Use recursion:
def foo(the_dict):
    if the_dict == {}:
        return ""
    return {k : foo(v) for k,v in the_dict.items()}

Here you have a live example

A: Checking values for an empty dict recursively, and replacing with empty string if so.
>>> d = {"a":{},"b":{"c":{}}}
>>> def replace_empty(d):
...     for k, v in d.items():
...         if not bool(v):
...             d[k] = ""
...         else:
...             d[k] = replace_empty(v)
...     return d
>>> replace_empty(d)
{'a': '', 'b': {'c': ''}}

A: Let the dictionary be cd then:-
>>> def foo(cd):
...     for x in cd:
...             if cd[x] == {}:
...                     cd[x] = ""
...             else: foo(cd[x])
...     return cd

>>> cd = {"a":{},"b":{"c":{}}}
>>> foo(cd)
{'a': '', 'b': {'c': ''}}

The thinking process goes like this:-
Firstly make a processor which will process your dictionary and replace all empty dictionaries with empty strings. Then just give all the dictionaries the opportunity to meet that processor.


text:
Q: Unhandled Exception: type '_InternalLinkedHashMap' is not a subtype of type 'Map>' in type cast I am trying to convert data decoded from json to Map<DateTime,List
Here is the Code:
var encodingaccounts = json.decode(gettingAccounts!);
var encodedAccounts = encodingTasks.map((dateTime, Accounts) {
    List<Account> convertedAccountsType = [];
    for (var Account in Accounts) {
      String _summary = Account['summary'];
      String _description = Account['description'];
      String _category = Account['category'];
      bool _isDone = Account['isDone'];
      convertedaccountsType.add(Account(_summary,
          category: _category, description: _description, isDone: _isDone));
    }
    return MapEntry(DateTime.parse(dateTime), convertedaccountsype);
  });
 _accounts = encodedAccounts as Map<DateTime, List<Account>>;

But following error occurs:
 [ERROR:flutter/shell/common/shell.cc(93)] Dart Unhandled Exception: type
 '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<DateTime,
 List<Account>>' in type cast

I have checked encoding.map() returns correct datatype(Map,List) but still this error appears.

A: You can use Dart special Method of Map.from()
Just Like:
_accounts = Map<DateTime,List<Account>>.from(encodedAccounts);

Here is the complete code:
var encodingaccounts = json.decode(gettingAccounts!);
var encodedAccounts = encodingTasks.map((dateTime, Accounts) {
List<Account> convertedAccountsType = [];
for (var Account in Accounts) {
  String _summary = Account['summary'];
  String _description = Account['description'];
  String _category = Account['category'];
  bool _isDone = Account['isDone'];
  convertedaccountsType.add(Account(_summary,
      category: _category, description: _description, isDone: _isDone));
}
return MapEntry(DateTime.parse(dateTime), convertedaccountsype);
});
w_accounts = Map<DateTime,List<Account>>.from(encodedAccount);

A: It sometimes helps to add types to map as here:
  final _accounts =
      et.map<DateTime, List<Account>>((dateTime, accounts) => MapEntry(
          DateTime.parse(dateTime),
          accounts
              .map<Account>((e) => Account(
                    e['summary'],
                    e['category'],
                    e['description'],
                    e['isDone'],
                  ))
              .toList()));

  print(_accounts.runtimeType);

Prints _InternalLinkedHashMap<DateTime, List<Account>> as expected. (Note that I changed the constructor of Account for simplicity in this example.)


text:
Q: Pods-Framework with multisite I have a wordpress multisite. But I tried to find a recipe or tutorial on how to create a multisite-pod. There is none! Not a single example.
Could someone post an example please? How to use a pod within a template.php?
The structure of my domains/mapping:
example.org

*

*network.example.org // define('DOMAIN_CURRENT_SITE', 'network.example.org');

*example.org

*example.de

The necessary fields are: name, content, link(german), link(english)


text:
Q: Excel - select next item off list that is not already in array (no VBA) I have a list of items, say 1 - 10 ordered smallest to biggest in cells c1-c10.  I currently have a formula in a2 which will lookup the value a1 on that list, and then return the next item.
So if a1=2, then my formula will return 3.  However, I would like it to also look at another list, and not answer if that number is already on that list.  Ie, if the second list contained 3,4,7, and a1=2, then my formula should return 5.
Both the first lookup list and the second list can be any length.  I can't use VBA.  I'm somewhat stumped.  Any ideas?

A: Let's say that the second range is in D2:D4 then try this "array formula"
=SMALL(IF(C1:C10>A1,IF(COUNTIF(D2:D4,C1:C10)=0,C1:C10)),1)
confirmed with CTRL+SHIFT+ENTER
That will return the smallest value in C1:C10 which is bigger than A1 but not in the D2:D4 list ( COUNTIF does that second check)
If there is no value that qualifies you get #NUM! error


text:
Q: Why isn't this.key working properly in JavaScript?

let student = {

fname: "Carlos",
    lname: 'Dubón',
    sayHi(){
        alert(`Hi my name is ${this.fname}`);
    },
    sayBye: function() {
        alert(`Bye ${this.fname}`);
    },
    sayHiAgain: ()=> {
        alert(`Hi my name is ${this.fname}`);
    }
}

student.sayHiAgain();

I'm new to OOP in Javascript, I understand that the 3 ways in which I wrote a method work exactly the same.
student.sayHi(); works and shows up the alert => "Hi my name is Carlos"
but student.sayHiAgain(); shows up the alert => "Hi my name is undefined"
What am I missing?

A: When using arrow functions, it uses lexical scoping meaning that it refers to it's current scope and no further past that, i.e., binds to the inner-function and not to the object itself.

An arrow function expression is a syntactically compact alternative to
a regular function expression, although without its own bindings to
the this, arguments, super, or new.target keywords. Arrow function
expressions are ill suited as methods, and they cannot be used as
constructors.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

A: Arrow functions have no "this"

Arrow functions are special: they don't have their "own" this. If we
reference this from such a function, it's taken from the outer
"normal" function.

let student = {
  fname: "Carlos",
  lname: "Dubón",
  sayHi: function () {
    console.log(`Hi my name is ${this.fname}`);
  },
  sayBye: function () {
    console.log(`Bye ${this.fname}`);
  },
  sayHiAgain: function () {
    console.log(`Hi my name is ${this.fname}`);
  },
};

student.sayHiAgain();

Arrow function expressions


text:
Q: Set $_SESSION to expire in 1 month PHP I am trying to get my $_SESSIONS to expire in 30 days. I do not deal with any sensitive data on my server, so I am not worried about cookie hi-jacking. Would this work?
ini_set('session.cookie_lifetime', 2592000);
ini_set('session.gc_maxlifetime', 2592000);
session_start();

Thanks in advance.

A: In addition to your cookie, there are some other settings you need to look at in your php.ini.
You can manipulate them in code as follows:
// Current Session Timeout Value
$currentTimeout= ini_get('session.gc_maxlifetime');

// Change session timeout value for a particular page load  - 1 month = ~2678400 seconds
ini_set('session.gc_maxlifetime', 2678400);

More here and here


text:
Q: How to add a Rating Bar programmatically How to add a Rating Bar programmatically android?
and how to set the count of stars. sometimes even if i set the number of stars it wont appear in the ui.

A: The key is wrap content over
// first create a layout
LinearLayout ll = new LinearLayout(getApplicationContext());
// now you will have to set width and height
ll.setMinimumWidth(300);
ll.setMinimumHeight(100);
// now init Rating bar
RatingBar rb = new RatingBar(getApplicationContext());
// now set num of stars
rb.setNumStars(5);
// adding ratingBar into the created layout
ll.addView(rb);
// get the current layout
LinearLayout l = findViewById(R.id.linearLayout);
// now add the layout
l.addView(ll);

Here is the layout resouce
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="horizontal"
    android:id="@+id/mainLayout">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    </LinearLayout>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>

A: you can try some liblary to make ratingbar.. like https://github.com/DreaminginCodeZH/MaterialRatingBar

A: For adding rating bar programmatically you need to add this code
//parent layout in which you want to add rating bar
LinearLayout linearLayout = findViewById(R.id.d_layout);
RatingBar r = new RatingBar(MainActivity.this);
linearLayout.addView(r);
//how many starts you want to show,parent layout width must be wrap_content
r.setNumStars(6);
r.setRating(Float.parseFloat("1.5"));


text:
Q: Route by using existing cookie How can I route requests in haproxy using a cookie that was set on the app servers?
Example: SESS=<hash-of-username>
haproxy should not insert cookies by itself in any case.

A: You can't use your existing cookie for balancing, the way you could use the URI parameter. You can't just take the md5() or build the hash table of the cookie, at least that is not documented. You could use prefix parameter for the cookie to achieve a different result. It might be what you are looking for (if you want to avoid creation of yet another cookie).
So in your case the config would look like this:
backend bk_web
    balance roundrobin
    cookie SESS prefix indirect nocache
    server s1 192.168.10.11:80 check cookie s1
    server s2 192.168.10.21:80 check cookie s2

When the request arrives without a cookie, any server is chosen by round-robin and request is redirected to it. When response arrives from the backend, HAProxy checks for the SESS cookie and if it's set, it prepends the server name (sX) to the cookie and sends it to the client. In the browser, the cookie looks like sX~, but when the next request is sent with that cookie, the backend server only sees  in the cookie, as HAProxy strips the sX~ part
Source: load balancing, affinity, persistence, sticky sessions: what you need to know

A: If you just want to read cookies in the request and route accordingly, you can do something like this in your configuration:
frontend http
   acl cookie_found hdr_sub(cookie) COOKIENAME
   use_backend app_server if cookie_found

backend app_server
   balance roundrobin
   server channel1 X.X.X.X:PORT #Host1
   server channel2 Y.Y.Y.Y:PORT #Host2

A: For testing a specific server behind haproxy I can recommend this approach:
frontend http
   acl is_cookie_hack_1 hdr_sub(cookie) server_test_hack=server1
   acl is_cookie_hack_2 hdr_sub(cookie) server_test_hack=server2
   ... insert your normal acl rules here

   use_backend bk_server_1 if is_cookie_hack_1
   use_backend bk_server_2 if is_cookie_hack_2
   ... insert your normal use_backend expressions here

backend bk_server_1
   ...

backend bk_server_2
   ...

I insert the server_test_hack cookie by javascript in my browser's js console by this script:
document.cookie="server_test_hack=server1";


text:
Q: jordan canonical form of the D, the matrix of the map of first derivative of the polynomials $D=\begin{bmatrix}0 & 0 & 0 & ... & 0& 0\\n & 0 & 0 & ... & 0 & 0\\0 &n-1 & 0 & ...& 0& 0\\...\\0& 0 & 0 & ... &1&0\end{bmatrix}$
D is the matrix representation of the linear transformation $D : p →
\frac{dp}{dx} $
where p is the polynomial of degree n. How can I find the Jordan Canonical Form of D? I now that $|\lambda I - A| = \lambda ^n $, will this help?

A: I am going to restate the problem before explaining. Let $V$ be the vector space of polynomials of degree less than or equal to $n-1$. I'll assume that the field your were working over is either $\mathbb{R}$ or $\mathbb{C}$, but any field of characteristic zero is fine.
Define $D: V \to V$ by $D(p(x)) = p'(x)$. Note that the $n^{th}$ derivative of any polynomial of degree $(n-1)$ or less is $0$. That is, $D^n = 0$. Note also that $D^{n-1}(x^{n-1}) = (n-1)! \neq 0$. Therefore $D^{n-1} \neq 0$. This tells us that the minimal polynomial of $D$ is $m(\lambda) = \lambda^n$.
Thus the Jordan form of $D$ consists of a single Jordan block of size $n$ corresponding to the eigenvalue $0$.


text:
Q: The integral of ${x^2 - 1 \over x^3 \sqrt{2x^4 - 2x^2 + 1}}$
$$\int {x^2 - 1 \over x^3 \sqrt{2x^4 - 2x^2 + 1}}dx$$

Substituting $u = x^2$, I get $${1\over 4}\int {u - 1 \over u^2 \sqrt{2u^2 - 2u + 1}}du$$
Then completing the square under the square root.
$${1\over 4}\int {u - 1 \over u^2 \sqrt{\left(\sqrt{2} u - \frac1{\sqrt{2}} \right)+ 1/2} }du$$
Substituting $\tan z = \sqrt{2}\left(\sqrt{2} u - \frac1{\sqrt{2}} \right)$
$${ \sqrt{2} \over 4}\int {\tan z -3 \over (\tan z- 1)^2 } \times \sec z \  dz$$
I think I can solve the last integral if I think a bit more but I need a better way to solve this question, this was seems very tedious.

A: Hint pull out $x^2$ common from numerator and $x^4$ in the root from denominator ie $x^2$ from numerator. Then put $1-\frac {1}{x^2}=u $ thus $\frac {2}{x^3}dx=du $ also write the new denominator as $1+(1-\frac {1}{x^2})^2$ hope you can handle  from  here.


text:
Q: ¿Cómo pasar todos los parámetros de un script bash a otro script/programa? Quiero pasar todos los parámetros que recibe un script bash a otro script o programa. Pero no quiero pasarle el parámetro 0, que contiene el nombre con que ha sido invocado el script bash.
Si supiese que lo invocan con 3 parámetros tal que así:
mi_script a b c

podría usar el siguiente script:
#!/usr/bin/env bash
otro_script_o_programa "$1" "$2" "$3"

Pero eso no me sirve si el script va a recibir un número arbitrario de parámetros, que puede incluso ser ninguno.
Es importante que se trate correctamente los parámetros que contienen espacios, tabuladores, etc.

A: Tal y como dicen en esta pregunta de SO en inglés:
Has de pasar "$@"
otro_script_o_programa "$@"

A: Para eso se usa "$@" que significa "todos los parámetros que recibí".
En tu caso, el contenido de mi_script sería
#!/usr/bin/env bash
otro_script_o_programa "$@"

Edit: originalmente había propuesto utilizar $@ de manera no entrecomillada, lo cual lleva a que, dado un parámetro con la forma de un string entrecomillado, los espacios dentro de éste harán que cada palabra se considere un nuevo parámetro. Con la opción "$@" esto no sucede y se pasa literalmente cada parámetro entrecomillado a la siguiente función.


text:
Q: Psycopg2 fails to install on python 3 with pip issuing a fatal error $ yum install python3 postgresql python-devel libpqxx-devel
Loaded plugins: langpacks, refresh-packagekit
Package python3-3.3.2-8.fc20.x86_64 already installed and latest version
Package postgresql-9.3.2-2.fc20.x86_64 already installed and latest version
Package python-devel-2.7.5-9.fc20.x86_64 already installed and latest version
Package 1:libpqxx-devel-3.2-0.5.fc20.x86_64 already installed and latest version
Nothing to do

I am trying to install psycopg2 in my virtualenv to connect django with the postgresql database.
In Fedora 19 and postgresql-9.2 the path to pg_config was:
/usr/pgsql-9.2/bin
In Fedora 20, this directory does not exist.
However pg_config can be found in /usr/bin/pg_config.
Trying to install psycopg2:
 $ export PATH=$PATH:/usr/bin; pip install psycopg2
Downloading/unpacking psycopg2
  Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
  Running setup.py egg_info for package psycopg2

... -compiling output here- ...

gcc -pthread -Wno-unused-result -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.5.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090302 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/usr/include/python3.3m -I. -I/usr/include -I/usr/include/pgsql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.3/psycopg/psycopgmodule.o -Wdeclaration-after-statement

In file included from psycopg/psycopgmodule.c:27:0:

./psycopg/psycopg.h:30:20: fatal error: Python.h: No such file or directory

 #include <Python.h>

                    ^

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /home/flyer/.virtualenvs/p3test/bin/python3 -c "import setuptools;__file__='/home/flyer/.virtualenvs/p3test/build/psycopg2/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-mrsky4-record/install-record.txt --single-version-externally-managed --install-headers /home/flyer/.virtualenvs/p3test/include/site/python3.3 failed with error code 1 in /home/flyer/.virtualenvs/p3test/build/psycopg2
Storing complete log in /home/flyer/.pip/pip.log

I would appreciate your help.

A: You are missing python3 include files
./psycopg/psycopg.h:30:20: fatal error: Python.h: No such file or directory

you can probably find them in the python3-devel package.

A: Install the python3-devel package to get it work
sudo dnf install python3-devel

If it works then alright or if it requires libpq-fe.h file then install it using the command:
sudo dnf install postgresql-devel

A: On Ubuntu. I solved this with:
sudo apt-get install libpq-dev

A: As indicated in the other answers this is caused by not having the right Python "devel" package installed. On CentOS, the Python "devel" rpm package is numbered with the with the qualified version. For example as of this writing the current versions are:
python34-devel for epel repository
python36u-devel for ius repository
Example Yum command (assumes EPEL repository is configured):
sudo yum install python34-devel
Related answer from server fault: https://serverfault.com/questions/710354/repository-for-python3-devel-on-centos-7