text:
Q: How does Monitor Synchronisation work? So I'm reading about synchronisation and have come across Monitors, but can't seem to grasp how they work.
I see the general layout is something in the format of the following with what I can see as condition variables (and I'm not really sure what these do):
monitor {
    // shared variables
    procedure P1 (..) {..}
    ...
    procedure P2 (..) {..}
    initialisation code (..) {..}
}

However, as much as I bang my head against this, I can't see to really see how a monitor such as that described would allow only one process to access at a time.

A: I like to think of a monitor as an object that has a private mutex, and where every procedure is protected by that mutex.  So something like:
MyClass {
  // private shared variables
  ...
  mutex m;
  // public procedures
  Procedure P1(...) {
    acquire(m);
    ...
    release(m);
  }
  Procedure P2(...) {
    acquire(m);
    ...
    release(m);
  }
  initialisation code (...) { ... }
}

The mutex is guaranteeing that only one thread/process at a time can be manipulating the object, because every public Procedure is wrapped with mutex acquire/release.
Now what about those condition variables?  Well, often you don't need them.  But sometimes you have some condition where one thread needs to wait for another, that's where condition variables come in.
Suppose for example that you were implementing a concurrent queue object.  You would have a push() procedure and a pop() procedure.  But what should you do if the queue is empty?
It won't work to have separate empty() and pop() procedures, because of code like this:
Thread A                Thread B
if (not q.empty())
                        if (not q.empty())
                        then q.pop() // now q is empty!
then q.pop() // error!

So you would have to define an pop() procedure which returns a special value when the queue is empty, and then spin wait for the queue to become not empty.  But spin waiting is incredibly inefficient.
So instead you use a condition variable.  A condition variable has two methods: wait() and notify().  Wait() atomically gives up the mutex that you are holding, and then blocks the thread until some other thread calls notify().  So like this:
condition_variable cv;
Procedure int pop() {
  acquire(m);
  while (q.empty()) {
    wait(cv, m)  // atomically release m and wait for a notify() on cv.
    // when wait() returns it automatically reacquires mutex m for us.
  }
  rval = q.pop();
  release(m);
  return rval;
}
Procedure push(int x) {
  acquire(m);
  q.push(x);
  notify(cv);  // wake up everyone waiting on cv
  release(m);
}

Now you have a data structure/object where only one thread can be accessing the object at a time, and you can take care of situations where the operations between different threads need to happen in a particular order (like that at least one push() has to happen before each pop() can complete.)


text:
Q: Find position in active record object I have a league table that i create with:
 QuizuserAnswer.all(:include =>:user, :select => 'user_id, SUM(answer) AS points', :group =>'user_id', :order=>'points DESC'

This returns an object like this:
 => [#<QuizuserAnswer user_id: 340>, #<QuizuserAnswer user_id: 348>]

Now i want to find the league table position of one specific user. Is there a clean way? or do i have to loop through al columns?

A: From a very little i got your question i think you want something like following
answers = QuizuserAnswer.all(:include =>:user, :select => 'user_id, SUM(answer) AS points', :group =>'user_id', :order=>'points DESC')
user_id = 348
answers.map(&:user_id).index(user_id) #This will return 1

i.e It will return the position of the answer given by the user among the answer's list

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using set_index in time series to eliminate holiday data rows from DataFrame I am trying to eliminate holiday data from a time series pandas DataFrame.  The instructions I am following processes a DatetimeSeries and uses the function set_index() to apply this DatetimeSeries to the DataFrame which results in a time series without the holidays.  This set_index() function is not working for me.  Check out the code...
{data_day.tail()}
Open    High    Low Close   Volume
Date
2018-05-20  NaN NaN NaN NaN 0.0
2018-05-21  2732.50 2739.25 2725.25 2730.50 210297692.0
2018-05-22  2726.00 2741.75 2721.50 2738.25 179224835.0
2018-05-23  2731.75 2732.75 2708.50 2710.50 292305588.0
2018-05-24  2726.00 2730.50 2705.75 2725.00 312575571.0

from pandas.tseries.holiday import USFederalHolidayCalendar

from pandas.tseries.offsets import CustomBusinessDay

usb = CustomBusinessDay(calendar=USFederalHolidayCalendar())

usb

<CustomBusinessDay>

data_day_No_Holiday = pd.date_range(start='9/7/2005', end='5/21/2018', freq=usb)
data_day_No_Holiday

DatetimeIndex(['2005-09-07', '2005-09-08', '2005-09-09', '2005-09-12',
               '2005-09-13', '2005-09-14', '2005-09-15', '2005-09-16',
               '2005-09-19', '2005-09-20',
               ...
               '2018-05-08', '2018-05-09', '2018-05-10', '2018-05-11',
               '2018-05-14', '2018-05-15', '2018-05-16', '2018-05-17',
               '2018-05-18', '2018-05-21'],
              dtype='datetime64[ns]', length=3187, freq='C')

data_day.set_index(data_day_No_Holidays, inplace=True)

----------------------------------------------------------------------

ValueError                                Traceback (most recent call last)
<ipython-input-118-cf7521d08f6f> in <module>()
----> 1 data_day.set_index(data_day_No_Holidays, inplace=True)
      2 # inplace=True tells python to modify the original df and to NOT create a new one.

~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in set_index(self, keys, drop, append, inplace, verify_integrity)
   3923         index._cleanup()
   3924
-> 3925         frame.index = index
   3926
   3927         if not inplace:

~/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in __setattr__(self, name, value)
   4383         try:
   4384             object.__getattribute__(self, name)
-> 4385             return object.__setattr__(self, name, value)
   4386         except AttributeError:
   4387             pass

pandas/_libs/properties.pyx in pandas._libs.properties.AxisProperty.__set__()

~/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in _set_axis(self, axis, labels)
    643
    644     def _set_axis(self, axis, labels):
--> 645         self._data.set_axis(axis, labels)
    646         self._clear_item_cache()
    647

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in set_axis(self, axis, new_labels)
   3321             raise ValueError(
   3322                 'Length mismatch: Expected axis has {old} elements, new '
-> 3323                 'values have {new} elements'.format(old=old_len, new=new_len))
   3324
   3325         self.axes[axis] = new_labels

ValueError: Length mismatch: Expected axis has 4643 elements, new values have 3187 elements

This process seemed to work beautifully for another programmer.
Can anyone suggestion a datatype conversion or a function that will apply the DatetimeIndex to the DataFrame that will result in dropping all datarows (holidays) that are NOT represented in the data_day_No_Holiday DatetimeIndex?
Thanks, Let me know if I made any formatting errors or if I am leaving out any relevant information...

A: Use reindex:
from pandas.tseries.holiday import USFederalHolidayCalendar

from pandas.tseries.offsets import CustomBusinessDay

usb = CustomBusinessDay(calendar=USFederalHolidayCalendar())

data_day_No_Holiday = pd.date_range(start='1/1/2018', end='12/31/2018', freq=usb)

data_day  = pd.DataFrame({'Values':np.random.randint(0,100,365)},index = pd.date_range('2018-01-01', periods=365, freq='D'))

data_day.reindex(data_day_No_Holiday).dropna()'

Output(head):
            Values
2018-01-02      38
2018-01-03       1
2018-01-04      16
2018-01-05      43
2018-01-08      95


text:
Q: increasing, decreasing, non-decreasing, non-increasing permutation/combination I have this question and I'm stuck:

Q: In the set of three-digit integers {100,101,...,999}, how many integers are there
(a) with three distinct digits that are either increasing (as in 257, 139) or decreasing (as in 752, 430)?
(b) with three digits that are either non-decreasing (as in 477, 555, 123) or non-increasing (666,321,943)?
(Note that digits may repeat.)

For part a) I got to 7 * _ * _ as you know for the three digit number as 8, 9 cannot be the first digit, it would not make a three digit number however I don't know how to proceed because wouldn't the second digit vary from the first digit picked?
I would like to understand this as much as I can. Thanks!

A: We solve the first problem. There is some complication because $0$ is not allowed as an initial digit.
So let us first count how many possibilities there are if we allow initial $0$. We can choose the $3$ digits in $\binom{10}{3}$ ways, and for each such choice we can arrange the digits in two orders, increasing or decreasing, for a total of $2\binom{10}{3}$.
Now we must take away the "bad" choices, the ones with initial digit $0$. There are $\binom{9}{2}$ ways to choose $2$ non-zero digits, and we can only use increasing order. So the number of bad choices is $\binom{9}{2}$. Thus the total number of good choices is $2\binom{10}{3}-\binom{9}{2}$.
For the second problem, one can count the additional possibilities that are produced by allowing equality.

A:
In the set of positive three-digit integers $\{100, 101, \ldots, 909\}$, how many integers are there with three distinct digits that are either increasing or decreasing?

A three-digit positive integer with strictly increasing digits corresponds to a selection of three of the nine digits in the string $123456789$.  For instance, the selection $1\color{blue}{2}34\color{blue}{5}6\color{blue}{7}89$ corresponds to selecting the number $257$.  Thus, the number of three-digit positive integers with strictly increasing digits is $\binom{9}{3}$.
A three-digit positive integer with strictly decreasing digits corresponds to a selection of three of the ten digits in the string $9876543210$.  For instance, the selection $98765\color{blue}{43}21\color{blue}{0}$ corresponds to selecting the number $430$.  The number of three-digit positive integers with distinct decreasing digits is $\binom{10}{3}$.
Since the two cases are mutually exclusive, the number of positive three-digit integers with distinct digits that are either increasing or decreasing is
$$\binom{9}{3} + \binom{10}{3}$$

In the set of positive three-digit integers $\{100, 101, \ldots, 999\}$, how many integers are there with three digits that are non-decreasing or non-increasing?

Hint:  A three-digit positive integer with non-decreasing digits is completely determined by how many times each digit appears.  For instance, if $3$ appears twice and $2$ appears once, then the number must be $233$ since the digits are non-decreasing.


text:
Q: FreeMarker FMPP Failed to evaluate function "csv" Using FMPP version 0.9.15, I'm following the documentation examples to pull data from a CSV file. If I use command line with config.fmpp:
sourceRoot: src
outputRoot: out
data: {tdd(data/style.tdd), birds:csv(data/birds.csv)}

Or ANT config:
<project name="FMPP test" default="build">

    <taskdef name="fmpp" classname="fmpp.tools.AntTask">
        <classpath>
           <pathelement location="lib/fmpp.jar"/>
        </classpath>
    </taskdef>

    <target name="build">
        <fmpp
              sourceRoot="src" outputRoot="out"
              data="tdd(data/style.tdd), birds:csv(data/birds.csv)"
        />
    </target>
</project>

I receive the following error either way:
TDD error: Failed to evaluate function "csv".
tdd(data/style.tdd), birds:csv(data/birds.csv)
                       ^

On the other hand, If I switch to "birds:text..." or "birds:splitText..." I do not get the evaluation error.  It looks like csv is still supported in the code. Any idea why the TDD data source is not recognizing the csv function?

A: Did you try adding a space  between birds: and csv(data/birds.csv)?
data: {
    tdd(data/style.tdd)
    birds: csv(data/birds.csv)
}


text:
Q: A set of functions generating another set of functions. I have read this fact being used in a book, but I don't quite see why it is true, can you please help me?
Assume you have a probability space $(\Omega,\mathcal{A},P)$. Let $\mathcal{D}$ be the class of funtioncs $\mathbb{R}\times \Omega \rightarrow \mathbb{R}$ that is $\mathcal{B}(\mathbb{R})\otimes \mathcal{A}$ -measurable. Let $\mathcal{E}$ be the set of functions of the form $f(x)X(\omega)$ where $f$ is $\mathcal{B}(\mathbb{R})$-measurable and $X$ is a random variable, hence $\mathcal{A}$-measurable.  Let $\sigma(\mathcal{E})$ be the smallest collection of sets of $\mathcal{B}(\mathbb{R})\otimes \mathcal{A}$ such that every function in $\mathcal{E}$ is $\sigma(\mathcal{E})$-measurable. It is then stated(indirectly) that $\sigma(\mathcal{E})=\mathcal{B}(\mathbb{R})\otimes \mathcal{A}$.
Is the property as stated here true? If yes, is there an easy way to show it?

A: $\mathcal{B}\otimes \mathcal{A} \subset \sigma(\mathcal{E})$, since for each measurable rectangle $B \times A \in \mathcal{B}\otimes \mathcal{A}$, $\mathbb{1}_B\mathbb{1}_A$ is measurable, hence $B \times A \in \sigma(\mathcal{E})$, and $\mathcal{B}\otimes \mathcal{A}$ is the smallest $\sigma-$algebra containing the measurable rectangles. The other inclusion is clear from the definition.


text:
Q: How do you call a function that takes in a MAT file, manipulate the data in that file, and create a new textfile with that same MAT file name? The filename in question is a MAT file that contains elements in the form of "a - bi" where 'i' signifies an imaginary number. The objective is to separate the real, a, and imaginary, b, parts of these elements and put them into two arrays. Afterwards, a text file with the same name as the MAT file will be created to store the data of the newly created arrays.
Code:
function separate(filename)

    realArray = real(filename)
    imagArray = imag(filename)

    fileIDname = strcat(filename, '.txt')
    fileID = fopen(fileIDname, 'w')

    % more code here - omitted for readability

end

I am trying to run the above code via command window. Here's what I've tried so far:
%attempt 1
separate testFileName

This does not work as the output does not contain the correct data from the MAT file. Instead, realArray and imagArray contains data based on the ascii characters of "testFileName".
e.g. first element of realArray corresponds to the integer value of 't', the second - 'e', third - 's', etc. So the array contains only the number of elements as the number of characters in the file name (12 in this case) instead of what is actually in the MAT file.
%attempt 2
load testFileName
separate(testFileName)

So I tried to load the testFileName MAT variable first. However this throws an error:
Complex values cannot be converted to chars
Error in strcat (line 87)
    s(1:pos) = str;
Error in separate (line xx)
   fileIDname = strcat(filename, '.txt')

Basically, you cannot concatenate the elements of an array to '.txt' (of course). But I am trying to concatenate the name of the MAT file to '.txt'.
So either I get the wrong output or I manage to successfully separate the elements but cannot save to a text file of the same name after I do so (an important feature to make this function re-usable for multiple MAT files).
Any ideas?

A: A function to read complex data, modify it and save it in a txt file with the same name would look approximately like:
function dosomestuff(fname)
   % load
   data=load(fname);

   % get your data, you need to knwo the variable names, lets assume its call "datacomplex"
   data.datacomplex=data.datacomplex+sqrt(-2); % "modify the data"

   % create txt and write it.
   fid=fopen([fname,'.txt'],'w');
   fprintf(fid, '%f%+fj\n', real(data.datacomplex), imag(data.datacomplex));
   fclose(fid);

There are quite few assumptions on the data and format, but can't do more without extra information.


text:
Q: I was trying to implement useState hook in plain JavaScript to see its working. Below is my code, but it is not working and goes into infinite loop It seems kind of magic to me how React is able to maintain the state variable value inside the functional component between re-renders. So I tried to implement myself to see how things work. But fails. If you can point to some good resources where I can see what goes under the hood to achieve this process or can tell what I am doing wrong in the code. React source is a bit hard to understand at this point for me. Thank you.
  const MyReact = {
  state: null,
  stateInitialized: false,
  setState(newState) {
    if (this.state !== newState);
    {
      this.state = newState;
      Component();
    }
  },
  useState(initialValue) {
    if (!this.stateInitialized) {
      this.stateInitialized = true;
      this.state = initialValue;
    }
    return [this.state, this.setState];
  },
};

function Component() {
  const [count, setCount] = MyReact.useState(10);
  console.log(count);
  setCount(20);
}

Component();

A: You have two problems in your code:

*

*Wrong semicolon in setState(): if (this.state !== newState);, which leads to an unconditional call of Component() and thus an endless recursion.

*More subtle: In useState(), you return this.setState without binding it to MyReact, which leads to setCount() setting the state globally (i.e. on the window object). Replace it with this.setState.bind(this).

A: Hooks are triggered by events and in turn, dispatch those event changes to the recorded handler (setCount()).
The Component is a constructor function and must be instantiated (as seen in line 20 of this React Source code). So this source more closely reflects React's structure.

const MyReact = {
  state: null,
  stateInitialized: false,
  setState(newState) {
    if (this.state !== newState);
    {
      this.state = newState;
    }
    console.log("newCount event calls setState: ",this.state);
  },
  useState(initialValue) {
    this.setState = this.setState.bind(this);
    if (!this.stateInitialized) {
      this.stateInitialized = true;
      this.state = initialValue;
    }
    console.log("Component calls useState: ",this.state);
    return [this.state, this.setState];
  },
};

function Component() {
  const [count, setCount] = MyReact.useState(10);
  this.listener = setCount;
}

const component = new Component();

document.addEventListener("newCount", (e) => { component.listener(e.detail.value) });

// create and dispatch the event
var event = new CustomEvent("newCount", {
  detail: {
    value: 0
  }
});

event.detail.value = 20;
document.dispatchEvent(event);
event.detail.value = 30;
document.dispatchEvent(event);
console.log("MyReact.state = ",MyReact.state);


text:
Q: Laravel: error doing migration Sorry my poor english.
I'm learning Laravel. I've tried do a migration (php artisan migrate)
and i get this error message:
[PDOException]
  SQLSTATE[HY000] [1045] Access denied for user 'homest
  ead'@'localhost' (using password: YES)
Laravel is trying connecting using user homestead... however my database config file specify using root as user to connect to the database:

What's going wrong?
Thanks for any help.

A: Go to .env(at the root of your project) and overwrite the Database information there. like this
DB_HOST=localhost
DB_DATABASE=lixo
DB_USERNAME=root
DB_PASSWORD=segredo

A: For homestead the default username is Homestead and password is secret.

A: In .env file:
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=DBName
DB_USERNAME=root
DB_PASSWORD=password

Close the laravel application server and restart again for clearing the cache.
 php artisan serve

try it!


text:
Q: Get table schema or structure in netbeans, derby I've been creating a database in derby/netbeans. And I'd like to output the structure of the database, not just exporting the whole database. How do I do this?
I've tried both "EXEC 'table name';"
which returned
"Error code -1, SQL state 42X01: Syntax error: Encountered "exec" at line 1, column 1."
and
"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'table name';"
which returned "Error code -1, SQL state 42Y07: Schema 'INFORMATION_SCHEMA' does not exist".
I've read on multiple forums that this should work, do you guys have any idea what I'm doing wrong?

A: GET TABLE STRUCTURE
select COLUMNNAME,COLUMNDATATYPE
FROM sys.systables t, sys.syscolumns
WHERE TABLEID = REFERENCEID and tablename = 'FRIENDS'

Other fields you can use in select

*

*COLUMNDEFAULT

*COLUMNDEFAULTID

*AUTOINCREMENTVALUE

*AUTOINCREMENTSTART

*AUTOINCREMENTINC

Inside Netbeans
Expand the Tables node under the sample database connection, right-click the table node and choose Grab Structure.

In the Grab Table dialog that opens, specify a location on your computer to save the grab file that will be created. Click Save.
The grab file records the table definition of the selected table.
Expand the APP schema node under the Contact DB database connection, right-click the Tables node and choose Recreate Table to open the Recreate Table dialog box.

In the Recreate Table dialog box, navigate to the location where you saved the CUSTOMER grab file and click Open to open the Name the Table dialog box.

GET TABLES
A complete list.
select * from SYS.SYSTABLES;

Only TABLENAME
select TABLENAME from SYS.SYSTABLES where TABLETYPE='T'

Derby Table

A: The simplest with NetBeans (8.0, perhaps with the previous versions too): "View Data..." of the table, right click on the data and choose "Show SQL Script for CREATE". You can copy the SQL script.

A: Another way to do this is to use the "dblook" utility: http://db.apache.org/derby/docs/10.10/getstart/tgsrunningdblook.html

A: The easiest way is to enter the command:
DESCRIBE table_name;


text:
Q: What is the syntax used for the library that contains the built-in map function on Arduino? I have been looking across various sites and I cannot seem to find much information regarding the information on the Arduino function libraries. I am using an HCS12 microcontroller (MC9S12DG256B) that has fewer libraries built into the bootloader. One of these lacking functionalities includes a built-in map function. I am specifically asking about the math and syntax that the Arduino utilizes in the library that contains the map function. How does Arduino define the map function? Here is what I am trying to define on my micro written in Arduino syntax.
int pot;
int PWM = map(pot,0,1023,3300,5700);

A: From the docs
https://www.arduino.cc/reference/en/language/functions/math/map/
map(value, fromLow, fromHigh, toLow, toHigh)

value: the number to map.
fromLow: the lower bound of the value's current range.
fromHigh: the upper bound of the value's current range.
toLow: the lower bound of the value's target range.
toHigh: the upper bound of the value's target range.

The math function is also given

long map(long x, long in_min, long in_max, long out_min, long out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}


text:
Q: Called service function from controller error "is not a function" So as a title says I'm calling function in Service by other function in controller which start on input[submit] click. I get following error when I click this input:

TypeError: authenticationService._register is not a function
      at Object.$ctrl.registerSubmit (RegisterModalCtrl.js:14)

HTML:
<form method="post"
      name="registerData"
      id="registerData"
      ng-submit="$ctrl.registerSubmit()">

controller function called on submit:
$ctrl.registerSubmit = function() {
    console.log('im in registerSubmit controller function');
    authenticationService._register(); // im line 14 obviously
    $uibModalInstance.dismiss('cancel');
};

service function called by controller function:
var _register = function(registerExternalData) {
    console.log('im in register service function');
    /*
        ...
    */
};

I inject my service in controller:
app.controller('RegisterModalCtrl', ['$scope', '$location', '$uibModalInstance', 'authenticationService',
function($scope, $location, $uibModalInstance, authenticationService) {

A: If you're using angular service (& not the factory) then instead of var use this to define function inside service (service is like a constructor function):
this._register = function(registerExternalData) {
    console.log('im in register service function');
    /*
        ...
    */
};

Everything else same, no need of any other change in your code.


text:
Q: ActiveReports 7 - How to format data on multiples columns with a subreport My question is similar to this one
here
The differences are that I'm on ActiveReports 7 instead of Crystal Report and that I'm using multiples SubReport on the same page...
[Edit]: I found it !
In the event "detail_Format" of my subreport, I used this code below to calculate how many rows by columns.
private int count = 0;
public void Detail_Format()
{
int maxElement = (result.Count() / this.detail.ColumnCount);

    if (count == maxElement)
    {
      this.detail.NewColumn = NewColumn.After;
      count = 0;
    }
    else
    {
      this.detail.NewColumn = NewColumn.None;
      count++;
    }
}

A: You may use the following code snippet in the Script tab to add a pagebreak after every ten records :
int i = 0;
public void Detail_Format()
{
    i = i + 1;
    if(i > 9)
      {
         this.Detail.NewPage = GrapeCity.ActiveReports.SectionReportModel.NewPage.After;
         i = 0;
          }
    else
      {
         this.Detail.NewPage = GrapeCity.ActiveReports.SectionReportModel.NewPage.None;
          }
}

Regards,
Mohita

A: There is a problem when I split my data into column. On each new page, the first row of data isn't splitted into column... I don't understand why ?


text:
Q: Python Code not outputting I am having trouble with the code shown below. For some reason, it is not outputting any values for the last part of my code. I also have my csv sheet as well. It is not outputting.
output = 'From Bus #: {}\tTo Bus #: {}\tTo Bus #: {}\t Area Station: {}\t VMIN: {} pu\tVMAX: {} pu\t'
print(output.format(from_, to,name2, min_value, max_value,last_bus))

The code is shown below as well as the csv sheet.Also in that part of that code, instead of me saying if last_bus==126783, Is there a way of saying if an integer value exists in that column, the code will run. I am asking because I am limited to only one condition with 126783
Excel Sheet
from __future__ import print_function
import os.path
import win32com.client

#---------------------------------------------------------------------------------------------------------------------
xlApp = win32com.client.DispatchEx('Excel.Application') # Running Excel
xlsPath = os.path.expanduser('C:\Users\RoszkowskiM\Desktop\UPDATED_LOAD_FORECAST_4.xlsm')# Reading xlsm file
wb = xlApp.Workbooks.Open(Filename=xlsPath) # Opening file
xlApp.Run('csvfile2')# Running macro---- csvfile2 is the macro name. It is under the "csv" module in the VBA editor
wb.Save()
xlApp.Quit()
#---------------------------------------------------------------------------------------------------------------------
# WHEN RUNNING THE PROGRAM, MAKE SURE THE CSV FILE IS NOT OPEN.

# THIS WILL PRODUCE AN ERROR WITH READING AND RUNNING THE MACRO.

# THE EXCEL WORKBOOK CAN BE OPEN WHEN RUNNING THE PROGRAM

import os, sys
#--------------------------------------------------------------------------
#PSSE_LOCATION = r"C:\Program Files (x86)\PTI\PSSE33\PSSBIN" #Locating PSSE
#sys.path.append(PSSE_LOCATION)
#os.environ['PATH'] = os.environ['PATH'] + ';' + PSSE_LOCATION
#--------------------------------------------------------------------------

#----------------------------------------------------------------------------------------------------------------
#import psspy
#import redirect
import csv
#psspy.throwPsseExceptions = True
from Tkinter import *    # File Dialog
import tkFileDialog
import tkSimpleDialog
import tkMessageBox
import Tkinter as tk

#Pop up window for picking file on PSSE
#root = tk.Tk()
#root.withdraw()
#tkMessageBox.showinfo("Welcome", "Please select case: ")
#root.fileName= tkFileDialog.askopenfilename( filetypes = ( ("PSSE CASES", "*.sav"), ("PSSE CASES", "*.raw*") ) )
#STUDY_CASE=root.fileName

#psspy.psseinit(10000)  # Intialize PSSE
#psspy.case(STUDY_CASE) # Upload Case

LOAD_GEN_DATAFILE = 'C:\Users\RM\Desktop\Data_2017.csv' # CSV File to Read

# read the entire CSV into Python.
# CSV has columns starting with  Year,busnum,busname,scaled_power,tla,location,empty,year_link,from_,to,digit,min_value,max_value,last_bus
#-------------------------------------------------------------------------------
# read the entire CSV into Python.
# CSV has columns starting with Year,busnum,busname,scaled_power,tla,location
data = list(csv.reader(open(LOAD_GEN_DATAFILE)))
mydict = {}
for row in data:
    Year,busnum,busname,scaled_power,tla,data_location,empty,year_link,from_,to,digit,name2,tla_2,min_value,max_value,last_bus = row[0:16]

    #If this is a year not seen before, add it to the dictionary
    if Year not in mydict:
        mydict[Year] = {}

    busses_in_year = mydict[Year]
    if data_location not in busses_in_year:
         busses_in_year[data_location] = []

    #Add the bus to the list of busses that stop at this location
    busses_in_year[data_location].append((busnum,busname,scaled_power))
#-------------------------------------------------------------------------------

#-------------------------------------------------------------------------------------------------------------------------------------
#User Input Statement

year = raw_input("Please Select Year of Study: ")

print("\n")

location=raw_input(" \n The list above show the TLA Pockets as well as the ID numbers assigned to them ()\n\n Please enter the ID #: ")
#psspy.prompt_output(islct = 6)
print("\n")
Year=year
data_location=location
#---------------------------------------------------------------------------------------------------------------------------------------

#-------------------------------------------------LOAD FORECASTS--------------------------------------------------------------------
if Year in mydict and data_location in mydict[Year]:
    busses_in_year = mydict[Year]
    #print("Here are all the busses at that location for that year and the new LOAD TOTAL: ")
    #print("\n")

    #Busnum, busname,scaled_power read from excel sheet matching year and location

    for busnum,busname,scaled_power in busses_in_year[data_location]:
        scaled_power= float(scaled_power)
        busnum = int(busnum)
        output='Bus #: {}\t Area Station: {}\t New Load Total: {} MW\t'
        print(output.format(busnum,busname,scaled_power))
        #psspy.bsys(1,0,[0.0,0.0],0,[],1,[busnum],0,[],0,[])
        #psspy.scal_2(1,0,1,[0,0,0,0,0],[0.0,0.0,0.0,0.0,0.0,0.0,0.0])
        #psspy.scal_2(0,1,2,[0,1,0,1,0],[scaled_power,0.0,0,-.0,0.0,-.0,0])

else:
    exit
#-------------------------------------------------LOAD FORECASTS--------------------------------------------------------------------

#------------------------------------------------VOLTAGE ENVLOPES---------------------------------------------------------------------------------------------------------------------------------

for row in data:
    year_link, from_,to,digit,name2,tla_2,min_value,max_value,last_bus = row[7:16]
    output = 'From Bus #: {}\tTo Bus #: {}\t Area Station: {}\t VMIN: {} pu\tVMAX: {} pu\t'
    if year_link == year and tla_2==location:
        from_=int(from_)
        to=int(to)
        min_value=float(min_value)
        max_value=float(max_value)
        digit=int(digit)

        print(output.format(from_, to,name2, min_value, max_value))
        #_c=psspy.getdefaultchar()
        #_i=psspy.getdefaultint()
        #_f=psspy.getdefaultreal()
        #psspy.two_winding_chng_4(from_,to,'%d'% digit,[_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f, max_value, min_value,_f,_f,_f],[])
    else:
        exit
for row in data:
     year_link, from_,to,digit,name2,tla_2,min_value,max_value,last_bus = row[7:16]
     if year_link==year and tla_2==location and isinstance(last_bus, int):
        output = 'From Bus #: {}\tTo Bus #: {}\tLast Bus #: {}\t Area Station: {}\t VMIN: {} pu\tVMAX: {} pu\t'
        print(output.format(from_, to,name2, min_value, max_value,last_bus))
        min_value=float(min_value)
        max_value=float(max_value)
        #psspy.three_wnd_winding_data_3(from_,to,last_bus,r"""1""",1,[_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f, max_value, min_value,_f,_f,_f])
     else:
        exit

    #------------------------------------------------VOLTAGE ENVLOPES----------------------------------------------------------------------------------------------------------------------------------

os.remove(LOAD_GEN_DATAFILE)

A: This is a way to replace your last_bus==126783 code
isinstance(last_bus, int)

and for the output question, could you check
if year_link == year and last_bus==126783 or year_link == year and last_bus==126783:

ever return True?


text:
Q: can ninject intercept private methods? I would like to know if its possible for ninject to intercept private methods on my class. im trying to do some aop programming to dynamically inject the logging mechanism.

A: Unfortunately, all methods to be intercepted must be virtual [and hence not private].
See this blog series by @Ian Davis for a flavour of what Ninject.Extensions.Interception majors in.
Deeper AOP on the .NET platform is typically the realm of PostSharp, which provides hihg and low level AOP abstractions of all kinds.


text:
Q: How to restrict the number of folders being returned by Known Folder library in Windows Phone 8.1? IReadOnlyList<IStorageItem> PicturesLibrary = await KnownFolders.PicturesLibrary.GetFoldersAsync();
await Pass_it_to_afunction(PicturesLibrary);

Known Folders are great. I love 'em. In this particular context, I am using Picture Library from Known Folders Class to get all the folders. So, if there are 50 folders, all the 50 folders will be returned at once. I don't want it like that.
I am thinking about something like the concept of "pagination". Return first 20 folders initiall, next 20 in next event(a button click or something), next 20 in next event (since there are only 10 folders left, 10 folders will be returned).
Is that possible? IDK. I haven't implemented it yet. IDK how to do that either.
I would like to hear propostions. Any suggestions/sample/comments/downvotes or anything useful would be greatful.
Well....Useful & Greatful rhymes.

A: What about Take (LINQ)? It returns the desired amount of elements from the beginning.
http://msdn.microsoft.com/de-de/library/bb503062%28v=vs.110%29.aspx


text:
Q: Not able to update story's Release field, when I am dragging feature card from one release to another release column I have created a cardboard application, whiich has Backlog and releases as headers.
Each column has number of features for that release, but when I am dragging the feature, I am able to change the release field for that feature.
But not able to update that feature story's Release field.
below is my code, any suggestions, help @nickm, @kyle
        Ext.override(Rally.ui.cardboard.Column,{
            getStoreFilter: function(model) {
                var property = this.attribute;
                var value = this.getValue();
                if ( this.attribute == "Release" ) {
                    property = "Release.Name";
                    if ( value ) {
                        value = value.get('Name');
                    }
                }
                return {
                    property:property,
                    operator: '=',
                    value: value
                };
            },
            isMatchingRecord: function(record) {
                var recordValue = record.get(this.attribute);
                if (recordValue) {
                    recordValue = recordValue.Name;
                }
                var columnValue = this.getValue();
                if ( columnValue ) {
                    columnValue = columnValue.get('Name');
                }

                return (columnValue === recordValue );
            },
            addCard: function(card, index, highlight) {
                var record = card.getRecord();
                console.log("record what we want", record);
                var project = record.get('Context');
                var target_value = this.getValue();
                if ( target_value && typeof(target_value.get) === "function" ) {
                    target_value = this.getValue().get('_ref');
                }
                //console.log("values to see", record, this.attribute, target_value);
                record.set(this.attribute,target_value);
                if (target_value) {
                    this._updateStories(record, project, this.getValue()).then({
                        success: function(){
                            console.log("Updated");
                        },
                        scope: this
                    }, this);
                    record.set("PlannedStartDate",this.getValue().get('ReleaseStartDate'));
                    record.set("PlannedEndDate",this.getValue().get('ReleaseDate'));
                } else {
                    record.set("PlannedStartDate",null);
                    record.set("PlannedEndDate",null);
                }
                if (!Ext.isNumber(index)) {
                    //find where it should go
                    var records = Ext.clone(this.getRecords());
                    records.push(record);
                    this._sortRecords(records);
                    var recordIndex = 0;
                    for (var iIndex = 0, l = records.length; iIndex < l; iIndex++) {
                        var i = records[iIndex];
                        if (i.get("ObjectID") === record.get("ObjectID")) {
                            recordIndex = iIndex;
                            break;
                        }
                    }
                    index = recordIndex;
                }
                this._renderCard(card, index);
                if (highlight) {
                    card.highlight();
                }
                this.fireEvent('addcard');
                card.fireEvent('ready', card);
            },
            _updateStories: function(record, project, releaseVal) {
                var deferred = Ext.create('Deft.Deferred');
                Ext.create('Rally.data.WsapiDataStore',{
                    model: 'HierarchicalRequirement',
                    autoLoad: true,
                    filters: [
                        {property:'Feature.ObjectID', value: record.get('ObjectID') },
                        //{property:'Parent.ObjectID', value: record.get('ObjectID') }
                        //{property:'DirectChildrenCount',value:0 }
                    ],
                    context: project,
                    limit: Infinity,
                    fetch: ['Name','Release','ObjectID'],
                    listeners: {
                        load: function(store, stories, operation) {
                            Ext.Array.each(stories, function(story) {
                                console.log(releaseVal); // Release Object
                                story.Release = releaseVal;
                                story.save({
                                    callback: function(result, operation) {
                                        console.log("operation", operation);
                                        if(operation.wasSuccessful()) {
                                            console.log("operation", operation);
                                        }
                                        else{
                                            console.log("error");
                                        }
                                    }
                                });
                            });
                            deferred.resolve();
                        }
                    }
                }, this);
                return deferred;
            },

A: Where you're doing this:
story.Release = releaseVal;

Try this instead:
story.set('Release', releaseVal);


text:
Q: Is it possible make dump of mysql database with updated content in codeigniter I am going to write scripts to make backup of mysql database using codeigniter.
However, here is one tricky issue.
I should convert all email into dummy letters not real email information.
Ex, Jon@gmail.com => aBdsEDd@test.com
So, the new dev can use all data, but not real email because of they are for real person's information.
But I am not sure It is possible or not.
Here, I dropped my approach, but can not change current database.
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');

$dumpOption = array(
    'tables'        => array(),   // Array of tables to backup.
    'ignore'        => array(),                     // List of tables to omit from the backup
    'format'        => 'txt',                       // gzip, zip, txt
    'filename'      => 'mybackup.sql',              // File name - NEEDED ONLY WITH ZIP FILES
    'add_drop'      => TRUE,                        // Whether to add DROP TABLE statements to backup file
    'add_insert'    => TRUE,                        // Whether to add INSERT data to backup file
    'newline'       => "\n"                         // Newline character used in backup file
);

if(ENVIRONMENT !== 'production') {
    if ($this->dbutil->database_exists('db'))
    {
        $backup = $this->dbutil->backup($dumpOption);
        try {
            echo 'loading database .....';
            write_file('./mybackup.sql', $backup, 'w+');
            echo 'finish preparing dev data.';
        } catch(Exception $e) {
            printf('Message: ' .$e->getMessage());
        }
    } else {
        echo 'database does not exist.';
    }
}

Would you let me know If it is possible?
Most important thing is that the dump file should have updated content but we should not change original database, changes should be on dump only.
Is it possible?
Thank you very much.

A: Strictly speaking, then answer is no, you cannot change the contents of the data this way, since the backup method takes a list of tables and dumps those to a file as they are. Well, this is exactly what you would expect from a backup solution.
What you could do, however, is to create views that incorporate the replacement logic you require. Then you can use the backup method to back the views up, not the tables.
Otherwise, you need to write the logic either in plain queries or implement it in php code and create the dump files yourself.

A: Trying to change the data in-flight like this is going to be some blend of "inadvisable" and "impossible". What I do is first clone the DB to a staging location, and then run data scrub scripts for PII and other sensitive information. Then you can make that available to clone to dev environments.
However, for values like the email address that may be used in relations or otherwise be required to be unique you will want to take extra care, as we found out the hard way, when you change all the emails to example@example.com properly testing anything relating to that information becomes virtually impossible.
For something like this I would suggest deriving a dummy email from the real one, eg:
UPDATE users
SET email = CONCAT(
  SUBSTRING(MD5(email),1,16),
  '@',
  SUBSTRING(MD5(email),17,16),
  '.com'
);

Result:
foo@bar.com -> f3ada405ce890b6f@8204094deb12d8a8.com
bar@foo.com -> dc8a42aba3651b0b@1f088ef928ff3b1d.com

However, as your DB grows cloning like this becomes more and more of a problem, particularly for local development, as the DB size will likely only grow over time. As it stands our prod DB is approaching 300GB and some of our devs' machines cannot fit a copy in addition to all of their other requirements. Plus the cloning and scrubbing takes hours, and now with everyone remote it poses additional logistical problems to get those clones out to devs over already-constrained links.
The best solution, particularly for local dev, is to only dump the schema of the database and fill it with a representative set of mocked data for testing. For full-blown tests we maintain full-copy, scrubbed versions of the DB in our CI/CD pipeline environments.


text:
Q: re enable click for a disabled element in jquery I used elem.off() to prevent clicks while svg animation has been finished. I've menage to disable clicks, but somehow it won't reenable it.
here is the example of my code:

/*main jquery content*/

$('.hamburger a').click(function(event) {
  'use strict';
  event.preventDefault();
  $(this).off('click');
  $('.menubar').toggleClass('show');
  setTimeout(delayed, 300);
});

function delayed() {
  $('.hamburger a').on('click');
}
.home-header {
  background-color: #333;
  margin: 0;
  padding: 0 0.9375rem;
  position: absolute;
  width: 100%;
  box-sizing: border-box;
}
.hamburger {
  float: right;
  position: relative;
  width: 50px;
  z-index: 5010;
}
.hamburger a {
  display: block;
  height: 50px;
  padding: 0;
  width: 50px;
}
.menubar {
  -webkit-transition: opacity 250ms ease-out;
  transition: opacity 250ms ease-out;
  background-color: rgba(0, 37, 127, 0.95);
  bottom: 0;
  left: 0;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  right: 0;
  top: 0;
  visibility: hidden;
  z-index: 5000;
}
.menubar.show {
  opacity: 1;
  visibility: visible;
}

      <svg id="hamburger" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 50" enable-background="new 0 0 50 50" xml:space="preserve">
        <desc>Created with Snap</desc>
        <defs></defs>
        <g style="opacity: 1;">
          <path d="M13,13v24h24V13H13zM36,36H14V14h22V36z" fill="#ffffff"></path>
          <path d="M19,24H31V26H19z" fill="#ffffff"></path>
          <path d="M19,20H31V22H19z" fill="#ffffff"></path>
          <path d="M19,28H31V30H19z" fill="#ffffff"></path>
        </g>
        <g style="opacity: 0;">
          <path d="M19,24H31V26H19z" fill="#ffffff"></path>
          <path d="M19,24H31V26H19z" fill="#ffffff"></path>
        </g>
      </svg>

    Somecontent

Any ideas why enabling clicks with $('.hamburger a').on('click'); doesn't work?

A: You need to provide the function to execute on the click event again. Try this:
var hamburgerClick = function(e) {
    e.preventDefault();
    $(this).off('click');
    $('.menubar').toggleClass('show');
    setTimeout(delayed, 300);
}

$('.hamburger a').click(hamburgerClick);

function delayed() {
    $('.hamburger a').on('click', hamburgerClick);
}

A: create separate function to assign on click event

/*main jquery content*/

function hamburgerClick (event) {
  'use strict';
  event.preventDefault();
  $(this).off('click');
  $('.menubar').toggleClass('show');
  setTimeout(delayed, 300);
}

$('.hamburger a').on('click',hamburgerClick);

function delayed() {
  $('.hamburger a').on('click',hamburgerClick);
}
.home-header {
  background-color: #333;
  margin: 0;
  padding: 0 0.9375rem;
  position: absolute;
  width: 100%;
  box-sizing: border-box;
}
.hamburger {
  float: right;
  position: relative;
  width: 50px;
  z-index: 5010;
}
.hamburger a {
  display: block;
  height: 50px;
  padding: 0;
  width: 50px;
}
.menubar {
  -webkit-transition: opacity 250ms ease-out;
  transition: opacity 250ms ease-out;
  background-color: rgba(0, 37, 127, 0.95);
  bottom: 0;
  left: 0;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  right: 0;
  top: 0;
  visibility: hidden;
  z-index: 5000;
}
.menubar.show {
  opacity: 1;
  visibility: visible;
}

      <svg id="hamburger" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 50" enable-background="new 0 0 50 50" xml:space="preserve">
        <desc>Created with Snap</desc>
        <defs></defs>
        <g style="opacity: 1;">
          <path d="M13,13v24h24V13H13zM36,36H14V14h22V36z" fill="#ffffff"></path>
          <path d="M19,24H31V26H19z" fill="#ffffff"></path>
          <path d="M19,20H31V22H19z" fill="#ffffff"></path>
          <path d="M19,28H31V30H19z" fill="#ffffff"></path>
        </g>
        <g style="opacity: 0;">
          <path d="M19,24H31V26H19z" fill="#ffffff"></path>
          <path d="M19,24H31V26H19z" fill="#ffffff"></path>
        </g>
      </svg>

    Somecontent

A: You should instead toggle a class and delegate event to avoid any click event to be bound on this element.
So to bind it, use:
$('.hamburger').on('click', 'a:not(.disabled)', function(){...});

To avoid event to be fired, just add class instead of unbind event:
$('.hamburger').find('a').addClass('disabled');

And to renable it, just remove this class:
$('.hamburger').find('a').removeClass('disabled');


text:
Q: How to use directory operations in C++Builder? I am stuck in creating a directory with C++Builder. If you check this here and here, I find examples for my case, but when I try to use them, none of them work for me! For example, the following code for creating a directory, where the edSourcePath->Text value has been defined.
Unfortunately the documentation is not complete.
try
{
    /* Create directory to specified path */
    TDirectory::CreateDirectory(edSourcePath->Text);
}
catch (...)
{
    /* Catch the possible exceptions */
    MessageDlg("Incorrect path", mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

The error message says TDirectory is not a class or namespace.
Another question is, how can I pass the source path and directory name by CreateDirectory(edSourcePath->Text)?

A: What you are seeing is a compile-time error, not a runtime error.  The compiler cannot find the definition of the TDirectory class.  You need to #include the header file that TDirectory is defined in, eg:
#include <System.IOUtils.hpp> // <-- add this!

try
{
    /* Create directory to specified path */
    TDirectory::CreateDirectory(edSourcePath->Text);

    // or, if either DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE or
    // NO_USING_NAMESPACE_SYSTEM_IOUTILS is defined, you need
    // to use the fully qualified name instead:
    //
    // System::Ioutils::TDirectory::CreateDirectory(edSourcePath->Text);
}
catch (const Exception &e)
{
    /* Catch the possible exceptions */
    MessageDlg("Incorrect path.\n" + e.Message, mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

Note, however, that TDirectory::CreateDirectory() throws an exception ONLY if the input String is not a valid formatted path.  It DOES NOT throw an exception if the actual directory creation fails.  In fact, there is no way to detect that condition with TDirectory::CreateDirectory() itself, you would have to check with TDirectory::Exists() afterwards:
#include <System.IOUtils.hpp>

try
{
    /* Create directory to specified path */
    String path = edSourcePath->Text;
    TDirectory::CreateDirectory(path);
    if (!TDirectory::Exists(path))
        throw Exception("Error creating directory");
}
catch (const Exception &e)
{
    /* Catch the possible exceptions */
    MessageDlg(e.Message, mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

Otherwise, TDirectory::CreateDirectory() is just a validating wrapper for System::Sysutils::ForceDirectories(), which has a bool return value.  So, you could just call that function directly instead:
#include <System.SysUtils.hpp>

/* Create directory to specified path */
if (!ForceDirectories(edSourcePath->Text)) // or: System::Sysutils::ForceDirectories(...), if needed
{
    MessageDlg("Error creating directory", mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}


text:
Q: How can I send the request to the Managed Bean using javascript ? I have this Primefaces code,
<p:commandButton id="btnDisplay" styleClass="btn" value="Display Selected"
      update="messages" style="margin:20px 0 20px 0;"
      actionListener="#{jobsTree.displaySelectedMultiple}" />

I have to perform the same action using javascript instead of using h:commandbutton like
<input type="button" />

How can I send the request to the Managed Bean using javascript ?

A: As you are using primefaces you can use p:remoteCommand:
<p:remoteCommand name="displaySelected" update="messages"
                 actionListener="#{jobsTree.displaySelectedMultiple}"/>

To call it from JS just use:
displaySelected();


text:
Q: How to properly upscale a texture in opengl? Let's say, for the simplicity of this question, I want to create a texture containing a color gradient from black to red. I know there are much easier ways to achieve this but it is a good example for my problem.
I figured, i could simply create a texture from an float array like so:
float values[4] {
    0.f, 1.f,
    0.f, 1.f
}

// gen texture
unsigned int texId;
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);

// set filter and wrap
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

// copy values
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 2, 2, 0, GL_RED, GL_FLOAT, values);

And draw it:
float vertices[8] {
    -1.f, -1.f, 0.f, 0.f,
     1.f, -1.f, 1.f, 0.f,
     1.f,  1.f, 1.f, 1.f,
    -1.f,  1.f, 0.f, 1.f
}

// generate vertex buffer, vertex buffer layout and vertex array

unsigned int[6] indices {
    0, 1, 2,
    2, 3, 1
}

// generate index buffer

// bind everything

glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

Where the bound vertex shader looks like this:
#version 330 core

layout(location=0) in vec2 in_position;
layout(location=1) in vec2 in_texCoords;

out vec2 texCoords;

void main() {
    gl_Position = vec4(in_position, 0.f, 1.f);
    texCoords = in_texCoords;
}

And the fragment shader like this:
#version 330 core

layout(location = 0) out vec4 out_color;

in vec2 texCoords;

uniform sampler2D u_gradient;

void main() {
    float red = texture(u_gradient, texCoords).r;
    out_color = vec4(red, 0.f, 0.f, 1.f);
}

Following this I'd expect to get an color gradient from left to right (black to red) across my entire window.
However what I get is a gradient from about 1/4 to 3/4 of the window in x and y direction (See image below). I've also noted that the wrap of repeat does not seem to apply here as what I get looks like mirror-repeat.
Result:
I've played around with the fragment shader using fixed values instead of texCoords and figured that a range from .25 to .75 on the x axis represents the entire gradient (.25 maps to 0 for red and .75 to 1).
Changing the amount of 'steps' passed as values to the texture (eg. a 4x4 array) did not change the results.
I've also tried using an image as texture (loaded with stb_image, resolution 1920x1080) which works perfectly fine and spreads across the entire screen.
For clarification: Why do the texCoords for the gradient range from .25 to .75 and not from 0 to 1 and how can I fix it (besides adjusting the texCoords itself)?

A: Lets assume you have a 2x2 texture
2x2 Texture

If this texture is wrapped on a grid of 6x6 fragments, the the center of a texel is on exactly on the texel in the middel of 3x3 tile of the 6x6 square:
6x6 quad

The color of the other fragments depends on the the texture parameters - see glTexParameter.
Since the texture is magnified, the GL_TEXTURE_MAG_FILTER is significant.
If it is GL_NEAREST, then the color of the fragments is that one of the closest texel, to the texture coordinates of the fragment:

If it is GL_LINEAR, then the color is interpolated, by the weighted average of the 4 pixels which are closest to the texture coordinates.
The interpolation at the borders of the 6x6 quad depends on the wrap parameters GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T.
If the parameters are GL_REPEAT (which is default), the the texture is treated as an endless texture and the interpolation of the interpolation of the color at the borders takes into account the texels on the opposite side of the texture. This is used for seamless textures and tiling:

If it is GL_CLAMP_TO_EDGE, then the interpolated color at the borders is clamped to the color of the texels at the border of the texture:

Apply the texture wrap parameter GL_CLAMP_TO_EDGE to the texture object,
float values[4] { 0.f, 1.f, 0.f, 1.f };

unsigned int texId;
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);

// set filter and wrap
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

// copy values
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 2, 2, 0, GL_RED, GL_FLOAT, values);

to get the following gradient:


text:
Q: Inductive sets with chains of finite elements. An inductive set is said to be a partially ordered set P that satisfies the hypothesis of Zorn's lemma when nonempty (that is every chain in P has a least upper bound).
1)Now is it true that if a poset P satisfies the condition that every chain in P is finite , then P is inductive;
2)As a result every finite poset is inductive and the discrete poset is inductive  ;

A: If a partial order is finite, then every chain is finite, and therefore has a maximum, which is indeed the least upper bound of that chain.
As for the partial order given by the $=$ relation, indeed, it satisfies the hypothesis of Zorn's lemma, and indeed, every element is maximal.

A: The hypothesis of Zorn's lemma isn't that every chain should have a least upper bound, but rather that every chain has an upper bound.
Every finite non-empty chain has a maximum, which is an upper bound.


text:
Q: Select value is not inserting into database I have admins who insert entries into database, other values are properly inserting into database but select option value is not inserting. Firstly admin loged in and his session start after that he add new entries to database.
Please help.
My html form is
<form method="post" action="" enctype="multipart/form-data" role="form">

        Subject Material Title
        <input type="text" name="sub_title" placeholder="Subject Material Title" class="form-control" required>

        Download url link
        <input type="text" name="sub_url" placeholder="Download url link" class="form-control" required>

        File input
        <input type="file" name="sub_file" id="exampleInputFile" required>

Upload Image/File upto 2MB size only

        Writen By
        <select class="form-control" name="writen_by">
            <?php if(isset($_SESSION['admin_email'])){
                        echo '<option value='. $_SESSION['admin_username'] .'>'. $_SESSION['admin_username'] .'</option> ';
                  }
            ?>
        </select>

</form>

PHP code is
<?php

include("includes/config.php");
global $con;
    if(isset($_POST['add_submat'])){

        //getting the text data from the fields
        $sub_title = $_POST['sub_title'];
        $sub_url = $_POST['sub_url'];
        $writen_by = $_POST['writen_by'];

        //getting image from the fields
        $sub_file = $_FILES['sub_file']['name'];
        $sub_file_tmp = $_FILES['sub_file']['tmp_name'];

        move_uploaded_file($sub_file_tmp,"sub-material-files/$sub_file");

        //insert data into table
        $insert_submat = "insert into m_study_material (sm_title,sm_downloadurl,sm_image,created_by) values ('$sub_title','$sub_url','$sub_file','$writen_by')";

        echo $insert_submat;

        $run_submat = mysqli_query($con, $insert_submat);

        //error_reporting(E_ERROR);

        if($run_submat){
            echo "";
        } else{
            echo "Not inserted";
        }
    }
?>

A: You forgot to add quotes arround value, thats why values is being post properly.
  <?php
  if(isset($_SESSION['admin_email'])){
      echo '<option value="'. $_SESSION['admin_username'] .'">'. $_SESSION['admin_username'] .'</option> ';
  }
  ?>

A: First fix

    Writen By
    <select class="form-control" name="writen_by">
        <?php if(isset($_SESSION['admin_email'])): ?>
            <option>
                <?= $_SESSION['admin_username']; ?>
            </option>
        <?php endif; ?>
    </select>

Second you should consider cleaning user input before inserting because your code is currently widely open to Injection attack.
See more about SQL Injection in PHP
For example you could utilize helper function such as
function cleanInput($input)
{
    $search = array(
        '@@si',   // Strip out javascript
        '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
        '@@siU',    // Strip style tags properly
        '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
    );
    $output = preg_replace($search, '', $input);
    return $output;
}
function prepare($input)
{
    if (get_magic_quotes_gpc())
    {
        $input = stripslashes($input);
    }
    $input  = cleanInput($input);
    return mysql_real_escape_string($input);
}

This way you could do this before any sql query
$sub_title = prepare($_POST['sub_title']);
$sub_url = prepare($_POST['sub_url']);
$writen_by = prepare($_POST['writen_by']);


text:
Q: Tailwind safelist patterns for multiple patterns? I'm trying to use safelist patterns (formerly whitelist patterns) with Tailwind CSS V3.1.6 and have the following. It's not working, but essentially I'm trying to safelist all values beginning with bg-, text- and border-
safelist: [
  // Retain all classes starting with...,
  {
    pattern: /bg-/,
    pattern: /text-/,
    pattern: /border-/,
  },
],

A: You can safelist multiple entrances within an array of objects like
safelist: [
  {pattern: /bg-./},
  {pattern: /text-./},
  {pattern: /border-./},
]

but in your case it would be shorter to use pipe sign "|"
safelist: [
  {pattern: /(bg|text|border)-./}
]

More about safelisting with regular expressions can be found here


text:
Q: Why image of an item of listview becomes small when I add a new item? I am retrieving data from firebase in a listview. When there is one item, image size remains good but it becomes small when I add another item.
I am using wrap_content for hight and width in ImageView. Some item might not have images in it that's why I can't set the height and width manually.
Here is my list layout:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
tools:context=".UserPostHistoryActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/lesswhite"
        android:padding="10dp"
        android:id="@+id/posthistorylayer">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listuserposthistory"
            android:divider="@color/lesswhite"
            android:dividerHeight="10.0sp"/>

    </LinearLayout>

This is the item layout to display in Listview:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:id="@+id/postdamo"
    android:background="@color/white">

    <TextView
        android:id="@+id/postnametv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="5dp"
        android:text="Username"
        android:textSize="18sp"
        android:textStyle="bold"
        tools:ignore="RtlCompat" />

    <TextView
        android:id="@+id/postdatetv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/postnametv"
        android:layout_below="@+id/postnametv"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="24-Jan-2019"
        android:textSize="14sp"
        tools:ignore="RtlCompat" />

    <TextView
        android:id="@+id/poststatustv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/postnametv"
        android:layout_below="@+id/postdatetv"
        android:layout_marginTop="0dp"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="Not Collected"
        android:textSize="18sp"
        android:textStyle="bold"
        tools:ignore="RtlCompat" />

    <ImageView
        android:id="@+id/postimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/poststatustv"
        android:layout_centerHorizontal="true"
        android:padding="5dp"
        android:maxHeight="250dp"
        tools:ignore="RtlCompat" />

    <TextView
        android:id="@+id/detailtxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/postimage"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="Details:"
        android:textSize="16sp"
        android:textStyle="bold"
        tools:ignore="RtlCompat" />

Any help is much appreciated.

A: You can try LinearLayout as parent with wrap_content height and width and give some specific values for child views in the parent layout to make better layout, if there is no image for particular data then you can use default images for that to make layout better and uniform.


text:
Q: Widget launches Dialog on click Is it possible to launch a dialog on widget click or do I have to launch a Activity on widget click then a dialog?

A: I am sure you have already solved that, but I'll write here anyway, in case other like me land on this answer.
To launch a Dialog by clicking a Widget you can define an activity that is styled like a dialog and launch it when the widget gets clicked.
First of all add the activity in the manifest, let's call it DialogWidgetActivity
<activity
    android:name=".DialogWidgetActivity"
    android:theme="@android:style/Theme.Dialog"
    ...
/>

Then in your WidgetProvider, let's call it MyWidgetProvider bind the click of the widget with the launch of the activity
public class MyWidgetProvider extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {

    final int N = appWidgetIds.length;

    // Perform this loop procedure for each App Widget that belongs to this
    // provider
    for (int i = 0; i < N; i++) {
        int appWidgetId = appWidgetIds[i];

        // Create an Intent to launch the activity-dialog
        Intent intent = new Intent(context, DialogWidgetActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        // Get the layout for the App Widget and attach an on-click listener
        // to it
        RemoteViews views = new RemoteViews(context.getPackageName(),
                R.layout.widget);
        views.setOnClickPendingIntent(R.id.widget_container, pendingIntent);

        // Tell the AppWidgetManager to perform an update on the current app
        // widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

}
}

Note that here we have bind the launch of the activity to the click on the widget_container element of the dialog. You can easily achieve this by assigning the id widget_container, android:id="@+id/widget_container", to the root element of the widget layout.
You can then write your activity-dialog and its layout like you would do for a normal full screen activity.
My sources were this answer and the Android documentation.
Hope I helped :)

A: You can launch AlertDialogon click of a widget.
Update:
Add the following code for onclick listener.
    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setMessage("Message");
    dialog.show();


text:
Q: putExtra data not passing between activities I have a query. I am designing a widget. I have 2 apps in it. I am able to pass intents to one of the apps. But i am facing problem when i try to click FB, intents doesn't work. I get error in passing the data from 1 activity to an other. Data not getting passed from 1 activity to another.
Code class first:
Intent i = getIntent();
String show = i.getStringExtra("show");
if(show.equals("facebook"))
{
 viewFlipper.setDisplayedChild(0);
 mListView.setAdapter(mFacebookAdapter);
 currentView = 0;
}
else if(show.equals("twitter"))
{
viewFlipper.setDisplayedChild(1);
mListView.setAdapter(mTwitterAdapter);
currentView = 1 ;
}

Class second:
Intent facebook = new Intent(context, SocialList.class);
facebook.putExtra("show", "facebook");
PendingIntent pendingfb = PendingIntent.getActivity(context, 0, facebook, 0);

I need to pass the value from one class to another. In second class i need to get the show value as "facebook" from class first. How can i do that. Please guide me.
Thanks in advance.

A: The code i am using.
Inserting Data:
    Intent intent = new Intent(this, ProfileActivity.class);
    intent.putExtra("profileId", userId);
    startActivity(intent);

Retrieving Data:
    profileId = getIntent().getExtras().getString("profileId");


text:
Q: Enabling access to MySQL database using Perfect - MySQL Connector I'm going to create web application using Swift. I have a problem with connection with MySQL. I use PhpMyAdmin for MySQL databases management. It seems to me that the best way is to use Perfect. I have done everything in accordance with Perfect - MySQL Connector! Unfortunately, I have a problem with calling function useMysql in main.swift. I wonder whether it is written correctly. I invoke function useMysql in file main.swift:
//This route will be used to fetch data from the mysql database
routes.add(method: .get, uri: "/use", handler: useMysql)

However in file mysql_quickstart.swift we define function with two arguments:
public func useMysql(_ request: HTTPRequest, response: HTTPResponse)
{
//function body
}

I am not sure but maybe I should call it in this way? -
routes.add(method: .get, uri: "/use", handler: useMysql(request: object of HTTPRequest, response: object of HTTPResponse))

I don't have any errors however function useMysql seems to be never executed. I am aware of fact that it isn't a good habit to attach code from files of project but maybe it will be useful.
Here is my code Any suggestions? Thanks in advance.
I have also found other Perfect - MySQL Connector tutorial and I'm not sure which way is better? By the by I wonder if it is a good idea to use more than one framework in one project? For instance both Perfect and Kitura or Vapor, too?
EDITED:
What do you think to use it in this way?
// Register your own routes and handlers
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
        request, response in
        response.setHeader(.contentType, value: "text/html")
        response.appendBody(string: "<title>Hello, world!</title>Hello, world!")
        //This route will be used to fetch data from the mysql database
        useMysql(request, response: response)
        response.completed()
    }
)

A: Two things, swap out the useMysql function with a simple print result and return HTML function.
Second, I suggest looking at (or using) the MySQL StORM abstraction layer.
https://github.com/SwiftORM/MySQL-StORM
It's quite possible it's permissions, host access or port.

A: Main.Swift:-
routes.add(method: .post, uri: "/admin/api/v1/login") { (request, response) in

let email = request.param(name: "email")
let password = request.param(name: "passwrod")
let JSON = Login.checkLogin(email: email, password: password)
do {
    try response.setBody(json: JSON)
        .completed()
} catch {
 }
}

Login.Swift
import Foundation
import PerfectMySQL
import PerfectLib

class Login: NSObject {

 class func checkLogin(email: String?, password: String?)-> JSONConvertible {

 var JSON: JSONConvertible?

 if !ServerHelper.isValidEmail(candidate: email) {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_INVALID_EMAIL_ADDRESS)
 return JSON

 } else if !ServerHelper.isValidPassword(password: password!) {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_INVALID_PASSWORD)
 return JSON

 } else {

 let mySql = MySQL()
 let connect =  mySql.connect(host: "127.0.0.1", user: "root", password: "mypassword", db:"SuperAdmin" , port: 3306, socket: "", flag: 0)
 if !connect {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_SERVER_ERROR)
 return JSON
 }

 let query = "select email, phone_number from SuperAdmin.Login where email='\(String(describing: email!))' AND password='\(String(describing: password!))'"

 if mySql.query(statement: query) {

 let result = mySql.storeResults

 var jsonResult = [Dictionary<String, Any>]()

 result()?.forEachRow(callback: { (element) in

 var dict = Dictionary<String, Any>()

 if let arrRow = element as? [String] {

 let email = arrRow[0]
 let phone_number = arrRow[1]
 dict["email"] = email
 dict["phone_number"] = phone_number
 jsonResult.append(dict)
 }
 })

 if jsonResult.count == 0 {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_NOT_AUTHORIZE)

 } else {

 JSON = ServerHelper.getJson(result: jsonResult)

 }

 } else {

 JSON =  ServerHelper.getErrorJson(message: KMESSAGE_NOT_AUTHORIZE)
 return JSON
 }
 mySql.close()
 }
 return JSON
 }

}

Hit POST API like
localhost:8080/admin/api/v1/login
and I got the response:
{
"status": 200,
"succcess": true,
"result": [
    {
        "phone_number": "84747474574",
        "email": "myemail@swift.com"
    }
]

}

Please make sure your are passing correct values to connect with database
let connect =  mySql.connect(host: "127.0.0.1", user: "root", password: "mypassword", db:"SuperAdmin" , port: 3306, socket: "", flag: 0)


text:
Q: How to generate IDbSet instead of DbSet I'm new to C# and  EntityFramework and I need to maintain an active software.
I needed to create a new table so I created it in the database and then updated my Model with EntityFramework.
Howewer, it looks like the previous developer had been writing code directly in generated code (The Mode.Context.cs class) and EntityFramework when updating the model is wiping it and rewritting it completly.
So I did a new partial class Model. It looks like this :
public partial class Model : DbContext, IModel
    {
        public void SomeRandomMethod();
    }

And the generated Model looks like this :
public partial class Model : DbContext
{
    public Model()
        : base("name=Model")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public DbSet<RandomTable> ARandomTable { get; set; }
}

The problem, however, is that previously, the model was using IDbSet instead of DbSet and the interface IModel is asking for IDbSet<RandomTable> ARandomTable
What would be the proper way to deal with that ?

A: Normally the Dbcontext that represents your database has several DbSet<TEntity> properties, where every DbSet represents a table in your database.
All non-virtual properties of TEntity represent the columns in your table; the virtual properties of TEntity represent the relations between tables: one-to-many, many-to-many etc.
Every DbSet<TEntity> implements IDbSet<TEntity> so wherever your old DbContext used an IDbSet, you can give it the corresponding DbSet instead.
If I understand you correctly, your old DbContext had some properties that implemented IDbSet<...>, and method SomeRandomMethod used these properties.
class MyOldDbContext : DbContext
{
     public IDbSet<Aentity> Aentities {get; set;}
     public IDbSet<Bentity> BEntities {get; set;}

     public void SomeRandomMethod()
     {   // this method uses the IdBsets AEntities and BEntities:
         IDbSet<AEntity> x = this.AEntities;
         IDbSet<BEntity> y = this.BEntities;
         ... // do something with x and y
     }
}

Now your new DbContext. If the DbSets have the same Entity types as the old ones, there is no problem:
class MyNewDbContext : DbContext
{
     public DbSet<Aentity> Aentities {get; set;}
     public DbSet<Bentity> BEntities {get; set;}

     public void SomeRandomMethod()
     {   // this method uses the DbSets AEntities and BEntities, which implement IDbSet
         IDbSet<AEntity> x = this.AEntities;
         IDbSet<BEntity> y = this.BEntities;
         ... // do something with x and y
     }
}

Note that AEntities/BEntities are now DbSet<...> instead of IDbSet<...>. Because every DbSet<...> implements IDbSet<...>, your problem is solved.
It is a bit more difficult if your new tables are different than your old ones. In that case you'll have to write adapter properties, that return the expected IDbSet<...>
class MyNewDbContext : DbContext
{
     public DbSet<Teacher> Teachers {get; set;}
     public DbSet<Student> Students {get; set;}

     public void SomeRandomMethod()
     {   // this method uses the IdBset of AEntities and BEntities:
         IDbSet<AEntity> x = this.AEntities;
         IDbSet<BEntity> y = this.BEntities;
         ... // do something with x and y
     }

     // for SomeRandomMethod we need properties AEntities and BEntities
     // use your new DbSets to mimic the old AEntities and BEntities
     private IDbSet<AEntity> AEntities => this.Teachers
          .Join(this.Students, ...)
          .Where(...)
          .Select(...);
      // similar for BEntities
}


text:
Q: Convert DbContext way to SqlCommand way Today I have an App which work using EF Core, with the DbContext class and looks like this:
    public class RcoreContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=rCoreData.TestDb;Trusted_Connection=True;");
        }

        public DbSet<Hosts> Hosts { get; set; }
        public DbSet<Route> Route { get; set; }
    }

    public class Hosts
    {
        public int      HostsId  { get; set; }
        public string   Host     { get; set; }

        [NotMapped]
        public Dictionary<object, object> Datas { get; set; }

        public string   DatasJson { get { return JsonConvert.SerializeObject(Datas); } set { Datas = JsonConvert.DeserializeObject<Dictionary<object, object>>(value); } }
    }

    public class Route
    {
        public int                          RouteId     { get; set; }
        public int                          HostId      { get; set; }
        public string                       RealRoute   { get; set; }
        public string                       alias       { get; set; }
    }

