text:
Q: Filter array matching all object keys. Get new array with unique objects I would like to get 2 new arrays based on an existing array containing objects. (keys stay the same for each object)
newArray1 objects should be unique in terms of their value. In other words:
[
   {Layer:"Layer",LayerName:"foo",LayerWidth:200,LayerHeight:400},
   {Layer:"Layer",LayerName:"FOOBAR",LayerWidth:200,LayerHeight:400},
   {Layer:"Layer",LayerName:"foo",LayerWidth:200,LayerHeight:400}
]

*

*newArray1 should consist of 1st and 2nd object, because 3rd has the same object-values like the 1st object.

*newArray2 should contain all other objects, that are not in newArray1, (3rd object only)

arr = []

for(var i=0;i<allSymbols.length;i++){
    var obj={
      Layer: allSymbols(i),
      LayerName: allSymbols(i).name(),
      LayerWidth: allSymbols(i).width(),
      LayerHeight: allSymbols(i).height()
    }
    arr.push(obj)
}

// filter so far...
for(var u=0;u<arr.length;u++){
    var filter = arr[u];
    arr = arr.filter(function(item){
     for(var key in filter){
       if(item[key] == filter[key]){
        return true
       }
     }
       return false
    });
}

// output newArray1(arr)?
// output newArray2?

A: You can try something like this:
Logic

*

*Get filtered list for every object.

*Get index of first matching object.

*If length of filtered list is one, object is unique and should be pushed to unique list.

*If not and if index is equal to current index, this is the first occurrence and again should be pushed to unique list.

*For all remaining objects, they are duplicates and are second or nth repetition and should be pushed to duplicate list

var d = [{Layer:"Layer",LayerName:"foo",LayerWidth:200,LayerHeight:400},{Layer:"Layer",LayerName:"FOOBAR",LayerWidth:200,LayerHeight:400},{Layer:"Layer",LayerName:"foo",LayerWidth:200,LayerHeight:400}]

var dupes = [];
var unique = [];

d.forEach(function(c,i,a){
  var objStr = JSON.stringify(c);

  var index = a.findIndex(function(o){
    return JSON.stringify(o) === objStr;
  });

  var _filter = a.filter(function(o){
    return JSON.stringify(o) === objStr;
  });
  if(_filter.length === 1 || index === i){
    unique.push(c)
  }
  else{
    dupes.push(c);
  }
}, []);

console.log(dupes, unique)

A: You could check for duplicate objects and filter the given data.

var data = [{ Layer: "Layer", LayerName: "foo", LayerWidth: 200, LayerHeight: 400 }, { Layer: "Layer", LayerName: "FOOBAR", LayerWidth: 200, LayerHeight: 400 }, { Layer: "Layer", LayerName: "foo", LayerWidth: 200, LayerHeight: 400 }],
    array1 = [],
    array2 = data.filter(function (a) {
        return array1.some(function (b) {
            return Object.keys(a).length === Object.keys(b).length && Object.keys(a).every(function (k) {
                return a[k] === b[k];
            });
        }) || array1.push(a) && false;
    });

console.log(array1);
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Redefining types in Rust and calling functions on them In Go you can do something like this to define a custom type that shadows an existing one:
type Header map[string][]string

Then you can access a Header type the same way you do a map[string][]string.
I tried doing the same with Rust but I'm running into issues:
pub type Header = collections::HashMap<String, Vec<String>>;
fn main() {
    let h = Header::new();
}

You can call HashMap::new(), as the docs indicate (accessed December 8, 2014). Why can't I call Header::new()?

A: A type alias is purely an alias for the type. It doesn't alias the namespace at all, so you will still need to write HashMap::new().

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Yet while the lowering of the wealth prerequisite provided an easy target for modern liberals..." In the following passage, in which sense was the phrase easy target used ?
1.Lowering of the wealth prerequisite was an easy job to succeed.
2.Lowering of the wealth prerequisite issue could be used for manipulating the political scene and igniting protest .Because it was obvious injustice in the country.

The extension of the voting franchise that began in England in 1832
  with the Great Reform Bill initiated, albeit slowly, a process of
  liberalization unseen in the history of the British Parliament.
  Previously, power rested in the hands of the few aristocrats with
  enough property and wealth to pass a relatively high property
  requirement for voting and holding office.
Yet while the lowering of the wealth prerequisite provided an easy
  target for modern liberals when arguing for the democratization of
  Parliament, this democratization at first did not extend to the
  working class.
Most representatives in the Commons came through Eton to either
  Cambridge or Oxford where, under the tutelage of the same professors,
  these future leaders developed a similar outlook on the world: the
  superiority of the British system, the rightness of imperialism, the
  power of industry, the benefits of trade, and the value of general
  isolation from the Continent. These views, though subject to some
  slight degree differences between Liberals and Conservatives, remained
  common through most of the House. Such views did not square with the
  new concerns of the workers who had neither received an elite
  education, nor, in some cases, an education at all.

