text:
Q: chrome extension: how to insert sidebar via iframe in content? I want to add a vertical side bar on the left side of the current page by injecting an iframe via chrome extension I'm building.
How can I achieve this in a way that it is consistent on any web page, like the sidebar won't end up overlapping the current page and etc. I want to make sure that the page gets pushed to the side to make room for the side bar.
I also don't want the content of the sidebar to be affected by the css styling on the current page, so I'm thinking of putting it inside an iframe.


text:
Q: What does the following Oracle error mean: invalid column index I got the following error while testing some code:

SQLException: Invalid column index

What exactly does that mean?
Is there an online document explaining what all the Oracle error codes and statements?

A: Using Spring's SimpleJdbcTemplate, I got it when I tried to do this:
String sqlString = "select pwy_code from approver where university_id = '123'";
List<Map<String, Object>> rows = getSimpleJdbcTemplate().queryForList(sqlString, uniId);

*

*I had an argument to queryForList that didn't correspond to a question mark in the SQL.  The first line should have been:
String sqlString = "select pwy_code from approver where university_id = ?";

A: I also got this type error, problem is wrong usage of parameters to statement like, Let's say  you have a query like this
SELECT * FROM EMPLOYE E WHERE E.ID = ?

and for the preparedStatement object (JDBC) if you set the parameters like
preparedStatement.setXXX(1,value);
preparedStatement.setXXX(2,value)

then it  results  in       SQLException: Invalid column index
So, I removed that second parameter setting to prepared statement then problem solved

A: Just try this fix, as I faced your error:
Remove the single quotation marks around your question mark, which means, if you used your reserved parameters like ('?','?','?')  you should make it look like this:
(?,?,?)

A: If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.
For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.

A: I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES"   My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.

A: I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G.  I was using the following query and getting the invalid column index error:
<security:jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"

It turns out that I needed to add: "1 as enabled" to the query:
<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"

Everything worked after that.  I believe this could be a bug in the Spring JDBC core package...

A: It sounds like you're trying to SELECT a column that doesn't exist.
Perhaps you're trying to ORDER BY a column that doesn't exist?
Any typos in your SQL statement?

A: the final sql statement is something like:
select col_1 from table_X where col_2 = 'abcd';

i run this inside my SQL IDE and everything is ok.
Next, i try to build this statement with java:
String queryString= "select col_1 from table_X where col_2 = '?';";
PreparedStatement stmt = con.prepareStatement(queryString);
stmt.setString(1, "abcd"); //raises java.sql.SQLException: Invalid column index

Although the sql statement (the first one, ran against the database) contains quotes around string values, and also finishes with a semicolumn, the string that i pass to the PreparedStatement should not contain quotes around the wildcard character ?, nor should it finish with semicolumn.
i just removed the characters that appear on white background
"select col_1 from table_X where col_2 = ' ? ' ; ";
to obtain
"select col_1 from table_X where col_2 = ?";

(i found the solution here: https://coderanch.com/t/424689/databases/java-sql-SQLException-Invalid-column)

A: I had this problem in one legacy application that create prepared statement dynamically.
String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and  name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());

when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Expose type of local TypeScript class outside factory function I want to use a factory to manage some of my dependency injection and so I am creating a local class inside of a function. The JavaScript framework I am using (AngularJS) will inject the return value of the function into the constructor.
How can I reference the type of the returned class Record from outside the factory function?
/** Define factory to create Record classes */
export default function RecordFactory($window) {
  return class Record { // I want to reference this class as a type
    doSomething() {
      // use $window service
    }
  }

}

/**
 * Controller for page with returned class of RecordFactory injected
 * into the constructor
 */
class RecordPageCtrl {
  record
  constructor(Record) { // How do I specify the type of Record here?
    this.record = new Record();
  }
}

// Dependency Injection is handled by AngularJS
angular.module('myApp', [])
  .factory('Record', RecordFactory)
  .controller('RecordPageCtrl', RecordPageCtrl)

Note: I'm trying to avoid maintaining a interface with all of the methods on the Record class.

A: This works for me.
namespace Factored {
  // Class Record wrapped in namespace only to distinguish from other Record usages
  export class Record { // I want to reference this class as a type
    doSomething() {
      // use $window service
    }
  };
}

/** Define factory to create Record classes */
export default function RecordFactory($window) {
  return Factored.Record; // return class reference
}

/**
 * Controller for page with returned class of RecordFactory injected
 * into the constructor
 */
class RecordPageCtrl {
  record: Factored.Record;
  constructor(Record: typeof Factored.Record) { // Referencing namespaced class
    this.record = new Record();
    this.record.doSomething();
  }
}

// Dependency Injection is handled by AngularJS
angular.module('myApp', [])
  .factory('Record', RecordFactory)
  .controller('RecordPageCtrl', RecordPageCtrl)

A: I've reconsidered how the factory is created and the services are injected into classes like Record. By passing the service in through the constructor, a factory can easily pass in the service and allow AngularJS to handle dependency injection.
/** Class where service needs to be injected */
class Record {
  constructor(private myInjectedService) {}
    doSomething() {
      // use myService
      this.myInjectedService.log('Hello World');
    }
}

/** Define factory to create Record class instances */
function RecordFactory(MyService) {
  return new Record(MyService); // return a new class
}

/**
 * Controller for page
 * RecordFactory return variable is injected into the constructor
 */
class RecordPageCtrl {
  constructor(public Record: Record) {
    this.Record.doSomething();
  }
}

/** Service to inject into Record class */
class MyService {
    log(message: string) {
        console.log(message);
    }
}

let myServiceInst = new MyService();

// directly instantiated
let factoryInstance = RecordFactory(myServiceInst);
new RecordPageCtrl(factoryInstance);

// Dependency Injection handled by AngularJS
angular.module('myApp', [])
  .factory('Record', RecordFactory)
  .service('MyService', MyService)
  .controller('RecordPageCtrl', RecordPageCtrl)

Note, if you want to be able to create multiple instances of the Record class where the factory is being injected, you will need to have the factory return another factory which instantiates the function when called.


text:
Q: Add Label to Variant Selector (Shopify) I have a dropdown with my product variants (title Color). I would like to add a label to that dropdown ("Select Color"). I see that Shopify adds a label when theres more than one Variant, but I cant find the code that allows me to update that.
Im using the theme Simple.
Any help? Thanks.

A: In your case you'll find this code snippets in assets > theme.js.liquid in simple theme.
/**
 *
 *  Adjust option_selection.js labels based on variant default values
 *
 */
Slate.simplifyVariantLabels = function (product) {
  // option_selection.js does not add a label if there is only one variant option.
  // Add one as long as it is not 'Title' (Shopify's default), add one.
  if (product.options.length === 1 && product.options[0] !== 'Title') {
    $('.selector-wrapper:eq(0)').prepend('<label for="ProductSelect-option-0">'+ product.options[0] +'</label>');
  }

  // Hide variant dropdown if only one exists and title contains 'Default'
  if (product.variants.length && product.variants[0].title.indexOf('Default') >= 0) {
    $('.selector-wrapper').hide();
  }
};


text:
Q: MongoDB and Pymongo, query FULLTEXT in all collections I have a local MongoDB database with multiple collections.
I use pymongo in jupyter notebook, what I would like to do is run a query FULLTEXT looking for the data on all the collections present.
is it possible to do this? if so how could i proceed?
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
client.list_database_names()
out: ['admin', 'config', 'local']

In local I have a more collection:
this is what I do with just one collection
db = client["local"]
firstdb = db["firstdb"]

result = db.firstdb.find({"email": {"$regex":"test","$options": 'i'}})
for item in result:
    print(item['email'],item['log'])

in essence I would like to perform an email query also on secondb, thirdb, fourthdb, etc. etc.

A: no one can help me? basically I have to do a FULLTEXT query on all collections.
the only solution I found is this:
result = db.firstdb.find({"email": {"$regex":"test","$options": 'i'}})
result1 = db.secondb.find({"email": {"$regex":"test","$options": 'i'}})
result2 = db.thirdb.find({"email": {"$regex":"test","$options": 'i'}})

for item in result:
    print(item['email'],item['log'])
for item in result1:
    print(item['email'],item['date'])
for item in result2:
    print(item['email'],item['account'])

but I'm not sure I'm going on the right track!
I thank anyone who can help me!
PS: I would not like to change the structure of the collections, the problem could occur in other Database


text:
Q: Locating divs with changing class names (selenium) I am taking a selenium course online and we are automating log ins. The lecture is outdated and the website we are using is updated (Quora).
The problem is, the input fields have randomly generated class names which makes the "find_element_by_id method useless.
I can not figure out how to log in for different sessions. How would I select these fields during different sessions ( that have different class names ). This is what my code looks like. Thank you in advance. I tried asking the course instructor but he hasnt responded all week.
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path = r'/Users/mpbro17/Desktop/chromedriver')

driver.get('https://www.quora.com')

driver.find_element_by_id("__w2_fy0VXDC_email").clear()
driver.find_element_by_id("__w2_fy0VXDC_email").send_keys("programmingdude183@gmail.com")
driver.find_element_by_id("__w2_fy0VXDC_password").clear()
driver.find_element_by_id("__w2_fy0VXDC_password").send_keys("testpassword1")
driver.find_element_by_id("__w2_fy0VXDC_submit_button").click()

ERROR
Traceback (most recent call last):
  File "/Users/mbpro/Desktop/projects/scraping_course/test_quora_login.py", line 13, in <module>
    driver.find_element_by_name("email").clear()
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 92, in clear
    self._execute(Command.CLEAR_ELEMENT)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 494, in _execute
    return self._parent.execute(command, params)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidElementStateException: Message: invalid element state: Element is not currently interactable and may not be manipulated
  (Session info: chrome=53.0.2785.143)
  (Driver info: chromedriver=2.24.417412 (ac882d3ce7c0d99292439bf3405780058fcca0a6),platform=Mac OS X 10.11.5 x86_64)

A: Try css selectors instead:
driver.find_element_by_css_selector('[id$="email"]')
driver.find_element_by_css_selector('[id$="password"]')
driver.find_element_by_css_selector('[id$="submit_button"]')

A: You could have used find_element_by_name method to find your elements (email and password) and cssSelector for Login button. I think, this won't make you disheartened.
driver.find_element_by_name("email").clear()
driver.find_element_by_name("email").send_keys("programmingdude183@gmail.com")
driver.find_element_by_name("password").clear()
driver.find_element_by_name("password").send_keys("testpassword1")
driver.find_element_by_css_selector("input[value='Login']").click()

A: You have to go with name as it standard.However there are two elements present if you go by name property.

So go by the below xpath
//div[@class='regular_login']//input[@name='email']
//div[@class='regular_login']//input[@name='password']
//div[@class='regular_login']//input[contains(@class,'submit')]