I very like this way because the requests returns are based on existing classes (Hosts and Route in this code).
The SqlCommand way seems more comfortable to use (it seems to be more PHP-like) but seems to return the entries as object. (I read this article)
I would like to know if is it possible to make a mix between the 2 ways and to send a request as a StoredProcedure like SqlCommand do BUT still be based on existing classes for the request return.
Thanks

A: if you want to use ADO.NET in EF, you just need to get the current connection string and create the sqlcommand as below:
using (var context = new RcoreContext())
{
   // creates a Command
   var command = context.Database.Connection.CreateCommand();
   command.CommandType = commandType;
   command.CommandText = sql;

   using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.WriteLine(reader.GetValue(i));
        }
        Console.WriteLine();
        }
    }
}

and if you just want to execute sql or stored procedure, you can also use below in EF
 _dbContext.Database.ExecuteSqlCommand(sql, parameters);
_dbContext.Database.SqlQuery<TEntity>(sql, parameters);

A:     using (var connection = context.Database.GetDbConnection())
    using (var command = context.Database.GetDbConnection().CreateCommand())
    {
       command.CommandText = string.Format(sqlQuery, id);
       connection.Open();
       using (var reader = command.ExecuteReader()){}
    }

A: using (var connection = new SqlConnection(_dbContext.Database.Connection.ConnectionString))
using (var cmd = new SqlCommand())
{
      cmd.Connection = connection;
      cmd.CommandText = "your query here";
      cmd.CommandType = CommandType.Text;

      cmd.Parameters.Add("@param1", SqlDbType.Int);

      cmd.Connection.Open();
      cmd.ExecuteNonQuery();
}