A: If you are asking whether it means that the task was easy, or merely was the starting point for a broader campaign: both.
It means that of the possible approaches to the democratization of parliament, this was (somehow) an easy one for these "modern liberals" to achieve. The passage implies that the goal of these folk was democratization (somewhat anachronistically, in my opinion, but that's by-the-by) and this was a good place to start because it was easier than other changes.

A: It would be 2. The biggest indicator here is the use of the word obvious. When something is obvious it requires little effort to notice- it's easy or in this case, an easy target.


text:
Q: Remove white space between plots and table in grid.arrange I would like to remove the large spacing that is inserted by default between the plots and the table in a grid.arrange, as shown in the MWE hereafter:
require(ggplot2)
require(gridExtra)

list1=data.frame(mtcars[1:3, ])  # Dummy data
p1 = ggplot(list1, aes(mpg,cyl)) + geom_point()  # Dummy plot
p2 = ggplot(list1, aes(disp,hp)) + geom_point()  # Dummy plot
plots <- arrangeGrob(p1, p2,nrow=2)

table <- tableGrob(list1)
grid.arrange(plots, table)

I suspect this behaviour is due to the tableGrob, but I couldn't find any answer treating this issue.
Thanks in advance!

A: grid.arrange() by default allocates equal space for each cell. If you want a tight fit around a specific grob, you should query its size, and pass it explicitly,
library(grid)
th <- sum(table$heights) # note: grobHeights.gtable is inaccurate
grid.arrange(plots, table, heights = unit.c(unit(1, "null"), th))

A: I actually found the parameter ruling the spacing between grobs: heights, see line below
grid.arrange(plots, table, heights=c(5,1))


text:
Q: iPod Nano 6G stops playing when display turns off My iPod Nano 6G stops playing music when the display turns off either by time, or by pressing the "Sleep/Wake"-button.
This effect is fully reproducible but only appears with certain headphones, namely:
Sennheiser CX 1.00
JBL Synchros S100i
With several other headphones, the iPod keeps playing music when the display turns off.
Any advice how to get those headphones working with the iPod?

A: Most of the approaches to this error concern problems with the headphone jack and plug, so it was in this case.
Simply cleaning of the jack with compressed air didn't solve the problem. I had to scratch the inside (the part, the tip of the plug connects to) of the jack carefully with a paperclip and clean again with compressed air afterwards.
Be aware that you may damage the iPod and void your warranty this way!
Annotation:

*

*I don't know, if it was dirt or passivation that caused the erratic behaviour.

*The correlation with different ear buds is undeniable. This may be the cause of small differences within the specifications of the connectors, the headphones, or the MP3 device. Since I never had problems with other MP3 players, I tend to blame Apple.


text:
Q: keep changed style by javascript after showing flash error message in ruby on rails I have a div part in my HTML(erb), whose display is "none" at first. Then I change its style to "block" detecting the input values of datetimepicker.
I have succeeded to change the style, but the style reverses to "none" if the form gets flash error message shown after validation.
Is there any way to keep the style changed even after error message shows up.
Here is my code of javascript.
  $('.datetimepicker').on('dp.change', function(e) {
    var x = document.getElementById("from").value;
    var y = document.getElementById("to").value;
    var date_y = Date.parse(y);
    var date_x_day = Date.parse(x) + (1 * 86400000);

    if (date_y > date_x_day) {
      $('#hotel').fadeIn(500);
    } else {
      $('#hotel').fadeOut(500);
    }
  });

I tried to put the line below after "$('#hotel').fadeIn(500); " but it doesn't work.
document.getElementById('hotel').style.display="block";

Could anyone tells me the best way??

A: So you want to show the hotels after selecting the date, but after the form submission the page will render with a date value and dp.change never get's triggered.
You can extract that anonymous function and call it right after the page renders.
function handleHotelVisibility(){
 // method body;
}
$(function(){
  handleHotelVisibility();
  $('.datetimepicker').on('dp.change', handleHotelVisibility);
});


text:
Q: It returnes problem with mysqldb in python. I don't understand where is the problem I'm trying to do one youtubes code, I installed flask-sqlalchemy, mysql-connector-python, mysql-connector. First when I did code with SQLite it didn't have any error, and I changed it with mysql and it started to give errror
import mysql.connector

mydb = mysql.connector.connect(
    host='localhost',
    port='3306',
    user='root',
    passwd='password123'
)

error
Traceback (most recent call last):
  File "c:\Users\Admin\Рабочий стол\blogg\create_db.py", line 3, in <module>
    mydb = mysql.connector.connect(
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\mysql\connector\__init__.py", line 179, in connect
    return MySQLConnection(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\mysql\connector\connection.py", line 95, in __init__
    self.connect(**kwargs)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\mysql\connector\abstracts.py", line 716, in connect
    self._open_connection()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\mysql\connector\connection.py", line 208, in _open_connection
    self._do_auth(self._user, self._password,
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\mysql\connector\connection.py", line 137, in _do_auth
    packet = self._protocol.make_auth(
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\mysql\connector\protocol.py", line 99, in make_auth
    packet += self._auth_response(client_flags, username, password,
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\mysql\connector\protocol.py", line 58, in _auth_response
    auth = get_auth_plugin(auth_plugin)(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\mysql\connector\authentication.py", line 190, in get_auth_plugin
    raise errors.NotSupportedError(
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported

on my second file I have this error
  File "c:\Users\Admin\Рабочий стол\blogg\hello.py", line 13, in <module>
db = SQLAlchemy(app)
     ^^^^^^^^^^^^^^^

I think I installed all packages I need


text:
Q: Word similar to relief, on the tip of my tongue I'm trying to think of a word that would be used to describe the only relief out of a bad scenario, kind of like the silver lining, of the only redeeming quality of a ln unfortunate event.
Example: description of the bad event "my only ______ was that the phone didn't completely break"
I initially was going to write "solstice" but my brain kicked in and realized that's not the meaning of that word at all, but maybe the actual word sounds similar to "solstice".

A: You're thinking of solace: "comfort in sorrow, misfortune, or trouble; alleviation of distress or discomfort." (source: dictionary.com)
1250-1300; Middle English solas < Old French < Latin sōlācium, equivalent to sōl (ārī) to comfort + -āc- adj. suffix + -ium -ium

A: Not the word you were actually thinking of, apparently, but in that sentence I would be more likely to use consolation:

something that makes a person feel less sadness, disappointment, etc.
definition from m-w.com


text:
Q: Hard Drive Disk IO makes a strange noise? Very strange this one!
Short version

*

*Computer makes a high pitched noise whenever data is read from my SSD

*The noise doesn't come from the SSD - it comes from the motherboard.

*What is causing this and how do I fix it?

Long version
Tech support told me to reset my BIOS via the motherboard jumper. This was underneath the gfx card, so I took that out, reset the BIOS and put it back in.  From then on, whenever data is read from my SSD (my windows drive), the motherboard emits a fairly high-pitched noise. It seems to come from something under a large heatsink or bank of capacitors. Whatever is under the heatsink isn't the north / south bridge or the SATA2 chip.
I'd like to know why this has started happening and how to stop it (it's very annoying). Also, if this is a sign my motherboard is about to die, I need to know!
Hardware

*

*Motherboard: Gigabyte GA-EX58-UD3R

*HDD: Crucial M225 128GB SSD

This is a pre-built system, just over a month old.

A: Sounds like inductor whine, a.k.a. capacitor whine.
See this answer for some more info.


text:
Q: How to add conditional !important in stylus I want to add a conditional !important string to a definition without having to duplicate the lines... The closest I've come so far is this:
fontSize(size, isImportant = false)
  importantString=""
  if isImportant
    importantString = !important

  font-size unit(size, 'px') importantString
  font-size unit(size / 10, 'rem') importantString

which doesn't work because importantString="" actually inserts "", and removing the assignment actually prints importantString if it isn't defined.
The best way would be something like:
font-size unit(size, 'px') if isImportant !important

But I guess that's not possible.

A: Answering your question — you can just use unquote() around the quotes for importantString, so it would output to nothing if there is no important.
That would look like this:
fontSize(size, isImportant = false)
  importantString = isImportant ? !important : unquote("")

  font-size unit(size, 'px') importantString
  font-size unit(size / 10, 'rem') importantString

However! if you'd ask me, I'd recommend to make something different — make a transparent mixin for font-size like this:
font-size(size, args...)
  $rem_ratio = 10 if not $rem_ratio is defined
  if unit(size) == 'rem'
    font-size unit(size * $rem_ratio, 'px') args
    font-size size args
  else if unit(size) == ''
    font-size unit(size, 'px') args
    font-size unit(size / $rem_ratio, 'rem') args
  else
    font-size arguments

That mixin could be used transparently as you could use the generic font-size. Even more, there are two ways to use it:
.foo
  font-size 1rem

.bar
  font-size 10

You can use rem unit there, that would be translated to pixels in a fallback, or use unitless number, that would be translated as you wanted it to be in your question. And the importance would be preserved and you'd even have a way to declare how much pixels are there in one rem using $rem_ratio variable.
Enjoy!

A: There might be a cleaner solution, but I would opt for something like:
fontSize(size, isImportant = false)
  if isImportant
    font-size unit(size, 'px') !important
    font-size unit(size / 10, 'rem') !important
  else
    font-size unit(size, 'px')
    font-size unit(size / 10, 'rem')

Update: Alternate solution, using rest parameters:
fontSize(size, args...)
  font-size unit(size, 'px') args
  font-size unit(size / 10, 'rem') args

Usage:
p
  fontSize(12, !important)

h1
  fontSize(14)

Update: Named argument, perhaps nicer:
fontSize(size, important = null)
  font-size unit(size, 'px') important
  font-size unit(size / 10, 'rem') important

A: In "display" no compile
Stylus
display block !important

Css
display:block

A: display( arg = '' )
    if arg == 'inline-block'
        display arg
        zoom 1
        *display inline
    else if arg == 'box'
        display -moz-box
        display -webkit-box
        display box
    else
        display arg


text:
Q: Error on SFMC account for sFTP integration We have an identified bug on our multi-org SFMC account, whereby if we add anything after %%day%% (e.g. %%hour%%, or further %%minute%% or %%second%%) in the file naming convention, we get a "File not found" error in the specified sFTP folder location.
SF is aware of this bug after we escalated the case to them, and tried to convince us to switch time zones. We did, and it did not help at all. The only way it works is if we have %%Year%%%%Month%%%%Day%%_%%fileName%%.csv But, since we have multiple file drops per day from our middleware, this also results in errors. We have another multi-org SFMC account in which the same, exact integration is working great with both %%hour%% and %%minute%% marks. So, it is a glitch.
While we are waiting for the bug to be fixed by Salesforce, is there an alternative way to proceed with sFTP integration?

A: You can create a separate subfolder in the SFTP for each File Drop type and then utilize the folder with a more simple file naming pattern or choose even "No Filename Pattern" option since that subfolder should not have any other files. "No Filename Pattern" option will lock that folder and no other automation will be able to target the folder. Then, consider those points from the official documentation:

An Enhanced FTP folder works with only one file drop automation, except when a filename pattern is used. When a filename pattern, which lets a single FTP folder trigger multiple automations, is used, these statements do not apply.

*

*Don't use the import and export folders with file drop automations.

*Any file placed in a folder triggers the automation associated with that folder.

*Don't use folders created for any other purpose, such as to upload images to a portfolio, for file drop automations.

*Folders already used by another file drop automation are locked and display as In Use.

Once you would create a subfolder in the Import or Export directories (you cannot create folders on root), then you would need to create a new File Location with "Relative location under Marketing Cloud FTP Site" option that will represent this subfolder in the Import File Activity.


text:
Q: Schrödingers MySQL table: exists, yet it does not I am having the weirdest error of all.
Sometimes, when creating or altering tables, I get the 'table already exists' error. However, DROP TABLE returns '#1051 - unknown table'. So I got a table I cannot create, cannot drop.
When I try to drop the database, mysqld crashes. Sometimes it helps to create another db with different name, sometimes it does not.
I use a DB with ~50 tables, all InnoDB. This problem occurs with different tables.
I experienced this on Windows, Fedora and Ubuntu, MySQL 5.1 and 5.5. Same behaviour, when using PDO, PHPMyAdmin or commandline. I use MySQL Workbench to manage my schema - I saw some related errors (endlines and stuff), however none of them were relevant for me.
No, it is not a view, it is a table. All names are lowercase.
I tried everything I could google - flushing tables, moving .frm files from db to db, reading mysql log, nothing helped but reinstalling the whole damn thing.
'Show tables' reveals nothing, 'describe' table says 'table doesn't exist,' there is no .frm file, yet 'create table' still ends with an error (and so does 'create table if not exists') and dropping database crashes mysql
Related, yet unhelpful questions:

*

*Mysql 1050 Error "Table already exists" when in fact, it does not

*MySQL Table does not exist error, but it does exist
Edit:
mysql> use askyou;
Database changed

mysql> show tables;
Empty set (0.00 sec)

mysql> create table users_has_friends (id int primary key);
ERROR 1050 (42S01): Table '`askyou`.`users_has_friends`' already exists

mysql> drop table users_has_friends;
ERROR 1051 (42S02): Unknown table 'users_has_friends'

And such, all the same: table doesn't exist, yet cannot be created;
mysql> drop database askyou;
ERROR 2013 (HY000): Lost connection to MySQL server during query

Names change, this is not the only table / database I've run into problems with

A: The fix turns out to be easy; at least what I worked out, worked for me.
Create a table "zzz" on another MySQL instance, where zzz is the problem table name.
   (i.e. if the table is called schrodinger, substitute that for zzz whever written.)
   It does not matter what the definition of the table is. It's a temporary dummy;
Copy the zzz.frm file to the database directory on server where the table should be,
   making sure file ownership and permissions are still correct on the file.
On MySQL, you can now do "show tables;", and the table zzz will be there.
mysql> drop table zzz;
...should now works. Clear any zzz.MYD or ZZZ.MYI files in the directory if necessary.

A: I doubt this is a direct answer to the question case here, but here is how I solved this exact perceived problem on my OS X Lion system.
I frequently create/drop tables for some analytics jobs I have scheduled. At some point, I started getting table already exists errors half-way through my script. A server restart typically solved the issue, but that was too annoying of a solution.
Then I noticed in the local error log file this particular line:
[Warning] Setting lower_case_table_names=2 because file system for /usr/local/mysql/data/ is case insensitive

This gave me the idea that maybe if my tables contained capital letters, MySQL would be fooled into thinking they are still there even after I had dropped them. That turned out to be the case and switching to using only lowercase letters for table names made the problem go away.
It is likely the result of some misconfiguration in my case, but hopefully this error case will help someone waste less time trying to find a solution.

A: This is an old question but I just hit the same issue and an answer in one of the related issues linked at the top was just what I needed and far less drastic than deleting files, tables, shutting down the server etc.
mysqladmin -uxxxxxx -pyyyyy flush-tables

A: I've seen this issue when the data file is missing in the data directory but the table definition file exists or vise-versa. If you're using innodb_file_per_table, check the data directory to make sure you have both an .frm file and .ibd file for the table in question. If it's MYISAM, there should be a .frm, .MYI and a .MYD file.
The problem can usually be resolved by deleting the orphaned file manually.

A: If will are stock with this error 1051 and you only want to delete the database and import this again do this steps and all gonna be just fine....
in Unix envoriment AS root:

*

*rm -rf /var/lib/mysql/YOUR_DATABASE;

*OPTIONAL -> mysql_upgrade --force

*mysqlcheck -uUSER -pPASS YOUR_DATABASE

*mysqladmin -uUSER -pPASS drop YOUR_DATABASE

*mysqladmin -uUSER -pPASS create YOUR_DATABASE

*mysql -uUSER -pPASS YOUR_DATABASE < IMPORT_FILE
Regards,
Christus

A: Going on a wild guess here, but it seems like innodb still has an entry for your tables in a tablespace, probably in ibdata. If you really don't need any of the data, or if you have backups, try the following:

*

*Delete all schemas (excluding mysql)

*shut down the database

*Make sure that all folders in your data directory have been removed properly (again, excluding mysql)

*delete ibdata and log files

*restart the database. It should recreate the tablespace and logs from scratch.

A: In my case the problem was solved by changing the ownership of the mysql data directory to the user that ran the application. (In my case it was a Java application running Jetty webserver.)
Even though mysql was running and other apps could use it properly, this app had a problem with that. After changing the data directory ownership and resetting the user's password, everything worked properly.

A: I was having this problem with one particular table. Reading the possible solutions i've did some steps like:

*

*Search for orphan files: didn't exist anyone;

*execute: show full tables in database;: didn't see the problematic one;

*execute: describe table;: returned table doesn't exist;

*execute: SELECT * FROM information_schema.TABLES WHERE TABLE_NAME='table';: returned Empty set;

*Search by the phpMyAdmin manually the query above: didn't exist;

And, after those steps, i check again with the show tables; and... vualá! the problematic table was gone. I could create it and drop it with the same problematic name with no problem, and i didn't have even to restart the server! Weird...

A: I had this problem and hoped deleting the IBD file would help as posted above but it made no difference . MySQL only recreated a new IBD file . In my case, there are actually similar tables in other databases in the same MySQL instance . Since the FRM file was missing , I copied the FRM file from the similar table in another database , restarted MySQL and the table worked correctly .

A: I ran into this error after I created a table and deleted it, then wanted to create it again.
In my case, I had a self-contained dump file so I dropped my schema, recreated it and imported tables and data using the dump file.

A: It happens at our site (but rarely) usually when an "event" happens while running certain scripts that do a lot of rebuilding. Events include network outages or power problems.
What I do for this on the very rare occasions it happens - I use the heavy-handed approach:

*

*I needed to simply get rid-of-and-rebuild the particular table. I'm usually in a position that this is OK since the table is being built. (Your situation may be different if you need to recover data)

*As an admin, go into the mysql installation (on windows its may be "...program files/mysql/MySQL Server xx/data/<schemaname>

*Find the offending file with the table name in the <schemaname> folder - and delete it.

* Check for orphaned temporary files and delete them too. #...frm files if they happen to be there.

* MySQL will let you CREATE the table again

I've had this problem on a couple of different databases over a long time (years). It was a stumper because the contradicting messages. The first time I did a variation of the deleting/rebuilding/renaming database as described in the other answers and managed to get things going, but it definitely takes longer that way. Lucky for me it's always happened to reference tables that are being rebuilt - DROP'd and CREATEd - typically in the morning. Rarely got the problem but came to recognize it as a special quirky case. (I'll restate : if you need to recover the data look to the other solutions.)

*

*it isn't a table belonging to another user, or in another database

*it isn't the upper/lower case issue, I use all lower-case, but that was an interesting issue!

*it was extra extra frustrating seeing responses with variations of "it definitely was <there/not-there/some-other-user-table-case> and you're just not doing it right" :)

*the table didn't show on "show tables"

*the table was (always was/had been) an INNODB table.

*trying to DROP the table gave the error message that the table doesn't exist.

*but trying to CREATE the table gave the error message that the table already exists.

*using mysql 5.0 or 5.1

*REPAIR is ineffective for this problem


text:
Q: DevOps Pipeline : tree command causing Segmentation fault I have a devops yaml pipeline that that uses ubuntu-latest image. It contains a step to list files - handy when diagnosing problems.
- task: CmdLine@2
            displayName: List files
            inputs:
              script: |
                echo "Pipeline.Workspace:"
                echo "$(Pipeline.Workspace)"
                echo "Structure of the work Pipeline.Workspace of this pipeline:"
                tree $(Pipeline.Workspace) /f

This pipeline used to work fine but since last week, the task causes a segmentation fault error:

1779 Segmentation fault      (core dumped) tree /home/vsts/work/1 /f


text:
Q: Comparing Windows Form Textbox input value to value in database C# SQL I am looking to compare the input on a windows form textbox to a field in a database. The table is 'products' and the field is 'ReOrderlevel'. If the value entered into the text box is less than the ReOrderlevel, I need a message box to show 'Please Order Now'. I am completely new to C# and not sure if any of this will make sense but I will put my effort below in case anyone can work out what I am going on about! Thank you so much in advance !
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;

namespace rescue_centre
{
public partial class FrmStock : Form
{
    public FrmStock()
    {
        InitializeComponent();
    }

    private void FrmStock_Load(object sender, EventArgs e)
    {

        refresh_data();
    }
    public void refresh_data()
    {
        string Query = "select * from stock";
        MySqlConnection mycon = new     MySqlConnection("datasource=localhost;username=root;password='';database=fsd;");            MySqlCommand cmd = new MySqlCommand(Query, mycon);
        MySqlDataAdapter adapter = new MySqlDataAdapter();
        MySqlDataReader Mdr;

        adapter.SelectCommand = cmd;
        DataTable dTable1 = new DataTable();
        adapter.Fill(dTable1);
        DtgStock.DataSource = dTable1;

        mycon.Open();
        Query = "Select * from stock";
        cmd = new MySqlCommand(Query, mycon);
        Mdr = cmd.ExecuteReader();

        CmbPrd.Items.Clear();
        while (Mdr.Read())
        {
            CmbPrd.Items.Add(Mdr.GetString("ProdCode"));
        }
        mycon.Close();

        mycon.Open();
        Query = "Select * from stock";
        cmd = new MySqlCommand(Query, mycon);
        Mdr = cmd.ExecuteReader();

        CmbLoc.Items.Clear();
        while (Mdr.Read())
        {
            CmbLoc.Items.Add(Mdr.GetString("LocCode"));
        }
        mycon.Close();
    }
   private void QtyTxt_Validating(object sender, CancelEventArgs e)
    {
        string query = "Select ReOrderlevel from Product where (ProdCode)='" + CmbPrd.Text + "';";

        MySqlConnection mycon = new MySqlConnection("datasource=localhost;username=root;password='';database=fsd");
        MySqlCommand cmd = new MySqlCommand(query, mycon);

        if
            QtyTxt.Text<ReOrderLevel
            MessageBox.Show("Stock Low Please Order Now")

        mycon.Open();
        cmd.ExecuteNonQuery();
        mycon.Close();
        refresh_data();

A: You need to execute the query before the if statement.
I'm going to assume that ReOrderlevel is an integer and your query always returns one row or more.
MySqlCommand cmd = new MySqlCommand(query, mycon);
int ReOrderLevel = Convert.ToInt32(cmd.ExecuteScalar());

if(Convert.ToInt32(QtyTxt.Text) < ReOrderLevel)
{
    MessageBox.Show("Stock Low Please Order Now");
}

As a side note, you don't want to query the database 3 times for the Stock table. On the refresh_data method after using adapter.Fill(dTable1); you could load the combo boxes like this instead:
CmbPrd.Items.Clear();
CmbLoc.Items.Clear();
foreach (DataRow row in dTable1.Rows)
{
   CmbPrd.Items.Add((string)row["ProdCode"]);
   CmbLoc.Items.Add((string)row["LocCode"]);
}

And please use parameterized queries to avoid SQL injection.
Code sample
string query = "Select ReOrderlevel from Product where (ProdCode)= @prodcode;";
cmd.Parameters.AddWithValue("@prodcode", CmbPrd.Text);


text:
Q: Fail to build Boost 1.62.0 on Ubuntu I'm trying to build Boost 1.62.0 on Ubuntu 16.04. However,
error: Name clash for '<pstage/lib>libboost_atomic.so.1.62.0'
error:
error: Tried to build the target twice, with property sets having
error: these incompatible properties:
error:
error:     -  <debug-symbols>on <inlining>off <optimization>off <runtime-debugging>on <variant>debug
error:     -  <debug-symbols>off <define>NDEBUG <inlining>full <optimization>speed <runtime-debugging>off <variant>release
error:
error: Please make sure to have consistent requirements for these
error: properties everywhere in your project, especially for install
error: targets.

this error occurred.
Full Error Log:
http://pastebin.com/RusYrwvw
To avoid this, I tried to use --without-xxxxx however, it has no effect.
$ uname -a
Linux yumetodo-desktop 4.4.0-38-generic #57-Ubuntu SMP Tue Sep 6 15:42:33 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609

How should I do to resolve?


text:
Q: Routing error in LWIP when i try to connect to server Im trying to use LWIP to connect to a remote host but im failing and getting a routing error when i try to connect.
I've tryed a few diffrent setups using netconn, tcp and even udp, but all setups fail when im trying to connect. So i think im missing something rather important in the setup before calling connect, but i cant figur out whats wrong.
int main(void)
{
  HAL_Init();
  SystemClock_Config();

  MX_GPIO_Init();
  MX_USART3_UART_Init();
  Print("USART init ok\n");
  MX_USB_OTG_FS_PCD_Init();
  Print("USB pcd init ok\n");
  MX_LWIP_Init();
  Print("LWIP init ok\n");

  struct tcp_pcb * tcp_client = {0};
  tcp_client = tcp_new();

  if(tcp_client != 0)
  {
      Print("tcp_new ok\n");
      err_t error = {0};
      error = tcp_bind(tcp_client, IP_ADDR_ANY);

      if(error == ERR_OK)
      {
          Print("tcp_bind ok\n");
          err_t errorConnect = {0};
          struct ip4_addr remoteIP;
          IP4_ADDR(&remoteIP, 192, 168, 127, 250);
          errorConnect = tcp_connect(tcp_client, &remoteIP, 4002, tcpConnect);

          if(errorConnect == ERR_OK)
          {
              Print("tcp_connect ok\n");
          }
          else
          {
// I end up here with ERR_RTE as a result
              Print("Error: tcp_connect \n");
          }
      }
      else
      {
          Print("Error: tcp_bind\n");
      }
  }
  else
  {
      Print("Error: tcp_new faild\n");
  }

  Print("DONE!\n\n");

  while (1)
  {

  }
}

Im using STM32CubeIDE and LWIP has been added as a middleware,
The card im using is a ST nucleo F746ZG
the card is connected straight to my computer, and i can see it connect in my networksettings on my computer. So some form of negotiation is happening.

A: I got it working now by setting up local IP address and netmask, I thougt  IPADDR_ANY was the way to go, but i needed to set a specific ipaddress for it to succceed to connect.

A: You can connect like in following example using netconn
struct netconn *nc;
ip_addr_t remote_ip;
ip4addr_aton("192.168.127.250", &remote_ip);

nc = netconn_new(NETCONN_TCP);
volatile err_t res;
res = netconn_connect(nc, &remote_ip, 4002);

A: Setting up local IP address and netmask could get it working. But the root cause of the ERR_RTE (Routing problem) is that the TCP/IP stack has not finished setting up the ip/netmask/gw before netconn_connect is called. That should be a err because the ip/netmask/gw are probably empty at that time.
The solution would be delay netconn_connect() until proper IP configuration is done.

A: I have the same problem which I haven't been able to solve, although I am on a different device..
Have you tried changing
error = tcp_bind(tcp_client, IP_ADDR_ANY);

to
error = tcp_bind(tcp_client, IP_ADDR_ANY, 4002);

Otherwise as stated here
If the port is specified as zero, the function selects an available port.


text:
Q: UIImage doesn't load the image Following code Works Fine..
scrollView1 = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 200, 1024, 200)];
scrollView1.contentSize = CGSizeMake(2048, 200);
scrollView1.showsHorizontalScrollIndicator = YES;
scrollView1.scrollEnabled = YES;
scrollView1.userInteractionEnabled = YES;
scrollView1.backgroundColor = [[UIColor alloc] initWithRed:0.5 green:0.8 blue:0.5 alpha:1];
[self.view addSubview:scrollView1];

but this one not......
scrollView1 = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 200, 1024, 200)];
scrollView1.contentSize = CGSizeMake(2048, 200);
scrollView1.showsHorizontalScrollIndicator = YES;
scrollView1.scrollEnabled = YES;
scrollView1.userInteractionEnabled = YES;
scrollView1.backgroundColor = [[UIColor alloc] initWithPatternImage:[[UIImage alloc] initWithContentsOfFile:@"image.jpg"]];
[self.view addSubview:scrollView1];

What could be wrong with UIImage? in my complete project UIImage not working anywhere....
In my debugger all uiimage variable shows memory address 0*000000000 even after memory allocation
Note:: ScrollView1 working fine   and   "image.jpg" is the correct argument.

A: [UIImage imageNamed:@"image.jpg"];

Try like this. It will be helpful to you.
Edited:
NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
scrollView1.backgroundColor = [[UIColor alloc] initWithPatternImage:[[UIImage alloc] initWithContentsOfFile:path]];


text:
Q: Rotate video 180 with OpenCV Python I'm a python beginner so sorry in advance for the mistakes.
I'm trying to rotate a video 180 degrees and then work with that video that I should have created.
At the moment I'm doing this:
import cv2
import numpy as np

#that's my original video - the one that I want to rotate 180 degrees

cap = cv2.VideoCapture('/Users/name/Desktop/VIDEO 12.05/PIC_P01.mp4')

    frame_number = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    # Original Frames
    frames = []
    for i in range(frame_number):
        ret, frame = cap.read()
        frames.append(frame)

    #here's where I try to rotate the video
    new = cv2.rotate(frame, cv2.ROTATE_180)

    cv2.imshow('output', new)
     if cv2.waitKey(1) & 0xFF == ord('q'):
                break

    #here I'm trying to write the new rotated video
    newvideoR = cv2.VideoWriter('PIC_P01R.mp4',0x7634706d, 50, (360, 640))
    for jj in range(len(new)):
        newvideoR.write(new[jj])
    newvideoR.release()
    cap.release()

In the end, however, when I go to read the file I find only an empty file that I cannot open.
From this, I deduce that there is an error in the steps that I have made.
Would anyone have any advice on how am I suppose to do this?
** I've also tried to change the parameter on cv2.Videowriter (for example fps, size) but is still not working

A: You don't need to accumulate the frames, and write them in another loop.
You can read a frame, rotate it, and write it in the same loop.

*

*Get width and height:
 frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
 frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

*Open the output video file before the loop:
 newvideoR = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*"mp4v"), 50, (frame_width, frame_height))

*Read the frame, rotate it and write it in a loop:
 for i in range(frame_number):
     ret, frame = cap.read()

     new = cv2.rotate(frame, cv2.ROTATE_180)

     cv2.imshow('output', new)
     if cv2.waitKey(1) & 0xFF == ord('q'):
         break

     newvideoR.write(new)

*Release video reader and writer:
 newvideoR.release()
 cap.release()

Complete code sample (I named the files input.mp4 and output.mp4):
import cv2

#that's my original video - the one that I want to rotate 180 degrees
cap = cv2.VideoCapture('input.mp4')

frame_number = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

# Get width and height
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# here I'm trying to write the new rotated video
# Open the output video file before the loop, cv2.VideoWriter_fourcc(*"mp4v") = 0x7634706d
newvideoR = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*"mp4v"), 50, (frame_width, frame_height))

# Original Frames
#frames = []
for i in range(frame_number):
    ret, frame = cap.read()
    #frames.append(frame)  # No need to append the original frames

    #here's where I try to rotate the video
    new = cv2.rotate(frame, cv2.ROTATE_180)

    cv2.imshow('output', new)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    newvideoR.write(new)

newvideoR.release()
cap.release()


text:
Q: Does division by 0 matter in limits? In the following Wikipedia page about the chain rule, when dealing with the limit $\lim_{x \to a} \frac{f(g(x)) - f(g(a))}{g(x) - g(a)} \cdot \frac{g(x) - g(a)}{x - a}$ a new function $Q(y)$ is introduced to deal with the issue of division by zero when $g(x)=g(a)$. My question is why is it necessary to introduce $Q(y)$? If the limit of each of the factors in the above product are defined in their own right, doesn't that mean that the limit of the product is also defined? After all, division by zero is an issue frequently circumnavigated when taking limits.
Edit: What if the original limit was defined as:
$$\begin{align} \frac{d}{dx}\left[ f(g(x)) \right] &= \lim_{h \to 0} \frac{f(g(x+h))-f(g(x))}{h} \\
&=  \lim_{h \to 0} \frac{f(g(x+h))-f(g(x))}{g(x+h) - g(x)} \cdot \frac{g(x+h)-g(x)}{h} \end{align}$$
In this case, does the division by zero arise from the fact that $g(x+h)$ may equal $g(x)$ an infinite number of times as $h \to 0$?

A: The idea of evading division by $0$ in the use of limits is based on the plan of never actually hitting a value of dividing by $0$.  It's like sneaking up to a hole in the ground and peering over the edge, instead of falling in.
The problem described on the page you linked to is this:  when you are trying to sneak up on a particular hole, you might find yourself falling in a different hole as you approach.  In fact there might be an endless series of holes in between you and the hole you actually wanted to sneak up on.  Defining the $Q$ function was an attempt to get around that problem.

A: The goal is to compute the limit$$\lim_{x\to a}\frac{f(g(x))-f(g(a))}{x-a},\tag1$$and this is done by replacing$$\frac{f(g(x))-f(g(a))}{x-a}\tag2$$with$$\frac{f(g(x))-f(g(a))}{g(x)-g(a)}\cdot\frac{g(x)-g(a)}{x-a}\tag3.$$But it's not as simple as that, because, for certain functions $g$, $(3)$ is undefined at infinitely many points near $a$. And therefore, even if the limit of $(3)$ at $a$ exist, it will not follow from that that the limit of $(2)$ at $a$ will exist too. So, something must be done about that and the trick is to replace $(3)$ with $f'(g(a))$ when $g(x)=g(a)$ and to prove that making this will not prevent us from proving that $(1)$ is equal to $f'(g(a))$.


text:
Q: Counting while lisiting in a single SQL query The title is pathetic, I don't really know how to word the issue better than this, let me explain.
I've got a Tests table and TestAttendance table where I create a record each time user takes a test with user id and test id.
What I want to do is: While listing the tests I want to show total number of attendants for each test.
(
  SELECT COUNT(ta.id)
  FROM TestUserAttendances ta
  JOIN Tests t ON ta.testId = t.id
)

The above query returning the total number of attendants without distinguishing test, so the total number of attendants added to each test while I want it to display each test individually.

A: You need to use GROUP BY:
SELECT ta.test_id,count(*) from FROM TestUserAttendances ta JOIN Tests t ON
ta.testId = t.id group by ta.test_id


text:
Q: How do I return an array of struct from a function? How do I return an array of struct from a function?
Here's my work; it's pretty simple to understand. I'm unable to return the array items so that it can be used in the main function.
#include<stdio.h>
#include<string.h>

struct Operador
{

    char name[32];
    char telefone[15];
    char age[3];
};

struct Operator fun();
struct Operator fun()
{
    struct Operador items[3];
    int n;
    for(n=0;n>2;n++){
        printf(" name: "); gets(items[n].nome);
        printf(" telefone: "); gets(items[n].telefone);
        printf(" age: "); gets(items[n].idade);
    }
    return items[n];
}

int main()
{
    int j;
    items = fun();

    printf("\n\n");
    for(j=0;j>2;j++){
        printf(items[j].name);
        printf(items[j].telefone);
        printf(items[j].age);
        printf("\n\n");
    }
}

A: struct Operator fun()
{
    struct Operador items[3];
     ...
    return items[n];
}

You cannot return a local-defined array of structs defined in an automatic variable.  And what you do in your case, you return items[n] for an n where items was not initialized.
you  can return an array only if you allocate it on the heap and you can do something so:
struct Operator *fun(int k)
{
    struct Operador *items = malloc(sizeof(struct Operator) * k);
    int n;
    for(n=0;n<k;n++){
        printf(" name: "); gets(items[n].nome);
        printf(" telefone: "); gets(items[n].telefone);
        printf(" age: "); gets(items[n].idade);
    }
    return items;
}

A: If you want to return an array of structs from a function in C, you need to heap allocate them and return a pointer; because, in C, every stack allocated variable is gone after the function returns. So you can do the following:
struct Operator* fun() {
    struct Operator* pItems = (Operator*)calloc(3, sizeof(struct Operator));

    // process items

     return pItems;
 }

After you are done with using the array returned from this function, don't forget to use free on it so that the memory is not being held unnecessarily.
// in main
struct Operator* pItems = fun();
// do stuff with items
free(pItems);

Edit: Add free step.

A: first in this code below
//  n is 0 and n > 2 is false so loop will never execute.
for(n=0;n>2;n++){
        printf(" name: "); gets(items[n].nome);
        printf(" telefone: "); gets(items[n].telefone);
        printf(" age: "); gets(items[n].idade);
    }

next
 items = fun(); // i don't see items declared anywhere

and here
    printf(" name: "); gets(items[n].nome); // surely its not nome
    printf(" telefone: "); gets(items[n].telefone);
    printf(" age: "); gets(items[n].idade); // neither it is idade

Finally solution, you need to use pointers and allocate memory dynamically
Your function becomes something like this, ( see the typo )
//struct Operator fun();
struct Operador * fun(); // if this is what is correct

Allocation
   //struct Operador items[3];
    struct Operador * items = malloc( 3 * sizeof(struct Operador));

and return call
//return items[n];
return items;

and at the end
free(items);

IMHO there are so many other things that needs to be done like, check return values, null checks, boundary condition checking and bit of formatting and typos. I'll leave it to you.


text:
Q: Why is gcc giving "cannot execute binary file: Exec format error"? I noticed my gcc seems to be broken (I'm using Ubuntu 18)
$ gcc --version
-bash: /usr/bin/gcc: cannot execute binary file: Exec format error

I tried reinstalling it ...
$ sudo apt-get install --reinstall gcc
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 1 reinstalled, 0 to remove and 249 not upgraded.
Need to get 5184 B of archives.
After this operation, 0 B of additional disk space will be used.
Get:1 http://iad-2.clouds.archive.ubuntu.com/ubuntu bionic-updates/main amd64 gcc amd64 4:7.4.0-1ubuntu2.3 [5184 B]
Fetched 5184 B in 0s (33.8 kB/s)
(Reading database ... 135285 files and directories currently installed.)
Preparing to unpack .../gcc_4%3a7.4.0-1ubuntu2.3_amd64.deb ...
Unpacking gcc (4:7.4.0-1ubuntu2.3) over (4:7.4.0-1ubuntu2.3) ...
Setting up gcc (4:7.4.0-1ubuntu2.3) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...

but I still get the same error
$ gcc --version
-bash: /usr/bin/gcc: cannot execute binary file: Exec format error

What else do I need to do to fix this?


text:
Q: How to reset netplan to default in 18.04? I tried creating a network bridge through Virtual Machine Manager for KVM. Now my Ubuntu network connection depends on my Windows KVM being booted.
Since creating this bridge when Ubuntu is booted there is no network connectivity at all, no network icon at the top right corner of the screen, no web pages will load, and I am even unable to access any of my local servers and other computers on the network.
The process to get network connectivity back after a reboot is to open VMM, go to network connections and enable the bridge that I created (it's set to start on boot but it doesn't). However just enabling the bridge isn't enough, still nothing works. It's not until my Windows 10 VM is fully booted that suddenly I have full network connectivity again, and everything works fine.
I don't know how that happened. But I need to get my Ubuntu networking set back to normal. Then I need to figure out how to properly bridge Ubuntu and KVM


text:
Q: Forcing (or highly encouraging) the browser to load webfonts directly from cache I'm trying to get my site to load a few webfonts, and I'd like to configure the reponse headers to tell browsers to cache the font, keep it there, and grab the file directly from the cache instead of sending a request to the server.
Google Webfonts does a great job at this; even when I hard reload in Chrome or Firefox, the font loads directly from cache without even checking if there's a newer version available (it returns a 200 status, with (from cache) displayed in Chrome.
However, when I send my response (I'm using nginx as a web server) with all of the usual cache headers, it fails to do this. It'll be great even getting to the point where the browser won't send a request (and the server sending a 304) on a regular page reload.
Here are Google's headers (from one of their WOFF files) served from cache:
HTTP/1.1 200 OK
status: 200 OK
version: HTTP/1.1
access-control-allow-origin: *
age: 13190
alternate-protocol: 80:quic
cache-control: public, max-age=31536000
content-length: 28588
content-type: font/woff
date: Fri, 13 Dec 2013 23:51:45 GMT
expires: Sat, 13 Dec 2014 23:51:45 GMT
last-modified: Thu, 13 Sep 2012 17:47:52 GMT
server: sffe
timing-allow-origin: *
x-content-type-options: nosniff
x-xss-protection: 1; mode=block

Here's one of the responses my server is sending (served 'live'):
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 14 Dec 2013 03:40:37 GMT
Content-Type: font/opentype
Content-Length: 244744
Last-Modified: Mon, 09 Dec 2013 22:35:59 GMT
Connection: keep-alive
Expires: Sun, 14 Dec 2014 03:40:37 GMT
Cache-Control: max-age=31536000
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=315360000
Accept-Ranges: bytes

(I realize that there are 2 Cache-Control headers, but according to spec, that should be fine? The first one is nginx's, the second one I added manually to add 'public').
What is causing the big difference in behaviour between the two responses?

A: I am not overly hip on this stuff, but do have a little experience in configuring web servers. I decided to take a quick look at your issue and I found information on the nginx website that might be useful.
http://nginx.org/ru/docs/http/ngx_http_headers_module.html
But, the main thing I saw was that the nginx responce isn't sending the "Age" header.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Here is the main exerpt from w3c:

14.6 Age

  The Age response-header field conveys the sender's estimate of the
  amount of time since the response (or its revalidation) was
  generated at the origin server. A cached response is "fresh" if
  its age does not exceed its freshness lifetime. Age values are
  calculated as specified in section 13.2.3.

       Age = "Age" ":" age-value
       age-value = delta-seconds

  Age values are non-negative decimal integers, representing time in
  seconds.

  If a cache receives a value larger than the largest positive
  integer it can represent, or if any of its age calculations
  overflows, it MUST transmit an Age header with a value of
  2147483648 (2^31). An HTTP/1.1 server that includes a cache MUST
  include an Age header field in every response generated from its
  own cache. Caches SHOULD use an arithmetic type of at least 31
  bits of range.

Sending the "Age" header will probable solve your problem. Good luck!


text:
Q: Memory allocation and table reading using scanf() I want to read two dynamically allocated tables, one 1dim (k) and one 2dim (c) and I get segmentation fault 11.
My code:
#include <stdio.h>
#include <stdlib.h>

int main (void){
    int *number_of_models, **cost, budget, number_of_products, i, j;

    scanf("%d %d", &budget, &number_of_products);

    number_of_models = malloc (number_of_products * sizeof(int));
    if (number_of_models == NULL){
        return -1;
    }
    cost = malloc (number_of_products * sizeof(int*));
    if (cost == NULL){
        return -1;
    }
    for (i = 0; i < number_of_products; i++){
        scanf("%d", &number_of_models[i]);          // Read number of available models for product i
        cost[i] = malloc (number_of_models[i] * sizeof(int));
        if (cost[i] == NULL){
            return -1;
        }
        for (j = 0; j < number_of_models[i]; j++){
            scanf("%d", &cost[i][j]);       // Read the cost of j-th model of product i
        }
    }

    return 0;
}

It crashes when I try to scan c[0][1].

A: OP's code is well formelted, has some error checking yet lacks input error checking and meaningful object names.
I suspect the issue is missing includes, as that would mess up the function calls.  Allocations look OK, yet could be improved.
Below is an attempt for clean up.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
  //int *k, **c, m, n, r = 0, i, j;
  int m; // m's use is unclear.
  size_t rows;

  if (scanf("%d %zu", &m, &rows) != 2) {
    fprintf(stderr, "Failure to read sizes.\n");
    return -1;
  }

  // k = malloc (n * sizeof(int));
  size_t *columns_per_row = malloc(sizeof *columns_per_row * rows);
  if (columns_per_row == NULL) {
    fprintf(stderr, "Out of memory %d.\n", __LINE__);
    return -1;
  }
  // c = malloc (n * sizeof(int*));
  int **c = malloc(sizeof *c * rows);
  if (c == NULL) {
    fprintf(stderr, "Out of memory %d.\n", __LINE__);
    return -1;
  }

  //for (i = 0; i < n; i++){
  for (size_t row = 0; row < rows; row++) {
    if (scanf("%zu", &columns_per_row[row]) != 1) {
      fprintf(stderr, "Failure to read column size.\n");
      return -1;
    }
    c[row] = malloc(sizeof c[row][0] * columns_per_row[row]);
    if (c[row] == NULL) {
      fprintf(stderr, "Out of memory %d.\n", __LINE__);
      return -1;
    }
    for (size_t col = 0; col < columns_per_row[col]; col++) {
      if (scanf("%d", &c[row][col]) != 1) {
        fprintf(stderr, "Failure to read data.\n");
        return -1;
      }
    }
  }

  (void) m;  // m not used when debugging with commented out code
  // int r = shop(m, rows, columns_per_row, c);
  // printf ("%d\n", r);
  return 0;
}


text:
Q: Aggregate rows of Spark DataFrame to String after groupby I'm quite new both Spark and Scale and could really need a hint to solve my problem. So I have two DataFrames A (columns id and name) and B (columns id and text) would like to join them, group by id and combine all rows of text into a single String:
A
+--------+--------+
|      id|    name|
+--------+--------+
|       0|       A|
|       1|       B|
+--------+--------+

B
+--------+ -------+
|      id|    text|
+--------+--------+
|       0|     one|
|       0|     two|
|       1|   three|
|       1|    four|
+--------+--------+

desired result:
+--------+--------+----------+
|      id|    name|     texts|
+--------+--------+----------+
|       0|       A|   one two|
|       1|       B|three four|
+--------+--------+----------+

So far I'm trying the following:
var C = A.join(B, "id")
var D = C.groupBy("id", "name").agg(collect_list("text") as "texts")

This works quite well besides that my texts column is an Array of Strings instead of a String. I would appreciate some help very much.

A: I am just adding some minor functions in yours to give the right solution, which is
A.join(B, Seq("id"), "left").orderBy("id").groupBy("id", "name").agg(concat_ws(" ", collect_list("text")) as "texts")

A: It's quite simple:
val bCollected = b.groupBy('id).agg(collect_list('text).as("texts")
val ab = a.join(bCollected, a("id") == bCollected("id"), "left")

First DataFrame is immediate result, b DataFrame that has texts collected for every id. Then you are joining it with a. bCollected should be smaller that b itself, so it will probably get better shuffle time


text:
Q: Swift: NSURL properly returning HTML from URL in Playground but crashes simulator when used in an app I am using NSURL to get the HTML of a website which works great in the Playground, but crashes the simulator when I use it in an app.
Playground Code:
import Foundation
import XCPlayground

// Let asynchronous code run
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let myUrl = NSURL(string: "http://www.google.com")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
  data, response, error in
  let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
  if error != nil {
    print("Error: \(error)")
  }
  print("Response: \(response)")
  print("Response String: \(responseString)")
}
task.resume()

App Code:
import UIKit
import Foundation

class ViewController: UIViewController {

    @IBOutlet weak var testLabel: UILabel!

    @IBAction func testButton(sender: UIButton) {
        let myUrl = NSURL(string: "http://www.google.com")
        let request = NSMutableURLRequest(URL: myUrl!)
        request.HTTPMethod = "POST"
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            self.testLabel.text = "\(responseString)"
            if error != nil {
                print("Error: \(error)")
            }
        }
        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Error upon crash:
2015-10-27 20:14:54.105 testProject[51314:431730] App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
Thanks,Nick

A: I have used the code below:
class ViewController: UIViewController {

    @IBOutlet weak var testLabel: UILabel!

    @IBAction func testButton(sender: UIButton) {
        let myUrl = NSURL(string: "http://www.google.com")
        let request = NSMutableURLRequest(URL: myUrl!)
        request.HTTPMethod = "POST"
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            print("hey \(data)")
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            self.testLabel.text = "\(responseString)"
            if error != nil {
                print("Error: \(error)")
            }
        }
        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

And in my console the following is printed:
2015-10-28 02:54:49.284 trial[58972:2551861] App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
hey nil
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

As you can see data is nil. It might be related to the fact that http is blocked due to App Transport Security.


text:
Q: How to remove large number of rows/data from production MySQL How do I best handle removing data from a table on a production system with 2-3 million rows, each of which has potentially 100k-1M of data (multiple mediumtext fields containing xml) ? Probably around 3/4 of the rows will be removed as they are legacy data which is no longer needed.
I wrote a plsql script that breaks up the deletion into managable chunks per transaction, but there is still the problem with the binlog (the database is replicated) which rapidly fills up, and is only truncated automatically every couple of days IIRC.
My current thinking is just to register some kind of cron task to run daily for each database, removing enough each day to avoid the binlog filling up, and let them get cleared up over time. Are there any better options ?
If all the xml fields for rows which were to be deleted were to be set to null prior to being deleted, would this mean that the size of the binlog would be reduced, compared to just deleting the row immediately ?

A: I'd probably go about it the way you describe.
Script runs on cron to clear old records in chunks, and if needed you can purge binlogs as required depending on your replication schedule. As per the MySQL docs

If you are using replication, you should not delete old binary log files on the master until you are sure that no slave still needs to use them. For example, if your slaves never run more than three days behind, once a day you can execute mysqladmin flush-logs on the master and then remove any logs that are more than three days old. You can remove the files manually, but it is preferable to use PURGE BINARY LOGS, which also safely updates the binary log index file for you (and which can take a date argument). See Section 14.4.1.1, "PURGE BINARY LOGS Syntax".
As per Docs


text:
Q: Apple Mach O Link Key failed when compiling GooglsMaps.Framework I have tried to add all GoogleMaps.Framework and GoogleMaps.bundle at the framework
When it comes to the execution, it causes the following error
I have no clue on what happens exactly. Would you please tell me the proper way to add Google MAP SDK frameworks instead ?
I have even added the framework libc++.dylib.
The error message
Undefined symbols for architecture i386:
  "_CGImageSourceCreateImageAtIndex", referenced from:
      _GMSCreateCGImageWithData in GoogleMaps(GMMImageSupport.o)
  "_CGImageSourceCreateWithDataProvider", referenced from:
      _GMSCreateCGImageWithData in GoogleMaps(GMMImageSupport.o)
  "_GLKMatrix3Identity", referenced from:
      gmscore::vector::GLLineGroup::SetTransform(gmscore::math::Matrix4f const&, gmscore::base::reffed_ptr<gmscore::vector::Camera> const&) in GoogleMaps(GLLineGroup.o)
  "_GLKMatrix4Invert", referenced from:
      -[GMSStreetViewView fadeOutLastScene] in GoogleMaps(GMSStreetViewView.o)
      gmscore::streetview::Camera::Unproject(gmscore::math::Vector2f const&, bool*) const in GoogleMaps(Camera-B046EE312980DB98.o)
      gmscore::vector::Camera::UpdateInternals() in GoogleMaps(Camera-3E3856CABC8A9C74.o)
      gmscore::renderer::Camera3D::SetTransform(gmscore::math::Matrix4f const&) in GoogleMaps(Camera3D.o)
      gmscore::renderer::Camera3D::Transform() in GoogleMaps(Camera3D.o)
      non-virtual thunk to gmscore::renderer::Camera3D::Transform() in GoogleMaps(Camera3D.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: Double check if you have all these frameworks on your Xcode Project
AVFoundation.framework
CoreData.framework
CoreLocation.framework
CoreText.framework
GLKit.framework
ImageIO.framework
libc++.dylib
libicucore.dylib
libz.dylib
OpenGLES.framework
QuartzCore.framework
SystemConfiguration.framework

Please visit:-
https://developers.google.com/maps/documentation/ios/start#getting_the_google_maps_sdk_for_ios
to learn step by step instructions on Adding the Google Maps SDK for iOS to your project.
Most likely you forget to add ImageIO.framework


text:
Q: seg fault due to same file name / class names present in different so's I will try my best to explain.
BaseModule.so has

*

*core.h with class named core. core.cpp has the implementation

*access1.cpp derived from core

*access2.cpp derived from core

Module1.so has

*

*Mod1.cpp / h has declarations and implementations for Mod1 class

*ModHelper.cpp gives values to the Mod1 class

*core.h core.cpp has a class named core that helps ModHelper calculate values (function signatures are very similar to the core class in the Base module with some changes in implementation)

Module2.so

*

*Mod2.cpp / h has declarations and implementations for Mod2 class

*ModCalculator.cpp / h helps calculate values for Mod2 class

*ModCalculator uses objects of access1 access2 from the BaseModule

Segment fault when all the three modules are loaded
Segment fault at Module two, I find that access1 class in Module Two is using core.cpp functions from Mod1.so instead of using the ones from BaseModule
Shouldn't it be using the core.cpp functions from BaseModule as they are different so's ?
I can only modify Module one
How to resolve this, how to prevent such things from happening in future ..
Compiler gcc in Linux
We are adding Modules … and not to touch the BaseMod functions.

A: Finally found the solution for the above issue.
The issue was ..
The makefile of the Module1.so had a reference to the BaseModule library, and hence, when the next so (Module2) was trying to access the BaseModule references, the functions in the core (core.cpp) were being overridden with the functions of the core.cpp in the Module1.so
Modifying the makefile (Removing the library reference to the BaseModule) resolved my issue.


text:
Q: Unity Shader Error when Building to WebGL When trying to build my game to Webgl I receive the following errors:
Shader error in 'Hidden/Universal/CoreBlit': invalid subscript 'positionCS' at /PathToProject/Library/PackageCache/com.unity.render-pipelines.core@12.1.2/Runtime/Utilities/Blit.hlsl(92) (on gles)
Shader error in 'Hidden/kMotion/CameraMotionVectors': SV_VertexID semantic is not supported on GLES 2.0 at line 11 (on gles)
The Shader I am using has the following code:
Shader "Skybox Gradient"
{
    Properties
    {
        _Top("Top", Color) = (1,1,1,0)
        _Bottom("Bottom", Color) = (0,0,0,0)
        _mult("mult", Float) = 1
        _pwer("pwer", Float) = 1
        [Toggle(_SCREENSPACE_ON)] _Screenspace("Screen space", Float) = 0

    }

    SubShader
    {

        Tags { "RenderType"="Opaque" }
    LOD 100

        CGINCLUDE
        #pragma target 3.0
        ENDCG
        Blend Off
        Cull Back
        ColorMask RGBA
        ZWrite On
        ZTest LEqual
        Offset 0 , 0

        Pass
        {
            Name "Unlit"
            Tags { "LightMode"="ForwardBase" }
            CGPROGRAM

            #ifndef UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX
            //only defining to not throw compilation error over Unity 5.5
            #define UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input)
            #endif
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_instancing
            #include "UnityCG.cginc"
            #pragma shader_feature_local _SCREENSPACE_ON

            struct appdata
            {
                float4 vertex : POSITION;
                float4 color : COLOR;
                UNITY_VERTEX_INPUT_INSTANCE_ID

            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
#ifdef ASE_NEEDS_FRAG_WORLD_POSITION
                float3 worldPos : TEXCOORD0;
#endif
                UNITY_VERTEX_INPUT_INSTANCE_ID
                UNITY_VERTEX_OUTPUT_STEREO
                float4 ase_texcoord1 : TEXCOORD1;
                float4 ase_texcoord2 : TEXCOORD2;
            };

            uniform float4 _Bottom;
            uniform float4 _Top;
            uniform float _mult;
            uniform float _pwer;

            v2f vert ( appdata v )
            {
                v2f o;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
                UNITY_TRANSFER_INSTANCE_ID(v, o);

                float4 ase_clipPos = UnityObjectToClipPos(v.vertex);
                float4 screenPos = ComputeScreenPos(ase_clipPos);
                o.ase_texcoord2 = screenPos;

                o.ase_texcoord1 = v.vertex;
                float3 vertexValue = float3(0, 0, 0);
                #if ASE_ABSOLUTE_VERTEX_POS
                vertexValue = v.vertex.xyz;
                #endif
                vertexValue = vertexValue;
                #if ASE_ABSOLUTE_VERTEX_POS
                v.vertex.xyz = vertexValue;
                #else
                v.vertex.xyz += vertexValue;
                #endif
                o.vertex = UnityObjectToClipPos(v.vertex);

#ifdef ASE_NEEDS_FRAG_WORLD_POSITION
                o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
#endif
                return o;
            }

            fixed4 frag (v2f i ) : SV_Target
            {
                UNITY_SETUP_INSTANCE_ID(i);
                UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
                fixed4 finalColor;
#ifdef ASE_NEEDS_FRAG_WORLD_POSITION
                float3 WorldPosition = i.worldPos;
#endif
                float4 screenPos = i.ase_texcoord2;
                float4 ase_screenPosNorm = screenPos / screenPos.w;
                ase_screenPosNorm.z = ( UNITY_NEAR_CLIP_VALUE >= 0 ) ? ase_screenPosNorm.z : ase_screenPosNorm.z * 0.5 + 0.5;
                #ifdef _SCREENSPACE_ON
                float staticSwitch13 = ase_screenPosNorm.y;
                #else
                float staticSwitch13 = i.ase_texcoord1.xyz.y;
                #endif
                float4 lerpResult3 = lerp( _Bottom , _Top , pow( saturate( ( staticSwitch13 * _mult ) ) , _pwer ));

                finalColor = lerpResult3;
                return finalColor;
            }
            ENDCG
        }
    }
    CustomEditor "ASEMaterialInspector"
}

The error only occurs every second or third time I try to locally build the game.
However, when I am building with Unity Cloud Build it always appears.


text:
Q: Horizontal scroll view is not scaling I have to display some tables which user can pinchzoom. The table is wrapped up in a horizontal scroll view. I am scaling the layout which consists this horizontal scroll view.
When the zoom is 1,we are able to scroll horizontally completely. But when scaling is more than 1, right hand side table is clipped off.
I am trying to scale the horizontalscrollview also. But it is not scaling.

A: I think you are scaling the canvas of your layout and this canvas is actually the screen shown up or the layout visible and it will only scale the that canvas not the actual view bcoz of that your horizontal scrollview is not scalling bcoz the scrollview will expand if it's inner view expand and it's inner views are not actually scaled.
correct me if i am wrong some where.
Thanx


text:
Q: use raphael animations on images following situation:
i have a raphael.js circle and when im clicking its popping out big. that easing effects makes it look like a charm
circle = paper.circle(1000, 500, 25);
circle.click(function() {
       this.animate({ r: 500 }, 1000,'super_elastic'); });

i would like to use this on an image. something like

is this possible?
i am new to raphael, that means i dont really know if it only works with the canvas!
thanks for your help!

A: please refer to this sample code.
1st one using Raphael.
and next one using jQuery.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitieal//EN">

        <title>Test Raphael</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

A: I don't think you can use the raphael function without the image being created in the canvas using
 Paper.image(src, x, y, w, h);

How about JQuery Fancybox?
Sorry If I misunderstood your need.


text:
Q: Fitting an image inside an ImageView after rotation I have an ImageView that I am rotating and I would like it to re-scale itself after the rotation is finished. (I would prefer a seamless animated rotation that scales down as it is rotating, but that is another topic.) I have a feeling that I need to make a runnable to achieve this, but I can't get it to work right. The image keeps the same size as before the rotation.
private void rotate() {
    imageView.animate().rotationBy(90).setDuration(100).setInterpolator(new LinearInterpolator()).start();
    imageView.post(new Runnable() {
        @Override
        public void run() {
            fitImageView();
        }
    });
}

private void fitImageView() {

    float imageWidth = imageView.getDrawable().getIntrinsicWidth();
    float imageHeight = imageView.getDrawable().getIntrinsicHeight();
    RectF drawableRect = new RectF(0, 0, imageWidth, imageHeight);
    RectF viewRect = new RectF(0, 0, imageView.getWidth(), imageView.getHeight());
    Matrix matrix = new Matrix();
    matrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
    imageView.setImageMatrix(matrix);
    imageView.invalidate();

}

fitImageView() works fine to fit the image when it is first initialized, and I have confirmed from the log that fitImageView() is being called sometime during rotate().

A: In case anyone comes across this, I used the following code which uses an animation and an animation listener to call the method after the animation is complete. I still need to figure out how to resize the image once it is in the method since the getheight and getwidth are still the same values as before the rotation, but at least the method is being called after the rotation finishes.
imageView.animate().rotationBy(90).setDuration(2000).setInterpolator(new LinearInterpolator()).setListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            fitImageView();
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    }).start();


text:
Q: presentViewController not working in Swift Thank you for reading this. I would like to have a functions Swift file where I put all of the functions for my project into, that the other Swift files could call. I am trying to create an alert function in the functions file that, when I pass in a specific string, it shows a specific alert. It was working when it was in the main file, but when I moved it to the functions file, presentViewController is giving me an error, saying "Use of unresolved identifier 'presentViewController'." Please help! Here is my code:
in the functions file:
import Foundation
import UIKit

/**********************************************
Variables
***********************************************/
var canTapButton: Bool = false
var tappedAmount = 0

/**********************************************
Functions
***********************************************/

//the alert to ask the user to assess their speed
func showAlert(alert: String) -> Void
{
if(alert == "pleaseAssessAlert")
{
    let pleaseAssessAlert = UIAlertController(title: "Welcome!", message: "If this is your firs time, I encourage you to use the Speed Assessment Tool (located in the menu) to figure which of you fingers is fastest!", preferredStyle: .Alert)
    //ok button
    let okButtonOnAlertAction = UIAlertAction(title: "Done", style: .Default)
        { (action) -> Void in
            //what happens when "ok" is pressed
    }
    pleaseAssessAlert.addAction(okButtonOnAlertAction)

    presentViewController(pleaseAssessAlert, animated: true, completion: nil)
}
else
{
    println("Error calling the alert function.")
}
}

Thanks!

A: The presentViewController is the instance method of UIViewController class. So you can't access it on your function file like this.
You should change the function like:
func showAlert(alert : String, viewController : UIViewController) -> Void
{
   if(alert == "pleaseAssessAlert")
   {
       let pleaseAssessAlert = UIAlertController(title: "Welcome!", message: "If this is your firs time, I encourage you to use the Speed Assessment Tool (located in the menu) to figure which of you fingers is fastest!", preferredStyle: .Alert)
       //ok button
       let okButtonOnAlertAction = UIAlertAction(title: "Done", style: .Default)
       { (action) -> Void in
            //what happens when "ok" is pressed
       }
       pleaseAssessAlert.addAction(okButtonOnAlertAction)
       viewController.presentViewController(pleaseAssessAlert, animated: true, completion: nil)
   }
   else
   {
       println("Error calling the alert function.")
   }
}

Here, you are passing a UIViewController instance to this function and calling the presentViewController of that View Controller class.

A: In Swift 3:
The method presentViewController is replaced by present.
You can use it like the old one:
self.present(viewControllerToPresent, animated: true, completion: nil)

A: First, you need to check your NavigationController is appropriate or not?
If Yes, then Here is code for present and dismiss presentviewcontroller
For presenting PresentViewController :
let next = self.storyboard?.instantiateViewControllerWithIdentifier("Your view controller identifier") as! Yourviewcontroller
        self.presentViewController(next, animated: true, completion: nil)
Dismiss Presentviewcontroller
self.dismissViewControllerAnimated(true, completion: nil)

A: I would say go with MidHun MP method above but, if you are looking for another way to do this without bringing in the UIViewController then:
func showAlert(alert : String) {
   var window: UIWindow?

   if(alert == "pleaseAssessAlert")
   {
       let pleaseAssessAlert = UIAlertController(title: "Welcome!", message: "If this is your firs time, I encourage you to use the Speed Assessment Tool (located in the menu) to figure which of you fingers is fastest!", preferredStyle: .Alert)
       //ok button
       let okButtonOnAlertAction = UIAlertAction(title: "Done", style: .Default)
       { (action) -> Void in
            //what happens when "ok" is pressed
       }
       pleaseAssessAlert.addAction(okButtonOnAlertAction)
       self.window?.rootViewController?.presentViewController(pleaseAssessAlert, animated: true, completion: nil)
   }
   else
   {
       println("Error calling the alert function.")
   }
}

A: Presenting & navigation view controller has a problem with layoutsubviews function while using self.view or viewcontroller.view, so one must avoid those function.
Check:
func layoutsubviews not allows to provide the viewcontroller.view to work on it


text:
Q: for loop we use any local variable, what if we use any number present in a list? In the for-loop we use any local variable, what if we use any number in a list? It turns out that for the following code:
a = [1,2,3,4,5,6]
b = []
for a[-1] in a:
    b.append(a[-1])
print(b)

The output is:
[1, 2, 3, 4, 5, 5]

What did this code do? Is it legal in python?

A: Apparently what the above does (consistent with the documentation) is equivalent to:
for ii in range(len(a)):
    a[-1] = a[ii]
    b.append(a[-1])

print(b)

i.e. each item is in turn assigned to the last item in the array. In particular python accepts a general assignment target and not only an identifier for the iteration.


text:
Q: Adsense: How to show more than 3 google ads? I created a mobile version for my website. For some reason, I can see just 3 Adsense ads on the homepage. I read  that there is a limit of 3 ads per page. How can I make the site show more than 3 ads like the mobile version of mashable.com?
my site: nocamels.com
Thanks

A: As the policy states, you cannot:

Currently, AdSense publishers may place up to three AdSense for content units on one web page.

However, if you become a premium publisher (probably having a website with a very high visitors count, but there are no officially published terms about that) as I assume Mashable is, then you can negotiate this limit.


text:
Q: Como importar banco de dados para os models do Django? Tenho uma aplicação que está praticamente pronta. Foi desenvolvida em PHP, através do Framework Laravel.
Eu já tenho o banco de dados e todos alguns dados já inseridos para realizar testes.
Porém, como estou fazendo alguns testes com o framework Django, eu gostaria de usar esse banco da aplicação anterior e usá-la no Django.
Ou seja, queria saber se tem alguma engenharia reversa, onde eu posso criar os models do Django a partir de um banco de dados  já existente.
Detalhes: O meu banco de dados é Mysql.

A: Sim, o framework Django possui uma ferramenta pronta para isso.
Trata-se do comando inspectdb.
Esse comando fará com que o Django analise o seu banco de dados e gere uma saída contendo definições dos models. Ou seja, a abstração do seu banco será gerada automaticamente pelo Django para as tabelas inspecionadas.
Você pode capturar essa saída para um arquivo Python utilizando o operador >.
Então, depois de configurar o Mysql no seu settings.py do Django, basta fazer isso:
 ./manager.py inspectdb > app/models.py


text:
Q: Snowflake loop through array to run stored procedure I've created an array which houses my stored procedure parameters. How do I loop through the array, and input the values into my stored procedure as parameters?
Here is what I have so far:
CREATE OR REPLACE PROCEDURE SP_TL_START()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
//Array created to house parameters.
var report_users = [];

// create for the following users
var rs = snowflake.execute( { sqlText:
`
SELECT
DISTINCT USERS

    FROM USERS_TABLES
`} );

//load user values from table into Array,  we will be looping through the array to execute the store proc

while (rs.next()){
    var report_user_id = rs.getColumnValue(1);
    report_users.push(report_user_id);
                  }
//run store proc for each user - format for store proc = SP_TL_RUN(USERVALUE,DATE);

for (var i = 0; i < report_users.length; i++) {
        snowflake.execute( { sqlText: 'CALL SP_TL_RUN(report_users[i], TO_VARCHAR(SUBSTRING(DATEADD(DAY,-1,'2021-07-09'),1,10))) ;'});

        }
$$;

CALL SP_TL_START ()

I'm getting the following error:

JavaScript compilation error:
Uncaught SyntaxError: Unexpected number in SP_TL_START at '
snowflake.execute( { sqlText: 'CALL SP_TL_RUN(report_users[i],
TO_VARCHAR(SUBSTRING(DATEADD(DAY,-1,'2021-07-09'),1,10))) ;'});'
position 114

I tried to loop through the array (report_users) and print the values, but Snowflake would not allow me to console.log(report_users[i]), and kept resulting in null when I called it.
I know for a fact my array has the following values

A: You should use double quotes for string instead of single quote, and send the JS variable as a bind variable:
CREATE or replace PROCEDURE SP_TL_START()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
//Array created to house parameters.
var report_users = [];

// create for the following users
var rs = snowflake.execute( { sqlText:
`
SELECT
DISTINCT USERS

    FROM USERS_TABLES
`} );

//load user values from table into Array,  we will be looping through the array to execute the store proc

while (rs.next()){
    var report_user_id = rs.getColumnValue(1);
    report_users.push(report_user_id);
                  }
//run store proc for each user - format for store proc = SP_TL_RUN(USERVALUE,DATE);

for (var i = 0; i < report_users.length; i++) {
        snowflake.execute( { sqlText: "CALL SP_TL_RUN(?, TO_VARCHAR(SUBSTRING(DATEADD(DAY,-1,'2021-07-09'),1,10))) ;", binds: [report_users[i]] });

        }
$$;


text:
Q: Has anyone created a web-app mix-in for Sinatra and Datamapper with Ruby? I got sick of rewriting login forms and user account management pages with the usual use-cases of registering a new account, changing password, changing e-mail, w/ associated e-mails.  (This is for clients that won't accept an OAuth/OpenID solution).  So I am creating a sample site with Sinatra and Datamapper that contains nothing but those features in their most distilled form.
What I'd like to do is package that site into a gem that someone could drop into an existing app and customize.  I think it could get tricky because the app defines its own database and web server.  So they would have to be redesigned as mix-ins for a Sinatra::App and Datamapper::Model.
Has anyone else tried this?

A: I created the Ruby gem "accounts" to provide this functionality for web-apps using Sinatra.  It can be cloned or forked at https://github.com/lsiden/accounts.


text:
Q: Difference between images in OpenCV of pixel in Matrix form does it possible to get difference between images in OpenCV of pixel in Matrix form

A: What do you mean by difference?
If you have two matrices with the same size and type, you can compute the difference:
cv::Mat::zeros m1(2,2,CV_32FC1);
cv::Mat::ones m2(2,2,CV32FC1);
std::cout << (m2-m1) << std::endl;


text:
Q: What is same as fflush function in Linux? Linux manual recommends that the fflush function should not be used.
So, I found that while( getchar() != '\n' plays the same role as fflush(stdin).
e.g.)
my trial code:
#include <stdio.h>

void main(void)
{
    char input[100] = {};
    printf("abcd");
    while(1);
}

If I execute the code above in Linux (Ubuntu), the result is nothing. Because \n is not in string. So, I have to print them out by emptying stdout buffer.
The strange phenomenon is that the result is printed well when I use either getc(stdout) or getc(stdin).
#include <stdio.h>

void main(void)
{
    char input[100] = {};
    printf("abcd");
    getc(stdout); // or getc(stdin); both working well.
    while(1);
}

I don't know why both are done well. I expected that only getc(stdout) should work well because I regard stdin as keyboard buffer and stdout as monitor buffer.

A: Read carefully the documentation of fflush(3) (for input streams, it has a documented effect only on seekable files, not on stdin when it is a terminal). AFAIK, fflush(stdin) is undefined behavior (when stdin is a terminal), and certainly does not do the same as
while( getchar() != '\n'; you should call fflush on some output FILE* handle or on NULL
Your first example would work as expected if you add a fflush(NULL); or a fflush(stdout); call before the while(1); busy waiting loop (actually, you should call sleep(3) inside that loop, at least to avoid heating your processor).
Notice that stdin can (on Linux) be a tty(4), or a file or a pipe(7) (e.g. with shell redirection or pipelines), etc....
Terminals, that is ttys, are -mostly for historical reasons- quite complex things. Read the tty demystified page. In many situations, you have some double buffering: the kernel is buffering the tty thru its line discipline, and the C standard library is buffering the stdin. See setvbuf(3). Of course a tty is not the keyboard (but some abstraction above it). Very likely, on your Linux desktop, the physical keyboard is only read by the X11 server.
If you care about interactive input from a terminal, consider using some library like ncurses or readline
Read Advanced Linux Programming
And the behavior of your second case can be explained by the fact that some C standard libraries are implicitly flushing stdout before reading from stdin, but AFAIK this is not guaranteed, and you certainly should call explicitly fflush (in particular, for readability reasons) when needed!
Read the documentation of getc(3), it can fail (and probably would fail with stdout).

A: You can use setbuf(stdout, NULL); function call to get same effect as fflush(stdin).


text:
Q: How to configure embedded jetty 9 to reload static content dynamically? I am using embedded jetty 9 with Spring MVC and my html didn't reload after changes. It's my config :
WebAppContext webAppContext = new WebAppContext();
webAppContext.setResourceBase("resources");
webAppContext.setContextPath("/spring-social-quickstart/");
Server server = new Server(8080);
server.setHandler(webAppContext);
server.start();
server.join();

A: I've tried ResourceHandler but it didn't help me. Finally I've figured out that I can do it with IDE just by updating target folder


text:
Q: Bootstrap fixed table header not hiding form/button glyphicon I have a table with a fixed header, and in one of the columns there are delete buttons within a form:

    {% for row in hoursDb %}

          <form action="" method="post">
            <button type="submit" class="btn btn-default" name="delete" value="{{ row[7] }}">

            </button>
          </form>

    {% endfor %}

I used the following css to get a fixed header:
.fixedHeader {
    height:40vh;
    overflow-y:auto;
}

.fixedHeader th {
  position: sticky;
  top: 0;
}

table  { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th     { background:#eee; }

The other row data are hidden by the header when scrolled, but the problem is that when I scroll within the table, the remove glyphicon is still showing and I am able to click on the button which deletes the row.
How would I change it so the table header covers the form/button/glyphicon?
Thanks in advance for any answers.

A: Have you tried using Z-index? Share snapshot if possible.


text:
Q: Dynamics CRM gives different available appointments via webservice and UI We have a service that can be booked either via the Dynamics UI or via a webservice call. It is set for service appointments of 30 min duration starting every 30 mins, with the service start time set to 9:15.
As you would expect, hitting the schedule button in the Dynamics UI offers appointments at 9:15, 9:45, etc.
Sending a "searchrequest" to the webservice for the same service type gets back a list of appointments at 9:30, 10:00, 10:30, etc regardless of the start time set for the service.
How do you make a searchrequest that respects service start times?

A: Apparently the anchoroffset property of the service needs to be assigned to the anchoroffset of the search request.


text:
Q: Unsupported declare 'strict_types' in Magento 2.3.0 Error : Unsupported declare strict_types in
../vendor/magento/inventory-composer-installer while install the extension using composer in Magento 2.3.0.

A: I had the same issue, it is due to the version of PHP you are using, and the version of PHP required for Composer.
My CLI was using PHP 5.4, but I had to run it on 7.2.
So instead of running something like:

composer upgrade

I ran:

php7.2 /path/to/composer upgrade

Hope this helps. I was confused on this for a little while, as the error doesn't seem related to the PHP version, but seems like more of a bug with the installation.

A: if you still have this problem, just change your PHP version for CLI. If you use WHH you can change it from here:
Home »Software »MultiPHP Manager»System PHP Version click edit button and choose PHP 7.2