text:
Q: If power lines are properly insulated, why do we see sparks/arcs in videos these days? I saw a video where power lines touched due to high speed air and created huge arcs. In another video, a person throws a wire in air, it touches a wire and he gets shocked. Also it is said that birds are not electrocuted because they do not short +ve and -ve wires. Why shouldn't the answer be power lines are insulated by rubber?

A: Powerlines in the air are not insulated.
If hung properly they shouldn't be able to touch.
In really heavy rain and wind you might be able to see some arcs and sparks between the wires, but that is not supposed to happen.

A: High voltage (>1KV) overhead lines are nearly always bare wire. Instead insulation is achieved through spacing of the wires and mounting them on insulated supports. This works fine most of the time, but sometimes either support structures break or high winds cause problems by either blowing wires into each other or blowing other stuff onto the wires.
Insulating a HV line is more complicated than just slapping a bit of plastic or rubber on, at high voltages controlling field strengths becomes very important. Insulated HV wires used underground often have multiple layers including a layer of earthed metal and then inside that a "semi-conductive layer" to control field strength. However having earthed metal close to a HV conductor means more capacitive losses.
Low voltage (<1KV) overhead lines were also historically often bare wire. At least in the UK this has fallen out of favor in recent years with new installations tending to use insulated conductors. There is still a lot of legacy bare wire LV overhead around though (and yes this does include service drops to peoples houses).


text:
Q: How to shift suptitle in Seaborn displot For a plot as below.

There is an issue whereby the Main title is on the same line with the other sub-title.
May I know how shift the suptitle further up?
The code to reproduce the above figure is as below
import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
fig=plt.figure()
g = sns.displot ( data=iris, x='petal_width', col='species', col_wrap=2, bw_adjust=0.5,
                      kind="kde", rug=True)

header_name =['1a','1b','1c','1d']
value_tick = [0.5,1,1.5,3]
g.set_xticklabels (rotation=45 )
plt.suptitle('Main title')
plt.xticks ( ticks=value_tick, labels=header_name, ha="right" )
plt.show()

A: .suptitle(...) is a matplotlib figure function. It has x and y arguments, with y=0.98 as the default. You can adjust it to be a bit higher, instead of moving the subplots (in some cases you may not have enough freedom there).

import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
fig=plt.figure()
#plt.suptitle("Main Title")
g = sns.displot ( data=iris, x='petal_width', col='species', col_wrap=2, bw_adjust=0.5,                      kind="kde", rug=True)
header_name =['1a','1b','1c','1d']
value_tick = [0.5,1,1.5,3]
g.set_xticklabels (rotation=45 )
g.fig.suptitle("My super title", y=1.05)
#plt.suptitle('Main title')
plt.xticks ( ticks=value_tick, labels=header_name, ha="right" )


text:
Q: get fixed value for android real time graph using GraphView library I am trying to create a Real time graph view in android using GraphView library from jjoe64GraphView. Now getting a real time graph with continuously changing Y axis values. Anyone can help me for change this real time graph with fixed value Y axis?
Thanks....


text:
Q: Error while posting a message on wall I am trying to post a sample message on user's wall. But the FB.ui method does not execute and I get a message saying "An error occurred. Please try again later". This is the code inside the body:

}
Publish to your wall

A: You cannot publish to a user's wall until that user authenticates your app.


text:
Q: Why is (sizeof(int) > -1) false? Can You justify the below code:
#include<stdio.h>
int main()
{
    if(sizeof(int) > -1)
    {
            printf("\nTrue\n");
    }
    else
    {
            printf("\nFALSE\n");
    }
}

The output is FALSE .....suggest me the reason

A: sizeof(int) has type size_t, which is an unsigned integer type.
-1 has type int, which is a signed integer type.
When comparing a signed integer with an unsigned integer, first the signed integer is converted to unsigned, then the comparison is performed with two unsigned integers.
sizeof(int) > (unsigned int)-1 is false, because (unsigned int)-1 is a very large number on most implementations (equal to UINT_MAX, or the largest number which fits in an unsigned int).

A: sizeof

yields a value of an unsigned type (namely size_t).
In sizeof(int) > -1 expression, the usual arithmetic conversion applies and -1 is converted to the unsigned type of sizeof which results in a huge unsigned value greater than -1.

A: It's because the sizeof operator returns an unsigned integer type.  When compared with a signed integer type, the signed integer is converted to unsigned.  So in effect, you were comparing sizeof(int) against the largest possible unsigned integer.
You can force the size to signed by casting:
#include <stdio.h>

int main()
{
    if((int)sizeof(int) > -1)
    {
            printf("\nTrue\n");
    }
    else
    {
            printf("\nFALSE\n");
    }
}


text:
Q: MS SQL Server Instances - How many instances do I really have? I have installed SQL Server 2016 Express and SQL Server Management Studio on my home computer. During installation I used option to create a named instance and nothing else. After that I have this:

Second line describes the named instance SPOKANE that I created, but what is the purpose of the first line? Which line should I use in which case?

A: The easiest method I know for checking what SQL Server instances are installed is to use the SQL Server Configuration Manager - it displays all the services including the DBMS, Agent, SSAS servers etc.
I, for instance, have SQL Server Express, a full SQL Server, and SSAS:

SQL Server Express often gets installed as part of other software, or sometimes as part of a developer image provided by ITS when they first set up your computer - if you have an extra instance, it could have come about through any number of reasons. In your case the version you installed will be what you want to use - the other may be a different version from what you're expecting (e.g. SQL Server 2014 rather than 2016)

A: Most likely other line(s) in the drop down list are result of a separate unrelated installation(s). To verify this, open SQL Server Management Studio and connect to both servers (you need to ensure that they are both running first), you will see something like this:

Note the versions of the servers: 9.0 and 13.0. This clearly indicates that they are from different installations.


text:
Q: spark streaming: job hangs at submitting ReceiverTracker Some jobs in my spark (1.5.0) streaming application are hang at: submitJob at ReceiverTracker.scala:557. The line 557 is quoted below:
val future = ssc.sparkContext.submitJob[Receiver[_], Unit, Unit](
    receiverRDD, startReceiverFunc, Seq(0), (_, _) => Unit, ())

I find the SPARK-1975, and it's suggested that number of cores should be greater than the number of DStream. It is true in my case: 2 receivers, 4 executors with 3 cores each.
Spark executors:

Spark jobs:

kafka topic

What would be the reason that hang the jobs? Any suggestion is appreciated. Thank you.


text:
Q: How do I transform a child element o uppercase if a child element with the same name exists? I have an XML file that looks like this:
..
<PersonalInfo>
    <LastName>Smith</LastName>
  ...
</PersonalInfo>
<DependentInfo>
    <LastName>Johnson</LastName>
  ...
</DependentInfo>
...

and I need to convert the last name of the dependent to upper case.
I wrote this XSLT
<xsl:value-of select="translate(//LastName, $smallcase, $uppercase)" />

It converts  last name of the dependent to the last name of the personal info in upper case. So it converts it to SMITH and I want it to be converted to JOHNSON.
Could someone tell me how I can do this?
Thanks you very much.

A: It's hard to tell for certain based on the XML example and the small XSL snippet, but it sounds like the context where you use the xsl:value-of is DependentInfo. By using //LastName in the translate() function, you're telling the processor to select any LastName in the XML. (In this case it appears to be selecting the first occurrence of LastName in PersonalInfo.)
Try removing the // from your xsl:value-of:
<xsl:value-of select="translate(LastName, $smallcase, $uppercase)" />

If this doesn't work, try posting more of your XSL for us to look at.

A: <xsl:value-of select="translate(DependentInfo/LastName, $smallcase, $uppercase)" />