text:
Q: Issue in self join : Laravel Database Table Schema
if (!Schema::hasTable('tblrole')) {
    Schema::create('tblrole', function (Blueprint $table) {
        $table->unsignedInteger('RoleID')->autoIncrement();
        $table->unsignedInteger('ParentRoleID')->nullable();
        $table->string('Role', 25)->unique();

        $table->boolean("IsActive")->default(0);

        $table->foreign('ParentRoleID')->references('RoleID')->on('tblrole');

    });
}

Eloquent Model
class RoleModel extends Model
{
    public $table = 'tblrole';
    public $primaryKey = 'RoleID';
    public $timestamps = false;

    protected $casts = [
        'IsActive'  =>  'boolean'
    ];

    public function ParentRole() {
        return $this->hasOne("App\Models\User\Role\RoleModel", "RoleID", "ParentRoleID");
    }
}

Query not working
$Roles = RoleModel
    ::select("RoleID", "Role", "IsActive")
    ->with(["ParentRole" => function($query) {
        $query->select("RoleID", 'Role', "IsActive");
    }])
    ->get();

Working Query
$Roles = RoleModel->with("ParentRole")->get();

Problem
In the above not working query, ParentRole is always null.
Am I missing anything?

A: Since you explicitly exclude the ParentRoleID from the query, eloquent doesn't know its value and can't make the connection to the parent role. Try adding ParentRoleID to your select() or remove the select() altogether.
$Roles = RoleModel
::select("RoleID", "Role", "IsActive", "ParentRoleID")
->with(["ParentRole" => function($query) {
    $query->select("RoleID", 'Role', "IsActive");
}])
->get();


text:
Q: XNA keyboard input I've got a small bug with registering the keyboard input.
       case GameState.InGame:
                {
                    **if (PlayerInput.IsKeyUp(Keys.P)&& oldInput.IsKeyDown(Keys.P))**
                         this.gameState = GameState.Paused;

                }
                   break;
            case GameState.Paused:
                {
                    **if (PlayerInput.IsKeyDown(Keys.P) && oldInput.IsKeyUp(Keys.P))**
                          this.gameState = GameState.InGame;
                }
                break;

What's happening is that it enters the pause game state just fine. But when trying to go from the pause state to InGame state is as soon as the 'P' key is up it goes back to paused state.

A: In the first case you're testing for a key transition from UP to DOWN and in the second case from DOWN to UP. Use the same method for both cases.

A: Just toggle the game state when the button gets pressed.
if (PlayerInput.IsKeyDown(Keys.P) && oldInput.IsKeyUp(Keys.P))
{
  switch (this.gameState)
  {
    case GameState.Paused:
      this.gameState = GameState.InGame;
      break;
    case GameState.InGame:
      this.gameState = GameState.Paused;
      break;
  }
}

Or, if you prefer:
if (PlayerInput.IsKeyDown(Keys.P) && oldInput.IsKeyUp(Keys.P))
{
  this.gameState = this.gameState == GameState.Paused ? GameState.InGame : GameState.Paused;
}