A: Use:
translate(/*/DependentInfo/LastName, $smallcase, $uppercase)


text:
Q: Does Next.js not need browser history when using Redux? I'm trying to migrate my React app to Next.js. I keep having below error from export const history = createBrowserHistory(); in my configureStore.js.

Invariant Violation: Browser history needs a DOM

configureStore.js
import { createStore, combineReducers, compose, applyMiddleware } from "redux";
import { connectRouter, routerMiddleware } from "connected-react-router";
import { createBrowserHistory } from "history";
import thunk from "redux-thunk";
import user from "./modules/user";
import stores from "./modules/stores";
import info from "./modules/info";

export const history = createBrowserHistory();

const middlewares = [thunk, routerMiddleware(history)];

const reducer = combineReducers({
  user,
  stores,
  info,
  router: connectRouter(history)
});

export default function configureStore(preloadedState) {
  return createStore(
      reducer,
      preloadedState,
      compose(
        applyMiddleware(
          ...middlewares
        )
      )
    );
}

I've found that many things need to be changed when migrating React to Next.js as Next is a framework which requires its own code architecture as well as the difference between SSR and CSR. When I studied Next.js tutorials, there is a routing section which says that routing is differentiated based on CSR or SSR. Does that mean I cannot use browser history in Next.js? That's what I'm guessting. I'm still confused.

A: You are right. There is different between SSR and CSR. Next.js use Next Router for routing for CSR and if you need custom SSR, then you should ask for some help from frameworks like express.
By doing the CSR, nextjs will remember browser history and back button works as expected. However if you need to change the route to a very diffrernt route you can use any of these solutions:
import Router from 'next/router';
...
Router .push('/about');

Or
import Link from 'next/link';
...
<Link href="/about">about</Link>

and if you need to do some extra work before routing then you should use:
Router.beforePopState(({ url, as, options }) => {...}

Migration would take some time and you need to remember next.js will take over the charge for routing and browser history automatically. Unless you customise it.


text:
Q: How make td element clickable, and make it working in IE? I get this code to make a td element clickable. It works fine in FF and Chrome but it doesn't work in IE. How can I improve this code?
$(document).ready(function() {

  $("td div.node-bloques-el-inicio").click(function(){

    window.location = $(this).find("h2 a").attr("href");
  });

});

capture of the code: capture

A: The above code is syntactically correct. Given the jQuery selectors in it, I'm assuming your HTML structure is as follows?

    ...

        ...

                    This is a link

        ...
    ...

If it is, your code should work in cross-browser. If this is you your HTML structure, please elaborate the question.


text:
Q: SMART support is: Unavailable - Packet Interface Devices [this device: Reserved] don't support ATA SMART So, I have a server which has 7 hardisks, each and everyone of them has smartmontools enabled, except the 7th hardisk (/dev/sdg). Tried force enabling it, did not work.
root@ac001.bafi:~# smartctl -a /dev/sdg
[unusually long delay]
=== START OF INFORMATION SECTION ===
Device Model:     CçS
Serial Number:    T- ^Rֻdª ª)EM½µr¢
Firmware Version: QÅ{õM
User Capacity:    1,257,344,326,144 bytes [1.25 TB]
Sector Size:      512 bytes logical/physical
Rotation Rate:    19867 rpm
Form Factor:      Unknown (0xf9e3)
Device is:        Not in smartctl database [for details use: -P showall]
...
SMART support is: Unavailable - Packet Interface Devices [this device:
Reserved] don't support ATA SMART

A mandatory SMART command failed: exiting.

Ran:
root@ac001.bafi:~# smartctl -H  /dev/sdg
smartctl 6.4 2014-10-07 r4002 [x86_64-linux-3.16.0-4-amd64] (local build)
Copyright (C) 2002-14, Bruce Allen, Christian Franke,
www.smartmontools.org

SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show    if SMART supported.
SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.
A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.

Even tried to force enable smartctl:
root@ac001.bafi:~# smartctl -T permissive -s on /dev/sdg1
smartctl 6.4 2014-10-07 r4002 [x86_64-linux-3.16.0-4-amd64] (local build)
Copyright (C) 2002-14, Bruce Allen, Christian Franke,
www.smartmontools.org

=== START OF ENABLE/DISABLE COMMANDS SECTION ===
unable to fetch IEC (SMART) mode page [unsupported field in scsi command]


text:
Q: ie div positioned absolute width bug I have a DIV with position absolute that contains an INPUT field, i need this input to be centered vertically and horizontally inside the div which i have accomplished with display:block and text align, the problem is that the width property is not working the same way for IE (10 and below), the parent div have the proper width in chrome and firefox but a totally different one in IE10,9 and 8.
Just in case this information is relevant, the parent div is inside another div with position relative. I know it sounds like a question from back to the future but i was really surprised to notice that that im still having this issue after normalizer, etc.
Here's the code
HTML and CSS
<div>
    <input type="text" />
</div>

div {
    position:absolute;
    background: blue;
    width: 180px;
    padding:8px 0;
    display:block;
}

input {
    border-radius: 5px;
margin: 0;
height: 20px;
position: relative;
display: block;
margin: 0 auto;
}

A: The problem is caused by the em units.
If you compare IE and Chrome you will see that the green bar in the menu is more to the left in IE than Chrome. That is because there is a pixel difference here and there in the font-size.
They are calculated differently. I think IE approximates differently.
Maybe instead of trying to make the 2 browsers look the same, you could make it look good on both browsers. Users will not know.
Use either a CSS file that gets added in IE browsers, or detect the browser with javascript and add classes on body (similar to modernizr), or use CSS hacks.


text:
Q: when using powershell inline script in Yaml file I get error "while parsing a block mapping did not find expected key" Yaml is really frustrating to work with, I exported as YAML from an azure devops release pipleine and each time i insert this code into my yaml file and run it Azure devops always says "error -while parsing a block mapping did not find expected key" . Is someone able to help on how to include inline powershell scripts in yaml as the export yaml option in Azure Devops is useless
 - task: AzurePowerShell@5
   displayName: 'test inline script in yaml'
   inputs:
   azureSubscription: 'azuresubscriptionid'
   ScriptType: InlineScript
   Inline: |
     # Setting Variables
     $var1 = "1!
     Write-Output $var1
   preferredAzurePowerShellVersion: 3.1.0

A: Please find below the correct script:
  - task: AzurePowerShell@5
    displayName: 'test inline script in yaml'
    inputs:
      azureSubscription: 'azuresubscriptionid'
      ScriptType: InlineScript
      Inline: |
        # Setting Variables
        $var1 = "1"
        Write-Output $var1
      preferredAzurePowerShellVersion: 3.1.0

There is an additional indent after inputs:
Please have a look at the documentation.
Online Validator

Thanks to @vince-bowdren regarding the typo in the script.


text:
Q: Incremental load from multiple tables for join queries in Nifi For Incremental load we will be using QueryDatabaseTable processor which extracts data incrementally from one table. For writing sql query which extracts data from multiple tables we are using ExecuteSQL processor.
How can we extract incremental load for a join query??

A: If I understand what you're trying to do, in NiFi that's a Lookup pattern so you'd likely use LookupRecord with a DatabaseRecordLookupService. Each one of those would "join" the incremental load table with the rows from the table specified by the DatabaseRecordLookupService. For multiple joins you'd have a LookupRecord with corresponding DatabaseRecordLookupService for each of them.


text:
Q: mongodb aggregation framework $match - $lookup - $project (failing to use $project for structuring the result) Sample Data:
users collection:
[
    {
        "_id":ObjectId("614804bb4236d9b0896f4e7c"),
        "firstName":"Fabian",
        "lastName":"Barlow"
    },
    {
        "_id":ObjectId("614804bb4236d9b0896f4e7d"),
        "firstName":"Chloe",
        "lastName":"Mendez"
    },
    {
        "_id":ObjectId("614804bb4236d9b0896f4e7e"),
        "firstName":"Valentine",
        "lastName":"Sharp"
    }
]

bookings collection:
[
    {
        "_id":ObjectId("614805534236d9b0896f4e86"),
        "resourceName":"res-1",
        "duration":"10 days",
        "status":"active",
        "bookingCreatorId":ObjectId("614804bb4236d9b0896f4e7c")
    },
    {
        "_id":ObjectId("614805534236d9b0896f4e87"),
        "resourceName":"res-2",
        "duration":"15 days",
        "status":"active",
        "bookingCreatorId":ObjectId("614804bb4236d9b0896f4e7d")
    },
    {
        "_id":ObjectId("614805534236d9b0896f4e88"),
        "resourceName":"res-3",
        "duration":"15 days",
        "status":"completed",
        "bookingCreatorId":ObjectId("614804bb4236d9b0896f4e7d")
    }
]

I am trying to perform an aggregation query on the above collection "bookings", to get the result in a particular structure,
While using project i am trying to add a new field "bookingCreatorDetails" which needs to hold data from "users" collections, but instead of getting the correct data for users collections, i am  getting "Array" type for the fields inside "bookingCreatorDetails"
Attempt on creating the query ("bookings"):
[
    {
        '$match': {
        'status': 'active'
        }
    }, {
        '$lookup': {
        'from': 'users',
        'localField': 'bookingCreatorId',
        'foreignField': '_id',
        'as': 'bookingCreator'
        }
    }, {
        '$project': {
        'resourceName': 1,
        'duration': 1,
        'bookingCreatorId': 1,
        'bookingCreatorDetails.firstName': '$bookingCreator.firstName',
        'bookingCreatorDetails.lastName': '$bookingCreator.lastName'
        }
    }
]

Current incorrect result:
[
    {
        "_id":ObjectId("614805534236d9b0896f4e86"),
        "resourceName":"res-1",
        "duration":"10 days",
        "status":"active",
        "bookingCreatorId":ObjectId("614804bb4236d9b0896f4e7c"),
        "bookingCreatorDetails": {
            "firstName":Array,
            "lastName":Array
        }
    },
    {
        "_id":ObjectId("614805534236d9b0896f4e87"),
        "resourceName":"res-2",
        "duration":"15 days",
        "status":"active",
        "bookingCreatorId":ObjectId("614804bb4236d9b0896f4e7d"),
        "bookingCreatorDetails": {
            "firstName":Array,
            "lastName":Array
        }
    }
]

Expected Result:
[
    {
        "_id":ObjectId("614805534236d9b0896f4e86"),
        "resourceName":"res-1",
        "duration":"10 days",
        "status":"active",
        "bookingCreatorId":ObjectId("614804bb4236d9b0896f4e7c"),
        "bookingCreatorDetails": {
            "firstName":"Fabian",
            "lastName":"Barlow"
        }
    },
    {
        "_id":ObjectId("614805534236d9b0896f4e87"),
        "resourceName":"res-2",
        "duration":"15 days",
        "status":"active",
        "bookingCreatorId":ObjectId("614804bb4236d9b0896f4e7d"),
        "bookingCreatorDetails": {
            "firstName":"Chloe",
            "lastName":"Mendez"
        }
    }
]

A: The $lookup will always return in array of objects format, You can use $arrayElemAt operator to select first element from the array or $first operator from 4.4,

*

*using $arrayElemAt operator

  {
    "$project": {
      "resourceName": 1,
      "duration": 1,
      "bookingCreatorId": 1,
      "bookingCreatorDetails": {
        $arrayElemAt: ["$bookingCreator", 0]
      }
    }
  }

*

*using $first operator

  {
    "$project": {
      "resourceName": 1,
      "duration": 1,
      "bookingCreatorId": 1,
      "bookingCreatorDetails": {
        $first: "$bookingCreator"
      }
    }
  }

Out of the question if you want to remove _id from lookup result you can use $unset stage after your $project stage,
  { $unset: "bookingCreatorDetails._id" }


text:
Q: Nsubsitute mocking AS/IS .net I am having hard time mocking IDbConnection. I have a method that returns IDbConnection but than I have a check to verify if this connection is NpgsqlConnection like this:
if (conn as NpgsqlConnection == null)
{
    throw new System.Exception("error");
}

and while method returns mock object, casting(as) returns null and creates an exception. How can I use NSubsiute so it will treat it as NpgsqlConnection object?
And second question that is following up, if this one could be resolved is that I am using BeginBinaryImport from NpgsqlConnection which does not have an interface and I cannot mock it, how can I fake it, so it won't throw an error when used like this using var importer = conn.BeginBinaryImport("COPY..... ?

A: It depends on what you want to test actually. If you want to test the functionality of NpgsqlConnection also, you can create a NpgsqlConnection with a test connection string.
public void DoSomething()
{
    // returns NpgsqlConnection with test connection string
    // If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member.
    IDbConnection conn = _connectionManager.GetConnection();

    if (conn as NpgsqlConnection == null)
    {
        throw new System.Exception("error");
    }

    // functionality
    using (var writer = (conn as NpgsqlConnection).BeginBinaryImport("COPY data (field_text, field_int4) FROM STDIN BINARY"))
    {
        // do some stuff
    }
}

Here. You can make _connectionManager.GetConnection(); to return a test db connection which is a NpgsqlConnection. So you can test the code.
You can set it up like this:
var testConnection = new NpgsqlConnection("TESTCONNECTIONSTRING");
var conn = Substitute.For<ConnectionManager>();
conn.GetConnection().Returns(testConnection);

Otherwise, You need a dependency which abstracts functionality away from calling code. You don't need to worry too much about what a dependency is doing.
Your code can be something like this instead:
public void DoSomething()
{
    IDbConnection conn = _connectionManager.GetConnection(); // returns NpgsqlConnection

    _npgsqlConnectionHelper.ValidateConnection(conn);

    _npgsqlConnectionHelper.DoFunctionality(conn);
}

Here, you can mock _npgsqlConnectionHelper


text:
Q: Printers fail to report issues to CUPS CUPS has 3 fields that are used in issue reporting,

*

*printer-state (enum): Either idle, processing or stopped.

*printer-state-message: Plain text human readable explanation.

*printer-state-reasons: Listed description of the printer state, as described in RFC8011 p.152 this is where the real issue reporting happens. It has a list of comma delimited keywords describing the state of a printer eg. 'media-needed' or 'toner-low'

When testing a Zebra LP 2844 on Ubuntu 16.04 (and mac but let's keep this simple for now) using the Zebra EPL2 Label Printer driver, I get the following results.
----Printer out of paper----
Status Enum: processing
Status Message: printer-state-message: 1 textWithoutLanguage {Waiting for
printer to become available.}
Status Reason: printer-state-reasons: 1 keyword {none}

----Printer rejecting jobs----
Status Enum: idle
Status Message: printer-state-message: 1 textWithoutLanguage {Rejecting Jobs}
Status Reason: printer-state-reasons: 1 keyword {none}

As you can see, the 'Printer out of paper' issue and most issues that prevent the printer from printing resolve as 'processing' and never give me more information. You could figure out how long the printer has been 'processing' and deduce if there is a problem from there, but besides that being janky, the cause of the issue would remain unknown.
Meanwhile, the 'Printer rejecting jobs' state tells me absolutely nothing (remember, the Status Message is just human readable plain text and is not parsable due to there being no guidelines on what is put there). Besides hiring someone to read state-message there is no way for my program to know there is an issue.
This is not the case with all printers, for example, this is the output from a Brother HL-L2380DW
----Printer out of paper----
Status Enum: processing
Status Message: printer-state-message: 1 textWithoutLanguage {Waiting for job to complete.}
Status Reason: printer-state-reasons: 2 keyword {cups-waiting-for-job-completed, media-needed-error}

Of the 3 printers tested so far (HP, Brother, and Zebra), the Brother HL-L2380DW was the only printer to properly communicate issues. If you wish to test it yourself you can run this crude CUPS tool I tossed together in java https://github.com/Vzor-/cupstool More data helps!
I do not know if the issue lies with cups or with the manufacturers. Either way I need a way forward, be it as a fix or a group I can help to make a fix.
Edit: It seems Zebra does not make or maintain its own Linux drivers.

A: From Michael Sweet,

Kyle,
Status reporting is complicated, but in general the problem with
  driver-based queues can come from the driver not implementing STATE:
  message support (typically because the printer's communication channel
  does not provide support) or from the printer itself not supporting
  any kind of status reporting.
In the case of the Zebra printer, it does not support in-band status
  reporting so the CUPS-bundled driver has no way of getting status from
  the printer that way.  It also does not support the SNMP Printer MIB
  for status, so we don't even get out-of-band status... :/  Sadly,
  these kind of printers often do not support status reporting, which is
  funny given that many are deployed in industrial settings where remote
  monitoring is common...
Printers that implement IPP (typically all printers these days except
  label printers - so 98%+ of printers) support the IPP
  printer-state-reasons keywords for status, in addition to other IPP
  attributes and (in many cases) SNMP Printer MIB properties as well.

So it seems this is mostly just an issue with some label printers.


text:
Q: Azure API Gateway - support for OpenAPI format property I have two api endpoints
[HttpGet("/items/{id:guid}")]
public IActionResult GetItemById(Guid id)
{

[HttpGet("/items/{code}")]
public IActionResult GetItemByCode(string code)
{

Swagger seems to deal with those without any problem. I've looked into the OpenAPI json file and noticed that the guid endpoint has a format property in the parameter object set to "uuid". The code endpoint doesn't have this property set at all. The type parameter of both is set to "string", so I believe this is how swagger differentiate them. I wanted to import this json file to Azure API Gateway, but it failed because it's seeing both of them as the same signature. Does it mean that Azure doesn't support format property of the parameter object? Is it part of the v3 specification? Are there any plans for this to be supported in Azure in the nearest future? Was trying to look for any info regarding that, but couldn't find any details.

A: Yes, from APIM point of view those are the same. I'm really not sure how OpenAPI spec would handle those either, sure you can write such spec file, but what would that mean is unclear. I couldn't find any word about this is OpenAPIv2.
Such specs are problematic at runtime as well. One would have to have a quite comprehensive priority order to parameter types to make it somehow work, and I feel that this may not satisfy all. Imagine a call is made:
/items/9c850ade-c083-4f66-b03d-3fdecffb8bd0
should it match id:guid or code:string? This is not immediately clear. So it's best to avoid such ambiguities.


text:
Q: Regular Expressions in SQL Server to validate fax numbers I'm trying to use RegEx to validate phone numbers saved in a SQL Server 2016 Table. In this table there are thousands of fax numbers which stored as different formats. Ex : 800-123-4567, 800/123-4567, 800#123/4567 etc. Now I'm wanting to use RegEx to validate the phone numbers also output them in a way without any special characters or spaces in between. Ex : 8001234567.
Here's what I have tried which does not seems to work for some reason. If anyone out there could correct me what I'm doing wrong here, I would really appreciate it.
DECLARE @expres  VARCHAR(50) = '%[/,-,\,#]%'
DECLARE @cmpfax as CHAR(100);
SELECT @cmpfax = cmp_fax FROM cicmpy WHERE LTRIM(RTRIM(cmp_code)) = '100373' AND cmp_fax IS NOT NULL;
SELECT REPLACE(@cmpfax, @expres, '#');

Here's my dbfiddle for the above code which I've tested.

A: This is a variation on the answer I linked earlier, however, as the OP is on 2016 RTM, they can't use STRING_AGG. This, therefore, uses the "old" FOR XML PATH (and STUFF) method to reaggregate the characters.
CREATE OR ALTER FUNCTION [fn].[PatternCharacterReplace_XML] (@String varchar(8000), @Pattern varchar(100), @ReplacementCharacter varchar(1))
RETURNS table
AS RETURN
    WITH N AS(
        SELECT N
        FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
    Tally AS(
        SELECT TOP(LEN(@String))
               ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3, N N4)
    SELECT (SELECT CASE WHEN V.C LIKE @Pattern THEN @ReplacementCharacter ELSE V.C END
            FROM Tally T
                 CROSS APPLY (VALUES(SUBSTRING(@String,T.I,1)))V(C)
            ORDER BY T.I
            FOR XML PATH(''),TYPE).value('(./text())[1]','varchar(8000)') AS ReplacedString;

Then you get the values and remove the characters with something like this:
SELECT YT.Fax
       PCRX.ReplacedString AS NewFax
FROM dbo.YourTable YT
     CROSS APPLY fn.PatternCharacterReplace_XML(YT.Fax, '[^0-9]', '') PCRX
WHERE YT.Fax LIKE '%[^0-9]%';


text:
Q: Filtrar SearchPanes [DataTables] Tengo implementado un SearchPanes en mi proyecto y funciona sin problemas, pero deseo que al momento de filtrar el SearchPanes se actualice y se filtre también. Por ejemplo, este es mi SearchPanes:

La idea es que, si selecciono, por ejemplo, a Daniel Fonseca (el primer empleado) los registros de la Fecha, Hora y Servicio se actualicen automáticamente a solo lo que coincida con Daniel Fonseca.
Actualmente si selecciono cualquier empleado todos los demás criterios de búsqueda quedan igual, entonces si selecciono a Daniel Fonseca y Enero 09/2021 no muestra ningún resultado porque no hay registros que coincida con esos criterios de búsqueda.

No sé cómo hacer esto con la herramienta DataTables, ¿es posible hacer esto? y ¿cómo puedo hacerlo?

A: Después de investigar más fondo me di cuenta que la solución es bien sencilla, solo se debe usar searchPanes.cascadePanes como se observa en el siguiente ejemplo.


text:
Q: Some questions regarding architecture/design to this usecase? My application needs to work as middleware where it has got orders(in form of xml) from various
customers which contains the supplier id. Once it get the order, it needs to send order request
to different suppliers in the form of xml.i am double minded about three aspects of it. Here they are:-
Questions:

*

*What i am planning at high level is as soon as request come, put it on jms queue.(Now i am not sure
should i create queue for each supplier or one queue should be sufficient. I think one queue will be sufficient.
as maintaining large number of queues will be overhead.). Advantage of maintaining separate queue per supplier is message can be processed faster as there will be separate producer on each queue.

*Before putting the object on queue
i need to do some business validations. Also the structure of input xml i am receiving and output xml i need to send to supplier is different. For this i am planning to convert the input xml to java object then put on queue
so that validation can be done with ease at consumer side. Another thought is dont convert the xml into java object, just get all elements
value thru xpath/xstream api and validate them and put xml string as it is on queue because. Then at consumer side convert xml to java object then to different xml format. Is there a way of doing it?

*Now my requirement is consumer on queue process the messages on queue after every 5 hours and send the xml request
to suppliers. I am planning to use quartz scheduler here which will pick the job one by one and send to corresponding
supplier based on supplierId. Here is my question is if my job pick the message one by one and then send it to supplier.
it will be too slow . I am planning to handle it where quartz job create ThreadPool with size of say ten threads at time
which concurrently process the messages from queue(So here will be multiple consumers on queue. I think thats not valid for queue. Do i need topic here instead of queue?). Is second approach is better or there is some better than this?
i am expecting a load of 50k request per hour which mean around 15 request per second

A: Your basic requirement is ,

*

*Get order from customer as XML ( you have not told how you are receiving)

*Do basic Business validation .

*Send the Orders to Suppliers

And you would be excepting 50k Request ( You haven't provided the approximate an Order size).
Assuming your Average order size 10K, it would be around 500 MB required just to hold it in Queue ( irrespective of number of queues) . i am not sure which environment you are running.
For Point #1
          I would choose single Queue instead of multiple Queue
             - Choose the appropriate persistent store.
I am assuming you would be using Distributed Queue , so that it can be easily scale while adding clusters.
For Point #2
          I would be converting in POJO (Your own format ) and perform business validation. So that later if you want to extend the business validation to ruler or any other conversion it would be easy to maintain.
          - basically get the input in any form ( XML / POJO / JSON ...) and convert into Middle format ( you can write custome validator / conversion utility on top of Middle fomart) . And have Keep Mappings between the Common format to input as well output.  So that you can write formatters and use them. which will not impact in future while changing format for any specific supplier. Try to externalize the format mapping.
For Point # 3
        in your case, A Order needs to be processed by only once. So i would go with Queue. and you can have multiple Message Listeners . Message listeners deliver order in asynchronous. So you can have multiple Listeners for an Queue. And each listeners would run separate thread.
Is there a problem to send the orders as soon as it received ? It would be good for you as well as the supplier to avoid heavy load at particular time.

A: Since you are the middleware, you should handle data quick at the point of contact, to get your hands free for more incoming requests. Therefore you must find a way to distinquish the incoming data as quick and memory low as possible. Leave the processing of the data to modules more specific to the problem. A receptionist just directs the guests in the right spot.
If you really have to read and understand the received data in your specialized worker later on, use a threadpool. This way you can process the data parallelly without too much worry about outofmem. Just choose your pool size smartly and use only one. You could use a listener pattern to signal new incoming data to the worker multiton. You should avoid jaxb or better the complete deserialization of the data if possible. It eats up memory like hell.
I would not use jmx because you "messages" are relevant for only one listener.
If it is possible send the mail as soon as the worker is done with its work. If not, use a storage. This way you can later proove you processed the data and if something went wrong or you have to update your software, you do not have to worry about volatile data.


text:
Q: OpenSSL config files for certificates
*

*I need to create a root certificate using the command:

openssl req -new -config ca.conf -x509 -out ca.crt -keyout=ca.key

The certificate should look exactly like this:
openssl x509 -in ca.crt -text

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: <...>
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = <...>, L = <...>, O = <...>, CN = <Some name>
        Validity
            Not Before: <...>
            Not After: <...>
        Subject: C = C = <...>, L = <...>, O = <...>, CN = <Some name>
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus: <...>
                Exponent: <...>
        X509v3 extensions:
            X509v3 Key Usage: critical
                Certificate Sign
            X509v3 Basic Constraints: critical
                CA:TRUE, pathlen:1
    Signature Algorithm: sha256WithRSAEncryption
<...>

*I need to create a client certificate using the command:

openssl req -new -config client.conf -out client.csr -keyout=client.key

The certificate should look exactly like this:
openssl req -in client.csr -text

Certificate Request:
    Data:
        Version: 1 (0x0)
        Subject: CN = <name1, name2, ...>, C = <...>, L = <...>, O = <...>
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus: <...>
                Exponent: <...>
        Attributes:
        Requested Extensions:
            X509v3 Key Usage:
                Digital Signature
            X509v3 Extended Key Usage:
                TLS Web Client Authentication
            X509v3 Basic Constraints:
                CA:FALSE
    Signature Algorithm: sha256WithRSAEncryption
<...>

*I need to create the requested certificate using the command:

openssl x509 -req -extfile client.conf -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt

The certificate should look exactly like this:
openssl x509 -in client.crt -text

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: <...>
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = RU, L = Novosibirsk, O = Novosibirsk State Technical University, CN = <Some name>
        Validity
            Not Before: <...>
            Not After : <...>
        Subject: C = <...>, L = <...>, O = <...>, CN = <name1, name2, ...>
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus: <...>
                Exponent: <...>
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature
            X509v3 Extended Key Usage:
                TLS Web Client Authentication
    Signature Algorithm: sha256WithRSAEncryption
<...>

I can't change commands or enter anything through the console, everything has to be specified in the config files. Can you help me create ca.conf and client.conf? I tried reading the documentation on the OpenSSL site, but there is nothing helpful about config files.


text:
Q: Inserted data not going to phpMyAdmin database I'm having a problem with my data not going through to phpMyAdmin. The server and database connects the PHP but the data is not inserted into the table.
This is what I have so far.
    <?php

    $dbConnect = mysqli_connect("xxxxxxx", "xxxxx","xxxxx");
    if (!$dbConnect)
    die("
The database server is not available.
");
    echo "
Successfully connected to the database server.
";
    $dbSelect = mysqli_select_db( $dbConnect,"sxxxxxxx_db" );
    if (!$dbSelect)
    die("
The database is not available.
");
    echo "
Successfully opened the database.
";

    $sql = "INSERT INTO customer (Name,Password,Email,Phone) VALUES ('$_POST[namefield]', '$_POST[pwdfield]','$_POST[email]','$_POST[phone]' ) ";

     mysqli_query($sql,$dbConnect);

     mysqli_close($dbConnect);

    if(isset($_POST['namefield']) && isset($_POST['pwdfield']) && isset($_POST['cpwdfield']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['submit']))
        {
            $name = $_POST['namefield'];
            $password = $_POST['pwdfield'];
            $cpassword = $_POST['cpwdfield'];
            $email = $_POST['email'];
            $phone = $_POST['phone'];

            if ($_POST["pwdfield"] == $_POST["cpassword"])
    mysqli_query("INSERT INTO user VALUES('','$password')") or die(mysqli_error());

       else {
       echo("Password did not match! Try again. ");

A: *

*close your connection .

*You should not use $_POST directly in your query, use following way to prevent SQL injection.

//Connect

$unsafe_variable = $_POST["user-input"];
$safe_variable = mysql_real_escape_string($unsafe_variable);

mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");

//Disconnect

A: You have closed the database connection
 mysqli_close($dbConnect);

A: change sql slightly
$sql = "INSERT INTO customer (Name,Password,Email,Phone) VALUES ('".$_POST['namefield']."', '".$_POST['pwdfield']."','".$_POST['email']."','".$_POST['phone']."' ) "


text:
Q: HMS Location Kit, location updates working only if user select "Allow all the time" i'm editing an Android application in order to use both GMS and HMS.
About Location Kit, i followed the docs and requested location updates, but task succeeds only when user give "Allow all the time" permission to location use.
In manifest i've added ACCESS_BACKGROUND_LOCATION too, even i don't need it, in order to check if something changed.
HMS Core have "Allow all the time" location permission.
I also tested sample app (https://github.com/HMS-Core/hms-location-demo-android-studio), but it have the same problem.
When user selects "Allow only when in use", the requestLocationUpdates method fails with error code PERMISSION_DENIED (a.k.a. Insufficient permission, from the docs), whose solution, always from the docs, should be to verify permission configurations in the Manifest file.
I have to say, i'm testing on a Redmi Note 8T, so not a Huawei phone.
Someone could help?
Thanks.

A: Currently, the fused location and geofence functions can be used on non-Huawei phones.
To use fused location on non-Huawei phones, ensure that HMS Core (APK) and your app have the permission to always obtain the device location.Otherwise, an error indicating insufficient permission will be reported.

A: Currently, the fused location and geofence functions can be used on non-Huawei phones.
To use fused location on non-Huawei phones, ensure that HMS Core (APK) and your app have
the permission to always obtain the device location. During location, your app triggers the location service of HMS Core (APK). To ensure successful location, your app user needs to assign the location permission to HMS Core (APK).


text:
Q: how to return two custom uitableviewcells Hi just trying to figure out how to load two different custom uitableviewcells into two different sections on my uitableview... Just not sure on how to proceed... here is the code I have currently
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //Registration Button
    static NSString *CellIdentifier = @"CustomRegCell";
    static NSString *CellNib = @"LogInCustomCell";

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
        cell = (UITableViewCell *)[nib objectAtIndex:0];
    }
    return cell;

}

/////// NEW ATTEMPT.... :( if you could call it that..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0)
    {
        //Registration Button
        static NSString *CellIdentifier = @"CustomRegCell";
        static NSString *CellNib = @"LogInCustomCell";

        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
            cell = (UITableViewCell *)[nib objectAtIndex:0];
        }
        return cell;

    }
    else if (indexPath.section == 1)
    {
        //Registration Button
        static NSString *CellButtonIdentifier = @"CustomButtonCell";
        static NSString *CellButtonNib = @"LogInCustomCell";

        UITableViewCell *cellButton = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellButtonIdentifier];
        if (cellButton == nil) {
            NSArray *nibButton = [[NSBundle mainBundle] loadNibNamed:CellButtonNib owner:self options:nil];
            cellButton = (UITableViewCell *)[nibButton objectAtIndex:0];
        }
        return cellButton;

    }
    return nil;

}

A: Use the section property of the indexPath variable:
if (indexPath.section == 0)
{
    // do this
}
else if (indexPath.section == 1)
{
    // do that
}

The section number is based on the order in which they appear. The first section you want to show in the tableView will be 0, and so on.


text:
Q: how to pass a dictionary to another dictionary in python robot framework My test case has below line
${text_field}=  CREATE DICTIONARY  Name=First Name  Length=225  encryption_type=LineFPEEngine  Text=dtypeS
${email_field}=  CREATE DICTIONARY  Name=Email Address  Length=NULL  encryption_type=emailFTEEngine  Text=dtypeE
${phone_field}=  CREATE DICTIONARY  Name=Mobile Number  Length=NULL  encryption_type=PhoneNumberEncryptionEngine  Text=dtypeH
${custom_fields}=  CREATE DICTIONARY  TextName=${text_field}  Email=${email_field}  Phone=${phone_field}
${field_ids}=  create custom fields  ${custom_fields}

but when print type of custom field is
<class 'robot.utils.dotdict.DotDict'>

Now if try to print
            for i in custom_fields:
                print i, custom_fields[i]['Text']
it saying TypeError: string indices must be integers
How can i acess this

A: Robot dictionaries are a subclass of the normal dict. You can use them exactly like a normal dict, but with the added ability to use dot notation when the keys don't have special characters in them (eg: ${custom_fields.TextName}
The error you say you get mentions a text index not a dictionary index, but without seeing the code that generates the error it's impossible to know what you're doing wrong. When I create a keyword with the following definition, it works fine:
Keyword definition:
# example.py
def print_text(custom_fields):
    for i in custom_fields:
        print i, custom_fields[i]['Text']

Example test case:
# example.robot
*** Settings ***
Library  /tmp/example.py

*** Test Cases ***
Example
    ${text_field}=  CREATE DICTIONARY  Name=First Name  Length=225  encryption_type=LineFPEEngine  Text=dtypeS
    ${email_field}=  CREATE DICTIONARY  Name=Email Address  Length=NULL  encryption_type=emailFTEEngine  Text=dtypeE
    ${phone_field}=  CREATE DICTIONARY  Name=Mobile Number  Length=NULL  encryption_type=PhoneNumberEncryptionEngine  Text=dtypeH
    ${custom_fields}=  CREATE DICTIONARY  TextName=${text_field}  Email=${email_field}  Phone=${phone_field}
    print text  ${custom_fields}

A: It looks like you are trying to iterate through a list rather than a dictionary. the syntax for looping through dictionaries is like this
# lets say custom_fields = {'TextName': 'test value', 'Email': 'email value'}
custom_fields = {'TextName': 'test value', 'Email': 'email value'}

#loop through the dictionary like this
for item in custom_fields.items():
    print item

# keep in mind that the items() returns a list of key, value tuple pairs

you can check here for a reference on using dictionaries
https://www.tutorialspoint.com/python/python_dictionary.htm

A: Actually, it looks like you have a list of keys AND a dict and you want to use the list to loop through the dict.
So what you want to do is,
for i in field_ids:
    print custom_fields[i]


text:
Q: Why does the absence of an else block translate to Unit type return for a function? I noticed there is a type mismatch caused in the line else if(r1 == 0 || divisors.tail.isEmpty || !divisors.tail.contains(r1)){newAcc}. Because there is no else clause to my if ... else if ...
def euclidianDivision(dividend:Int,divisor:Int):(Int,Int)={
  val quotient = dividend/divisor
  val remainder = dividend%divisor

  (quotient,remainder)
}
def firstExpansion(dividend:Int,divisors:List[Int]):List[(Int,Int)]={
  def firstExpansionIter(dividend:Int,divisors:List[Int], acc:List[(Int,Int)]):List[(Int,Int)]= {
    val div1:Int = divisors.head
    val (q1,r1):(Int,Int) = euclidianDivision(dividend,div1)
    val newAcc:List[(Int,Int)] = acc:::List((div1,q1))
    if (divisors.tail.contains(r1)){
      firstExpansionIter(r1,divisors.tail,newAcc)
    }else if(r1 == 0 || divisors.tail.isEmpty || !divisors.tail.contains(r1)){newAcc}
  }
  firstExpansionIter(dividend,divisors,List((0,0))).tail
}

Here's the error code:

Error:(32, 15) type mismatch;  found   : Unit  required: List[(Int,
  Int)]
          }else if(r1 == 0 || divisors.tail.isEmpty || !divisors.tail.contains(r1)){newAcc}

I can correct this by adding the else clause, but how come if there is no outcome handled by default, the function tries to return a Unit?
N.B : Corrected code :
def firstExpansion(dividend:Int,divisors:List[Int]):List[(Int,Int)]={
  def firstExpansionIter(dividend:Int,divisors:List[Int], acc:List[(Int,Int)]):List[(Int,Int)]= {
    val div1:Int = divisors.head
    val (q1,r1):(Int,Int) = euclidianDivision(dividend,div1)
    val newAcc:List[(Int,Int)] = acc:::List((div1,q1))
    if (divisors.tail.contains(r1)){
      firstExpansionIter(r1,divisors.tail,newAcc)
    }else if(r1 == 0 || divisors.tail.isEmpty || !divisors.tail.contains(r1)){newAcc}
    else throw new RuntimeException("Something unexpected happened.")
  }
  firstExpansionIter(dividend,divisors,List((0,0))).tail
}

A:
I can correct this by adding the else clause, but how come if there is no outcome handled by default, the function tries to return a Unit?

In Scala, unlike more "imperative" languages, (almost) everything is an expression (there are very few statements), and every expression evaluates to a value (which also means that every method returns a value).
This means that, for example, the conditional expression if (condition) consequence else differentConsequence is an expression that evaluates to a value.
For example, in this piece of code:
val foo = if (someRandomCondition) 42 else "Hello"

the then part of the expression will evaluate to 42, the else part of the expression will evaluate to "Hello", which means the if expression as a whole will evaluate to either 42 or "Hello".
So, what is the type of foo going to be? Well, in the then case, the value is of type Int and in the else case, the value is of type String. But, this depends on the runtime value of someRandomCondition, which is unknown at compile time. So, the only choice we have as the type for the whole if expression is the lowest common ancestor (technically, the weak least upper bound) of Int and String, which is Any.
In a language with union types, we could give it a more precise type, namely the union type Int | String. (Scala 3 has union types, so we could give the expression this exact type, although Scala 3 will not infer union types.) In Scala 3, we could even annotate it with the even more precise type 42 | "Hello", which is actually the type that TypeScript is going to infer for the equivalent conditional expression:
const foo = someRandomCondition ? 42 : "Hello"

Now, let's move forward towards the code in the question:
val bar = if (someRandomCondition) 42

What is the type of bar going to be? We said above that it is the lowest common ancestor of the types of the then and else branch, but … what is the type of the else branch? What does the else branch evaluate to?
Remember, we said that every expression evaluates to a value, so the else branch must evaluate to some value. It can't just evaluate to "nothing".
This is solved by a so-called unit value of a unit type. The unit value and type are called the "unit" value and type, because the type is designed in such a way that it can only possibly be inhabited by a single value. The unit type has no members, no properties, no fields, no semantics, no nothing. As such, it is impossible to distinguish two values of the unit type from one another, or put another way: there can only be one value of the unit type, because very other value of the unit type must be identical.
In many programming languages, the unit value and type use the same notation as a tuple value and type, and are simply identified with the empty tuple (). An empty tuple and a unit value are the same thing: they have no content, no meaning. In Haskell, for example, both the type and the value are written ().
Scala also has a unit value, and it is also written (). The unit type, however, is scala.Unit.
So, the unit value, which is a useless value, is used to signify a meaningless return value.
A related, but different concept in some imperative languages is the void type (or in some languages, it is more a "pseudo-type").
Note that "returns nothing" is different from "doesn't return", which will become important in the second part of this answer.
So the first half of the puzzle is: the Scala Language Specification says that
if (condition) expression

is equivalent to
if (condition) expression else ()

Which means that in the (implicit) else case, the return type is Unit, which is not compatible with List[(Int, Int)], and therefore, you get a type error.
But why does throwing an exception fix this?
This brings us to the second special type: Nothing. Nothing is a so-called bottom type, which means that it is a subtype of every type. Nothing does not have any value. So, what then, would a return type of Nothing signify?
It signifies an expression that doesn't return. And I repeat what I said above: this is different from returning nothing.
A method that has only a side-effect returns nothing, but it does return. Its return type is Unit and its return value is (). It doesn't have a meaningful return value.
A method that has an infinite loop or throws an exception doesn't return at all. Its return type is Nothing and it doesn't have a return value.
And that is why throwing an exception in the else clause fixes the problem: this means that the type of the else clause is Nothing, and since Nothing is a subtype of every type, it doesn't even matter what the type of the then clause is, the lowest common supertype of the type of the then clause and Nothing will always be the type of the then clause. (Think about it: the lowest common ancestor of a father and any of his children, grandchildren, great-grandchildren, etc. will always be the father himself. The lowest common ancestor of T and any subtype of T will always be T. Since Nothing is a subtype of all types, the lowest common ancestor of T and Nothing will always be T because Nothing is always a subtype of T, no matter what T is.)


text:
Q: laravel casts doubles the date sometimes I have a web application supports multiple timezones, UTC is the default timezone and I used Laravel casts to read and set date times or times based on user timezone, but the problem I'm facing that sometimes its adding the difference in hours twice, lets say the difference between Istanbul and UTC two hours, its adding four.
the code is below, anyone faced something like this?
<?php

namespace App\Models\Casts;

use Carbon\Carbon;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class TimezoneDatetime implements CastsAttributes
{

    public function get($model, $key, $value, $attributes)
    {
        if (is_string($value)) {
            $date = Carbon::parse($value, config('app.default_timezone'))->setTimezone(detectUserTimezone());
            return $date;
        }

        if ($value instanceof Carbon) {
            return $value->copy()->setTimezone(detectUserTimezone());
        }

        return $value;
    }

    public function set($model, $key, $value, $attributes)
    {
        if (is_string($value)) {
            $date = Carbon::parse($value, detectUserTimezone())->setTimezone(config('app.default_timezone'));
            return $date;
        }

        if ($value instanceof Carbon) {
            return $value->copy()->setTimezone(config('app.default_timezone'));
        }

        return $value;
    }
}


text:
Q: Matching the scatter points colour with the Image colour bar I have made this GUI with PyQt5:

How can I make the colour of the points in the bottom plot match the colour bar in the 2D plot above? And change accordingly when I change the bar max/min ?

MWE:
from PyQt5 import QtGui, QtCore
import pyqtgraph as pg
import sys
import numpy as np

width = 1000
height = 500

x = np.linspace(-10,10,100)
def func():
    X, Y = np.meshgrid(x, x)
    return np.exp(-X**2/10 - Y**2/2)

array = func()
sumxaxis = np.sum(array, axis=0)
sumyaxis = np.sum(array, axis=1)

class layout():
    def setup(self, window):
        self.window = window
        self.window.resize(width, height)

        self.centralwidget = QtGui.QWidget(self.window)
        self.horizontallayout = QtGui.QHBoxLayout(self.centralwidget)
        self.window.setCentralWidget(self.centralwidget)

        self.plot = pg.GraphicsLayoutWidget(self.window)

        self.horizontallayout.addWidget(self.plot)
        self.view = self.plot.addPlot()
        self.img = pg.ImageItem(border='k')
        self.img.setImage(array, border = 'k')
        self.view.addItem(self.img)
        self.viewbox = self.view.getViewBox()

        self.hist = pg.HistogramLUTItem()
        self.hist.setImageItem(self.img)
        self.hist.setLevels(0, 1)
        self.hist.gradient.loadPreset('viridis')
        self.plot.addItem(self.hist, colspan=1)

        self.plot.nextRow()
        self.plot2 = self.plot.addPlot(colspan=1)
        self.plot2.setMaximumHeight(200)
        self.plot2.plot(-x,sumyaxis,symbol='o',symbolSize=1, symbolBrush=('w'), pen=None, clear=True)

class Window(pg.Qt.QtGui.QMainWindow, layout):

    def __init__(self, shot = None):

        super(Window, self).__init__()
        self.setup(self)
        self.show()

if __name__ == '__main__':
    app = pg.Qt.QtGui.QApplication([])
    Window()
    sys.exit(app.exec_())

UPDATE
I managed to change the scatter plot to the same colourbar as the 2D image, but I have not yet managed to make it change its colour as I drag the colour bar cursor!

New MWE:
from PyQt5 import QtGui, QtCore
import pyqtgraph as pg
import sys
import numpy as np

width = 1000
height = 500

x = np.linspace(-10,10,100)
def func():
    X, Y = np.meshgrid(x, x)
    return np.exp(-X**2/10 - Y**2/2)

array = func()
sumyaxis = array[:, len(array)//2]

class layout():
    def setup(self, window):
        self.window = window
        self.window.resize(width, height)

        self.centralwidget = QtGui.QWidget(self.window)
        self.horizontallayout = QtGui.QHBoxLayout(self.centralwidget)
        self.window.setCentralWidget(self.centralwidget)

        self.plot = pg.GraphicsLayoutWidget(self.window)

        self.horizontallayout.addWidget(self.plot)
        self.view = self.plot.addPlot()
        self.img = pg.ImageItem(border='k')
        self.img.setImage(array, border = 'k')
        self.view.addItem(self.img)
        self.viewbox = self.view.getViewBox()

        self.hist = pg.HistogramLUTItem()
        self.hist.setImageItem(self.img)
        self.hist.setLevels(0, 1)
        self.hist.gradient.loadPreset('viridis')
        self.plot.addItem(self.hist, colspan=1)

        self.colours = self.hist.getLookupTable(img=array)
        self.cmap = pg.ColorMap(pos=np.linspace(self.hist.getLevels()[0], self.hist.getLevels()[1], len(self.colours)), color=self.colours)

        self.plot.nextRow()
        self.plot2 = self.plot.addPlot(colspan=1)
        self.plot2.setMaximumHeight(200)
        self.c = self.cmap.map(sumyaxis, 'qcolor')
        self.plot2.plot(-x,sumyaxis,symbol='o',symbolSize=10, symbolBrush = self.c, pen=None, clear=True)

class Window(pg.Qt.QtGui.QMainWindow, layout):

    def __init__(self, shot = None):

        super(Window, self).__init__()
        self.setup(self)

        self.show()

if __name__ == '__main__':
    app = pg.Qt.QtGui.QApplication([])
    w = Window()
    sys.exit(app.exec_())

A: You have to use the sigLookupTableChanged signal and implement the logic to update the symbolBrush of PlotDataItem:
    # ...
    self.plot.nextRow()
    self.plot2 = self.plot.addPlot(colspan=1)
    self.plot2.setMaximumHeight(200)
    self.curve = self.plot2.plot(
        -x,
        sumyaxis,
        symbol="o",
        symbolSize=10,
        pen=None,
        clear=True,
    )
    self.hist.sigLookupTableChanged.connect(self.handle_sigLookupTableChanged)
    self.handle_sigLevelsChanged()

def handle_sigLookupTableChanged(self):
    colours = self.hist.getLookupTable(img=array)
    cmap = pg.ColorMap(
        pos=np.linspace(*self.hist.getLevels(), len(colours)),
        color=colours,
    )
    c = cmap.map(sumyaxis, "qcolor")
    self.curve.opts["symbolBrush"] = c
    self.curve.updateItems()


text:
Q: Checkbox covers content in editing mode in UITableView EDIT: Since I got a downvote, I'll provide some more details
I tried following apples guide for multiple selection in UITableView. What I've done is basically only:
tableView.allowsMultipleSelectionDuringEditing = true

and then:
tableView.setEditing(true, animated: true)

Here:
https://developer.apple.com/library/ios/samplecode/TableMultiSelect/Introduction/Intro.html
In their sample-app the label in the UITableViewCell get squeezed a bit to the right when entering editing mode.
However, in my app, the check-box gets covered by the default checkbox.
Like this:
What am I supposed to do to get the correct behaviour?

A: Instead of add subviews (labels) on cell
//cell.addSubview(aLabel)

add labels on cell's contentView
cell.contentView.addSubview(aLabel)


text:
Q: mysql wont start on my xamp how to fix this?
MySQL said: Documentation

Cannot connect: invalid settings.
 mysqli::real_connect(): (HY000/2002): No connection could be made because the target machine actively refused it
 Connection for controluser as defined in your configuration failed.
 mysqli::real_connect(): (HY000/2002): No connection could be made because the target machine actively refused it
 phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.

A: If you are using different port instead of 3306 you have to specify  it in config.inc.php.
For example if I am using 3308 port so i have to do
$cfg['Servers'][$i]['port'] = 3308
Below username and password extension.


text:
Q: Is $f(x,y)=\frac{x|y|}{\sqrt{x^2+y^2}}$ continuous and differentiable? Let $$f(x,y)=\begin{cases}\frac{x|y|}{\sqrt{x^2+y^2}} &\textrm{ if } (x,y)\neq(0,0), \\ 0 &\textrm{ if } (x,y)= (0,0).\end{cases} $$
I want to know: is $f$ is continuous? Are the partial derivatives exists at the origin? Is $f$ differentiable?
First, I tried some different paths to prove that $f$ is discontinuous, but none path lead me to it.
I found the partial derivatives:
$$\frac{\partial f}{\partial x}(x,y)=\frac{(y^2-x^2)|y|}{(x^2+y^2)^{3/2}},\quad \frac{\partial f}{\partial y}(x,y)=\frac{x|y|(x^2-y^2)}{y(x^2+y^2)^{3/2}}. $$
By doing $(x,y)=(0,t)$, the limit of the first partial derivative does not exist:
$$\lim_{t\rightarrow 0}\frac{t^2|t|}{t^3}=\lim_{t\rightarrow 0}\frac{|t|}{t} $$
Is this sufficient to  conclude that $f$ is not differentiable? What can I do?

A: *

*Continuity: $(x-|y|)^2=x^2+y^2-2x|y|\geq0 \iff \frac{x^2+y^2}{2}\geq x|y|$

*Partial Derivatives: $\frac{\partial f}{\partial x}(0,0)=\lim_{h\to0} \frac{f((0,0)+h(1,0))-f(0,0)}{h}$ and it is analogous for $\frac{\partial f}{\partial y}(0,0)$.

*Derivability: Consider the linear application, $L$ , such that for any $(x,y)\in\mathbb{R^2}:L(x,y)=0$ then
$$\lim_{(x,y)\to(0,0)} \frac{f(x,y)-f(0,0)-L((x,y)-(0,0))}{||(x,y)-(0,0)||}=\lim_{(x,y)\to(0,0)} \frac{x|y|}{x^2+y^2}$$
Can you take it from here?

A: Firstly $f$ is continuous, indeed by polar coordinates we have
$$\frac{x|y|}{\sqrt{x^2+y^2}}=r\cos \theta |\sin \theta| \to 0$$
For differentiability by the definition we have
$$\frac{\partial f}{\partial x}(0,0)=\frac{\partial f}{\partial y}(0,0)=0$$
and
$$\lim_{(h,k)\to(0,0)} \frac{\frac{h|k|}{\sqrt{h^2+k^2}}}{\sqrt{h^2+k^2}}=\lim_{(h,k)\to(0,0)} \frac{h|k|}{h^2+k^2} \neq 0$$
and therefore $f$ is not differentiable.
As noticed, we cannot conclude for differentiability from the discontinuity of partial derivatives.


text:
Q: Setting two different sessions on same domain for two different folders in PHP I have an application that has user management using sessions.Under the root folder of the application I have an admin panel which I need to have different session as otherwise it conflicts with the root session.
-root
   -admin/adminFiles
   -rootFiles

I went through this thread and also the docs and tried the below code in my admin folder
if(HTTP_SERVER != 'http://localhost'){
    session_save_path("/tmp");
}
 session_name('session_for_admin');
 ini_set('session.cookie_path','/session_for_admin');
 session_set_cookie_params(60*60*24*5,'session_for_admin');
 session_start();

This just does not start the session.No error in the logs too.
What am I doing wrong here.
I want to do it this way because the admin folder is just going to be accessed by a few privileged users and not very frequently. I am aware that session_name() adds and overhead.But would like to get through it this way.

A: so in regard to what you say about having an admin flag in your database:
let's say that $admin contains a boolean: true if your database confirmed the user as an admin, false if it's not
this will activate the session with name based on the result of this boolean:
if ($admin)
 {session_name('session_for_admin');}
else
 {session_name('session_for_others');}
session_start();

this will start and manage two different sessions, in the same way that two different users will have their own session.
admittedly from there you may want to do other things such as changing the working directory, or include different files.
Which you could also do by just setting a variable in your session when the user is logged in as admin:
$_SESSION['admin'] = true;

from then on, you can check and use some files or other like this:
if ($_SESSION['admin'])
 {// use files in admin folder
  }
else
 {// use files in root folder
  }

A: Try using session_name before you start the session
For example, in the first domain, use
session_name("AdminPanel");
session_start();

In the second domain, use
session_name("WebsiteID");
session_start();

For more visit session name


text:
Q: How to close async client connection in ASIO? I'm trying to create a client for the C++ 20 server example, the one that uses coroutines.
I'm not quite sure how I'm supposed to close the client connection. As far as I'm aware, there are two ways:
#1
This one seems to be closing it once it's ready/there is nothing else to do like read/write operations.
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto) { io_context.stop(); });

#2
Force close?
asio::post(io_context_, [this]() { socket_.close(); });

Which one should I use?
Client code (unfinished)
#include <cstdlib>
#include <deque>
#include <iostream>
#include <thread>
#include <string>

#include <asio.hpp>

using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::redirect_error;
using asio::use_awaitable;

awaitable<void> connect(tcp::socket socket, const tcp::endpoint& endpoint)
{
    co_await socket.async_connect(endpoint, use_awaitable);
}

int main()
{
    try
    {
        asio::io_context io_context;
        tcp::endpoint endpoint(asio::ip::make_address("127.0.0.1"), 666);
        tcp::socket socket(io_context);

        co_spawn(io_context, connect(std::move(socket), endpoint), detached);

        io_context.run();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

Server code
#include <cstdlib>
#include <deque>
#include <iostream>
#include <list>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <asio/awaitable.hpp>
#include <asio/detached.hpp>
#include <asio/co_spawn.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/read_until.hpp>
#include <asio/redirect_error.hpp>
#include <asio/signal_set.hpp>
#include <asio/steady_timer.hpp>
#include <asio/use_awaitable.hpp>
#include <asio/write.hpp>

using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::redirect_error;
using asio::use_awaitable;

//----------------------------------------------------------------------

class chat_participant
{
public:
    virtual ~chat_participant() = default;
    virtual void deliver(const std::string& msg) = 0;
};

typedef std::shared_ptr<chat_participant> chat_participant_ptr;

//----------------------------------------------------------------------

class chat_room
{
public:
    void join(chat_participant_ptr participant)
    {
        participants_.insert(participant);
        for (const auto &msg : recent_msgs_)
            participant->deliver(msg);
    }

    void leave(chat_participant_ptr participant)
    {
        participants_.erase(participant);
    }

    void deliver(const std::string& msg)
    {
        recent_msgs_.push_back(msg);
        while (recent_msgs_.size() > max_recent_msgs)
            recent_msgs_.pop_front();

        for (const auto &participant : participants_)
            participant->deliver(msg);
    }

private:
    std::set<chat_participant_ptr> participants_;
    enum { max_recent_msgs = 100 };
    std::deque<std::string> recent_msgs_;
};

//----------------------------------------------------------------------

class chat_session
    : public chat_participant,
    public std::enable_shared_from_this<chat_session>
{
public:
    chat_session(tcp::socket socket, chat_room& room)
        : socket_(std::move(socket)),
        timer_(socket_.get_executor()),
        room_(room)
    {
        timer_.expires_at(std::chrono::steady_clock::time_point::max());
    }

    void start()
    {
        room_.join(shared_from_this());

        co_spawn(socket_.get_executor(),
            [self = shared_from_this()]{ return self->reader(); },
            detached);

        co_spawn(socket_.get_executor(),
            [self = shared_from_this()]{ return self->writer(); },
            detached);
    }

    void deliver(const std::string& msg) override
    {
        write_msgs_.push_back(msg);
        timer_.cancel_one();
    }

private:
    awaitable<void> reader()
    {
        try
        {
            for (std::string read_msg;;)
            {
                std::size_t n = co_await asio::async_read_until(socket_,
                    asio::dynamic_buffer(read_msg, 1024), "\n", use_awaitable);

                room_.deliver(read_msg.substr(0, n));
                read_msg.erase(0, n);
            }
        }
        catch (std::exception&)
        {
            stop();
        }
    }

    awaitable<void> writer()
    {
        try
        {
            while (socket_.is_open())
            {
                if (write_msgs_.empty())
                {
                    asio::error_code ec;
                    co_await timer_.async_wait(redirect_error(use_awaitable, ec));
                }
                else
                {
                    co_await asio::async_write(socket_,
                        asio::buffer(write_msgs_.front()), use_awaitable);
                    write_msgs_.pop_front();
                }
            }
        }
        catch (std::exception&)
        {
            stop();
        }
    }

    void stop()
    {
        room_.leave(shared_from_this());
        socket_.close();
        timer_.cancel();
    }

    tcp::socket socket_;
    asio::steady_timer timer_;
    chat_room& room_;
    std::deque<std::string> write_msgs_;
};

//----------------------------------------------------------------------

awaitable<void> listener(tcp::acceptor acceptor)
{
    chat_room room;

    for (;;)
    {
        std::make_shared<chat_session>(co_await acceptor.async_accept(use_awaitable), room)->start();
    }
}

//----------------------------------------------------------------------

int main()
{
    try
    {
        unsigned short port = 666;

        asio::io_context io_context(1);

        co_spawn(io_context,
            listener(tcp::acceptor(io_context, { tcp::v4(), port })),
            detached);

        asio::signal_set signals(io_context, SIGINT, SIGTERM);
        signals.async_wait([&](auto, auto) { io_context.stop(); });

        io_context.run();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

A: In the example provided by asio, the listener runs within the io_context thread/thread-pool, which is started by run() and given a thread-pool size when constructing the io_context(1 /* pool of 1 */).
The listener will use an acceptor to listen for new connections from within the io_context. The acceptor will create a new chat_session for each new socket connection and will hand it over to the chat_room.
Thus, to safely close a connection, you need to post a lambda to asio. The asio::post will queue the lambda to be done from within the io_context thread(s).
You need to provided the correct io_context and the socket owned by the chat_session. The connection MUST be closed from within the io_context as follows:
// Where "this" is the current chat_session owning the socket
asio::post(io_context_, [this]() { socket_.close(); });