text:
Q: Переменную input в value чекбокса Господа помогите пожалуйста. Мне нужно, чтобы value чекбокса содержало value инпута. Как это можно воплотить в жизнь. Через форму не получилось, пытался сделать переменную инпута равной переменной чекбокса и тоже ничего не вышло.
Как то вот так пытался: $order = $amount1; где order это чекбокс, а amount1 это инпут.

                <input  type="checkbox" class="form" name="order">

              <input type="text" class="form-control" name="amount1">

Так же пытался вводить в value(чекбокса) пхп код содержащий переменную инпута(тоесть с name инпута) и всё равно ничего, уже все перепробовал и никак.
Опишу даже суть идеи, чтобы было прям вот понятно, что я хочу сделать. Вообщем есть сайт-магазин с мелким оптом. Товар 1 вида но разных цветов поэтому делать корзину ну я считаю незачем. На нем вообщем фотки с цветами и подписан id цвета и внизу есть чекбокс и инпут, в котором по задумке клиент должен вводить количество товара. Далее когда клиент выставит чекбоксы на нужных товарах, а так же выставит количество он доходит до формы оформления и всё это отправляется в базу sql.

A: используйте в названиях элементов формы код товара:

                <input  type="checkbox" class="form" name="order[10]">

              <input type="text" class="form-control" name="amount[10]" >

и при обработки вы будете иметь 2 массива order и amount. если order[10] отмечен, тогда берете количество из значения amount[10]


text:
Q: Can you deploy a Gen2 cloud function from below the top level of a Cloud Source repository? It appears that you cannot deploy a Gen2 cloud function using gcloud from a cloud source repo unless it is at the top level.
Here's a sample redacted deploy command for a gen 1 python function that works:
gcloud beta functions deploy funcname --source https://source.developers.google.com/projects/projectname/repos/reponame/moveable-aliases/main/paths/pathname --runtime python310 --trigger-http --project=projectname
if you add the -gen2 flag, it fails because it can't find main.py. Error is:

OperationError: code=3, message=Build failed with status: FAILURE and message: missing main.py and GOOGLE_FUNCTION_SOURCE not specified. Either create the function in main.py or specify GOOGLE_FUNCTION_SOURCE to point to the file that contains the function.

If you add main.py to the root of the repo and run the same command, it finds main.py, which indicates to me that it isn't honoring the paths.
There is an additional problem which doesn't matter unless the first one is fixed, which is that if pathname is below the top level (folder/subfolder) gcloud sees that as a syntax error when the gen2 flag is set, but not without it.
Is there any way around this? It is very inconvenient.

A: Answering as community wiki.As per above comments
There is a  bug raised for this at issue tracker. Which is still open further progress can be tracked there.