The io_context wil then close the connection and also call any active registered async_read / async_write methods of the chat_session such as in the c++11 example:
void do_read()
  {
    asio::async_read(socket_,
        asio::buffer(read_msg_.data(), chat_message::header_length),
      /* You can provide a lambda to be called on a read / error */
        [this](std::error_code ec, std::size_t /*length read*/)
        {
          if (!ec)
          {
            do_read(); // No error -> Keep on reading
          }
          else
          {
          // You'll reach this point if an active async_read was stopped
          // due to an error or if you called socket_.close()

          // Error -> You can close the socket here as well,
          // because it is called from within the io_context
            socket_.close();
          }
        });
  }

Your first option will actually stop the entire io_context. This should be used to gracefully exit your program or stop the asio io_context as a whole.
You should thus use the second option to "close an async client connection in ASIO".


text:
Q: Do quantmod indicator calculations include the current day? I'm new to quantmod and I would like to know if the indicators that I can add have a lagging as part of their calculation.
For example, will RSI calculate the RSI based on the last 14 days without the current day or with the current day? If I would like to get the RSI of the last day should I wrap the code with the lag function as my second line of code below?
# The 14-period relative strength index calculated off the open
RSI_14 <- RSI(Op(Data),n=14)
# The 14-period relative strength index calculated off the prior day's open
RSI_14_lastDay <- lag(RSI(Op(Data),n=14),K=1)

A: I checked it with SMA and it seems that indicators include current row (last new row) as part of the calculation, so there is a need to add a lag function in order to get the last period value on the current row. Here is an example:
RSI_14_lastDay <- lag(RSI(Op(Data),n=14),K=1)


text:
Q: Segmentation fault at GTK+ program I am trying to make an example of a simple GTK+ viewer using poppler and cairo which I found at gtkforums.com work. However I am getting a segmentation fault (I use anjuta).
When I use the debugger I get this:
ID:1
File: /usr/lib/i386-linux-gnu/libgdk-x11-2.0.so.0
Line: 0
Function: ??
Address: 0x1d3f16 (dont think that matters anyway)
terminal message while debugging:

Debug Terminal for the process:
  ------------------------------- &"warning: GDB: Failed to set controlling terminal: Operation not permitted\n"
GLib-GObject-WARNING **: cannot register existing type `GdkWindow'
GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT
  (object_type)' failed

Here is my code:
#include <config.h>
#include <glib/gi18n.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo.h>
#include <poppler.h>

/* gcc `pkg-config --cflags --libs gtk+-2.0 poppler-glib` -o pdfviewer pdfviewer.c */

static PopplerDocument* doc;
static PopplerPage* page;

static void
on_destroy(GtkWidget* w, gpointer data) {
    gtk_main_quit();
}

static gboolean
on_expose(GtkWidget* w, GdkEventExpose* e, gpointer data) {
    cairo_t* cr;
    cr = gdk_cairo_create(w->window);
    poppler_page_render(page, cr);
    cairo_destroy(cr);
    return FALSE;
}

int main(int argc, char* argv[]) {
    GtkWidget* win;
    GError* err = NULL;

    gtk_init(&argc, &argv);

    doc = poppler_document_new_from_file("file:///home/user/test.pdf", NULL, &err);
    if (!doc) {
        printf("%s\n", err->message);
        g_object_unref(err);
        return 2;
    }

    page = poppler_document_get_page(doc, 0);
    if(!page) {
        printf("Could not open first page of document\n");
        g_object_unref(doc);
        return 3;
    }

    int pages = poppler_document_get_n_pages(doc);
    printf("There are %d pages in this pdf.\n", pages);

    win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect(G_OBJECT(win), "destroy",      G_CALLBACK(on_destroy), NULL);
    g_signal_connect(G_OBJECT(win), "expose-event", G_CALLBACK(on_expose), NULL);
    gtk_widget_set_app_paintable(win, TRUE);
    gtk_widget_show_all(win);

    gtk_main();

    g_object_unref(page);
    g_object_unref(doc);

    return 0;
}

A: Based upon your comment it ("Cannot access memory at address 0x0") appears that the program has a function that fails, but you didn't check the function's return value to ensure it is not NULL before using it.
Based purely on the code example above the first case of that would be if gtk_window_new failed; then the g_signal_connect and other functions cannot use the win value sensibly.
When I compiled the snippet, it compiled fine without warnings, and executed correctly. There was a poppler error message about the PDF document, but it wasn't relevant to your problems.
So your problem is likely either elsewhere (not within the included example) or a trivial mistake.

A: One way to get more information is to set a breakpoint on g_log in the debugger and get a backtrace  of the warning / critical. With the backtrace you'll be able to see where exactly your code is calling the gtk+ function that is failing.


text:
Q: Get-ChildItem inside the A Get-ChildItem I have a question about a script I am writing.  I need a script that can find all folders inside a specific folder (in this case WRA), but I also want to find the sub-folders inside WRA
For example:
\Server01\WRA contains 100 folders
\Server01\WRA\Folder 1
\Server01\WRA\Folder 2
...
...
I want to look inside the "Folder 1" and obtain a report of the folders inside "Folder 1" and locate the folders older than 30 days which can be done with
Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))}

This is what I have so far
$FolderNames = Get-ChildItem "\\Server01\WRA\" -Directory |
    Select-Object Name, LastWriteTime

$FolderNames

Thank you for all your help

A: You can use this:
Get-ChildItem "\\Server01\WRA\" -Directory |
Get-ChildItem -Directory |
Where-Object -Property LastWriteTime -LT ([datetime]::Now).AddDays(-30) |
Select-Object Name, LastWriteTime

Edit
$directories = Get-ChildItem "\\Server01\WRA\" -Directory
$targetDate = ([datetime]::Now).AddDays(-30)

foreach($parentDir in $directories)
{
    $subFolders = Get-ChildItem $parentDir -Directory |
    Where-Object -Property LastWriteTime -LT $targetDate

    if($subFolders)
    {
        "Parent Directory: {0}" -f $parentDir.FullName
    }

    foreach($childDir in $subFolders)
    {
        "Parent SubFolder: {0}" -f $childDir.FullName

        $childDir | Select-Object Name, LastWriteTime | Out-String
    }
}


text:
Q: iPhone, Object allocated and stored into 'glossPath' is not referenced later (object leaked) I have this warning in analyzer and also in leaks instrument, how can I fix this leak?
Object allocated on line 86 and stored into 'glossPath' is not referenced later in this execution path and has a retain count of +1 (object leaked)
Tnx

A: You are responsible for releasing the object returned by CGPathCreateMutable() as per "The Create Rule". It is also stated in the reference:

Return Value
A new mutable path. You are responsible for releasing this object.

You can use CGPathRelease() to release the path.
CGPathRelease(glossPath);


text:
Q: When running ajax with cron its not executing the PHP file where I need to save the data I am trying to save data into MySQL using file add.php through ajax. I am getting data through cron.php. Data is saved when I am running cron.php file in browser but it's not saved when am running through cron job.
Here is my code:
cron.php
  $.ajax({
              method: 'POST',
              url:    'add.php',
               data: { id: id, videoid: vids }
               })
              .done(function(data) {
                          });

add.php
  am inserting id and videoid in the database.
Can anyone help me to insert data using cron with ajax and php

A: Ajax is a front end thing while cron job is a pure server back-end thing.
Instead of ajax you should make a function similiar to what is in add.php or call it from your cron.php passing arguments to it.

A: If you need to send data to add.php through POST, you can use CURL in cron.php instead of your jQuery code.
Another solution would be to send the data to add.php directly using GET parameters (instead of POST).


text:
Q: How To print out some data from a select query using PHP This is my code:
$arr = array(
    'cust_id' => "{$_SESSION['cust_id']}"
);

$query = $sql->select_query("code",$arr);
$result = $mysqli->query($query);

while ($row = $result->fetch_assoc()) {
    echo "<option name='{$row['pagename']}>{echo $row['pagename']}</option>";

?>

All I need to do is print out a option for each pagename for use in a drop down menu. Thanks in advance

A: while ($row = $result->fetch_assoc()) {
                              echo "<option name='{$row['pagename']}>{echo $row['pagename']}</option>";

to
<?php
while ($row = $result->fetch_assoc()) {
?>
     <option name="<?php echo $row['pagename']; ?>" > <?php echo $row['pagename']; ?> </option>
<?php
} ?>