text:
Q: Postgresql error: could not open segment 1 of relation base/20983/2416 I'm running a Postgresql query and getting the following error:
ActiveRecord::StatementInvalid (PGError: ERROR:  could not open segment 1 of relation base/20983/24161 (target block 5046584): No such file or directory
The query is of the format 'SELECT "locations".* FROM "locations" WHERE ("locations"."id" IN (115990, 78330, 77891, 78248, ...)' with about 600 ids in the IN clause - not an optimal query I know but it's what I have to work with for the moment!
The server is running PostgreSQL 8.4.6 on x86_64-pc-linux-gnu, compiled by GCC gcc-4.4.real (Ubuntu 4.4.1-4ubuntu9) 4.4.1, 64-bit. Postgis 1.5 is also installed, and the locations table contains a geometry column.
Anyone have any idea what could be causing the error? Thanks!

A: That error indicates serious database corruption, one of the database's files containing the table data (of something in the system catalogue?) is missing. I doubt you'll be able to do much beyond restoring the data from a backup.


text:
Q: ¿Como cambiar texto con formato a texto plano en PHP? Estoy trabajando en un proyecto de filtrado de datos, y se me presento una cuestión si podrían darme alguna guía.
Tengo datos en almacenados en postgres los cuales extraigo a través de una consulta pero entre ellos una columna la cual tiene texto en cursivas y negritas las cuales necesito cambiar a un solo formato.
A continuación se muestra:

Acá el fragmento de código para la consulta
$cbba = pg_query($conexion, "SELECT id, name, longitud, latitud, observaciones FROM cbba where id = 21");

while ($row1 = pg_fetch_row($cbba)){

echo $row1[0]." : ".$row1[4];
echo "
";

Aca el valor de $row1[4], el cual se encuentra dentro de
Casa en Venta en Cochabamba,
     -  6
ó Una de las mejores y mas tranquilas zonas residenciales de
Quillacollo, Villa Moderna, a pocos minutos del Cine Center y de la
Av. Blanco Galindo y a solo 3 cuadras del nuevo prado de Villa Moderna.
 ó Hermosa casa de estilo minimalista a estrenar.
La misma cuenta con amplio jardín y 6 habitaciones, acabados y
materiales de primera calidad, excelente iluminación natural e
iluminación LED, entre otros detalles, que les brindaran a ti y
a tu familia la comodidad y el estilo de vida que se merece.
  Espacioso living comedor / escritorio / cocina con
cajonería completa y espacio para comedor de diario / baño de visitas.
 1 Suite con vestidor y baño privado con jacuzzi /
3 dormitorios con roperos empotrados / baño compartido  2 :
2 dormitorios / baño compartido / amplia terraza
 Churrasquero techado/ lavandería / baño de servicio /
amplio jardín / garaje para 3 movilidades con puerta automatizada
 á Agua, Luz, Alcantarillado y Gas
!     ,    !

También utilice strip_tags para eliminar las etiquetas (gracias por la ayuda con la función) pero tampoco pudo eliminar:
$cbba = pg_query($conexion, "SELECT id, name, longitud, latitud, observaciones FROM cbba where id = 21");

while ($row1 = pg_fetch_row($cbba)){
$mostrar = strip_tags($row1[4]);
echo $row1[4];
echo "
";
echo "
";
echo $mostrar;
}

Utilizando strip_tags obtuve esta respuesta:
En 1ra respuesta esta la consulta,
En la 2da esta utilizando strip_tags

Agradecería mucho alguna guía de como se podría lograr cambiar el tipo de formato (quitar las cursivas y las negritas) y guardarlo en otra variable.
De todas formas seguiré investigando, gracias.

A: Lo que necesitas hacer se denomina transliteración

Las transliteraciones, en el sentido estricto, se utilizan para reflejar la forma exacta en que una determinada palabra se representa en la lengua original

Para llevar a cabo esto, podemos utilizar la función iconv

Convierte un string a la codificación de caracteres indicada
[...]
Si se añade el string //TRANSLIT a out_charset, se activa la transliteración. Esto significa que cuando un caracter no puede ser representado en el set de caracteres final, se puede aproximar a uno o varios caracteres parecidos.

Entonces, suponiendo que la cadena esta en UTF8, podemos hacer la transliteración a ASCII para obtener una cadena convertida a un sistema de caracteres mas básico.
Ejemplo:
<?php

$text = '!     ,    !';
echo iconv('UTF-8', 'ASCII//TRANSLIT', $text);
// Resultado: !Esta es la casa que buscas, agenda una visita ya!

A: Podrias eliminar los tags usando una expresion regular de esta forma:
$re = '/<[^>]*>/';
$str = 'String de ejemplo con tags HTML';
$subst = '';
$result = preg_replace($re, $subst, $str);
echo $result;

El resultado seria String de ejemplo con tags HTML


text:
Q: getClass.getResource return null when i run this line:
URL myurl = getClass().getResource("/bla.xml");

I got myurl is null
if I try to debug in runtime this value "getClass().getResource("/bla.xml")"
I got the right value.
it seems that something went wrong with placement.
what it can be?
using eclipse oxygen

A: If maven directory structure is used you can put the XML file in the resources folder. If resources folder is not available in the maven directory structure , you can create a one.
The path of the resources folder are src/main/resources and src/test/resources. The XML file needs to be in the classpath. If you are running the jar, the XML file needs to be embedded in the jar file.


text:
Q: Why does installing DBD::Pg fail in DynaLoader? Error:  Can't load '/home/oracle/.cpan/build/DBD-Pg-2.16.1/blib/arch/auto/DBD/Pg/Pg.so' for module DBD::Pg: libpq.so.5: cannot open shared object file: No such file or directory at /usr/lib/perl5/5.8.8/i386-linux-thread-multi/DynaLoader.pm line 230.

Did anyone have similar error while instaling DBD::Pg perl module ? what can I do to fix it ?

A: You should go under perl to solve these dynamic linking problems. Use strace program &> out, and then grep for libpq.so.5. My guess is your libpq.so.5 is in the wrong location, or your DynaLoader is misconfigured. Read the docs on @dl_library_path.
You can see what your search path is with this (the strace will also show it trying to find the .so by checking each directory):
perl -MDynaLoader -le'print for @DynaLoader::dl_library_path;'

Make sure your libpq.5.so falls in one of those. The strace will also show if the kernel is returning an error to DynaLoader that it is cloaking; moreover, it will certainly tell you everything DynaLoader knows.

A: The libpq.so.5 file is missing, which indicates that you do not have the Postgresql client library installed.  On Ubuntu this file is provided by the libpq5 package.

A: Make sure the path to the PostgreSQL library is in either ld.so.conf or in a file in ld.so.conf.d and re-run "sudo ldconf" (or sudo /sbin/ldconf).  That's taken care of this issue when I've encountered it in the past.

A: I know lots of people have answered your question but I thought I'd add one more thing. Makefile.PL locates the postgres libraries by executing pg_config. If this can't be found on your path, then you will find this sort of error. Interestingly though, it looks for the headers in the same way. Try running pg_config from your terminal and see what the output is. If it's not found in your path, locate it, add to your path and try to build DBD::Pg again