text:
Q: Unable to update images in PyQT5 from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QSlider, QLabel
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from utils import read_screenshots

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 Slider"
        self.top = 200
        self.left = 500
        self.width = 1400
        self.height = 1300

        self.InitWindow()

    def InitWindow(self):
        # hbox = QHBoxLayout()

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('./screenshots/output000011.png'))
        self.label.setGeometry(60, 60, 1280, 720)

        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setTickInterval(1)
        self.slider.setMinimum(0)
        self.slider.setMaximum(100)
        self.slider.setGeometry(100, 830, 1000, 20)
        self.slider.valueChanged[int].connect(self.changedValue)

        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)

        # self.setLayout(hbox)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

    def changedValue(self, value):
        # change value of the slider when you move the slider and switch to the next img
        if value == 0:
            print(value)
            self.label.setPixmap(QPixmap('./screenshots/output06439.png'))
        elif value < 50:
            print(value)
            self.label.setPixmap(QPixmap('./screenshots/output025316.png'))
        else:
            print(value)
            self.label.setPixmap(QPixmap('./screenshots/output033238.png'))

        size = self.slider.value()
        self.label.setText(str(size))

if __name__ == '__main__':
    App = QApplication(sys.argv)
    window = Window()
    sys.exit(App.exec_())

My changedValue() function is printing the values correctly but it doesn't display any of the images based on the value conditions. The changedValue() is supposed to switch pictures. Where have I made a mistake?
I couldnt figure out what the problem is!


text:
Q: Return and throw on one line without semi-colon Is there a way to return a fat-arrow anon function, run a conditional, return an error if it's false and return true if it's true all on one line, WITHOUT a semi-colon?
let example = (d) => { if (get(d, 'facebook_user.id')) return true; throw new Error('Missing `facebook_id` from request') }

I'm trying to find a better way of writing the above without a semi-colon, the restriction is I have to return and throw. Ideas? Thoughts?

A: One can create a function that wraps the condition and the error message and throws / returns.
export function ifThrow (condition, errorMessage) {
  if (condition) throw new Error(errorMessage)
  return true
}

let check_facebook_id = (d) => ifThrow(!get(d, 'facebook_id'), 'Missing `facebook_id`')

A: How about below?
let example = (d) => { get(d, 'facebook_user.id') || (() => {throw new Error('Missing `facebook_id` from request')})() };

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to detect that the entire period of C++ random engine has been consumed I want to write a small (fast) C++ program which essentially "detects" that the entire period of a std::minstd_rand0  engine has been consumed. In other words I want to detect when the sequence is repeating (and also measure the time required for the sequence to repeat). I don't care about the target distribution (it can be uniform).
Any ideas on how I should proceed? One option I was considering is to create two std::array variables. In the first std::array I would store say the 10000 first pseudo-random variates returned by std:minstd_rand0. I would then proceed by filling the other std::array with successive blocks of 10000 variates and compare the contents of the 2 arrays after each pass of 10000 variates. I would consider that the entire period has been consummed once the 2 arrays are equals.
Would this approach be sensible?

A: Standard random number engines can be compared to each other--they compare equal if and only if they have the same state.
Therefore, you can pretty easily measure the period with code that:

*

*Creates two default constructed generators

*Executes a loop generating a number from one of the generators, and incrementing a count.

*Until the two generators compare equal again.

At least in my quick test of std::minstd_rand0, I get a result of
 2147483646

Needless to say, this is a lot more practical with std::minstd_rand0 than with std::mt19937 (for one obvious example).


text:
Q: merge two separate mysql queries need to merge (maybe UNION ALL) this two mysql queries..
select users.name as 'Agent', min(agent_activities.created_at) as 'Login Time'
from agent_activities, users
where
agent_activities.agent_id = users.id
and date(agent_activities.created_at) = curdate()
and agent_activities.activity='login'
group by agent_activities.agent_id
order by agent_activities.agent_id asc;

select users.name as 'Agent', max(agent_activities.created_at) as 'Logout Time'
from agent_activities, users
where
agent_activities.agent_id = users.id
and date(agent_activities.created_at) = curdate()
and agent_activities.activity='logout'
group by agent_activities.agent_id
order by agent_activities.agent_id asc;

Now result is
Agent       | Login Time
test Admin  | 2018-09-27 10:26:54
Agent 1     | 2018-09-27 11:43:44
Hari        |  2018-09-27 11:10:41

Agent       | Logout Time
test Admin  | 2018-09-27 11:43:41
Agent 1     | 2018-09-27 11:45:04
ttt         | 2018-09-27 11:21:06
Hari VH     | 2018-09-27 15:18:04

Desired result
Agent       | Login Time           | Logout Time
test Admin  | 2018-09-27 10:26:54  | 2018-09-27 11:43:41
Agent 1     | 2018-09-27 11:43:44  | 2018-09-27 11:45:04
Hari        |  2018-09-27 11:10:41 | 2018-09-27 15:18:04

Please help,..................................
Thanks in advance.

A: You can do what you want with conditional aggregation:
select u.name as Agent,
       max(case when aa.activity = 'login' then aa.created_at end) as Login_Time,
       max(case when aa.activity = 'logout' then aa.created_at end) as Logout_Time
from agent_activities aa join
     users u
     on aa.agent_id = u.id
where aa.created_at >= curdate() and
      aa.created_at < curdate() + interval 1 day
group by u.name
order by u.name  asc;

Notes:

*

*Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

*Table aliases make the query easier to write and to read. Use abbreviations for the table names.

*Using functions on columns generally impedes the use of indexes, so I replaced date(created_at) with simpler date comparisons.

*Your GROUP BY columns should match the unaggregated columns in the SELECT.

A: Use conditional min/max, and consider the min created_at only when the activity is login, and vice-versa for logout.  The reason this works is that the default ELSE value (not explicitly shown) is NULL, which is ignored by both MIN and MAX.
SELECT
    u.name as 'Agent',
    MIN(CASE WHEN a.activity = 'login'  THEN a.created_at END) AS 'Login Time'
    MAX(CASE WHEN a.activity = 'logout' THEN a.created_at END) AS 'Logout Time'
FROM agent_activities a
INNER JOIN users u
    ON a.agent_id = u.id
WHERE
    DATE(a.created_at) = CURDATE()
GROUP BY
    a.agent_id, u.name
ORDER BY
    a.agent_id, u.name;

Some notes:
I converted your implicit join to an explicit inner join, with an ON clause.  Also, I introduced table aliases into the query, which leaves it much easier to read.

A: Try with conditional aggregation:
select users.name as 'Agent', min(case when agent_activities.activity='login' then agent_activities.created_at end) as 'Login Time' ,
max(case when agent_activities.activity='logout' then agent_activities.created_at end) as 'Logout Time'
from agent_activities inner join users
on agent_activities.agent_id = users.id
and date(agent_activities.created_at) = curdate()
group by users.name
order by users.name asc


text:
Q: Cross Domain Cookies with IFrame in Internet Explorer I had a client's requirement for opening a another domain link in Iframe. This thing works fine with Firefox, Chrome but in Internet Explorer its giving error that cookies are not enabled. When I directly open that link it work fine with IE, but with IFrame its not the same case. I did some search on Google and didn't find a proper answer for it. I just want to confirm is there any coding fault from my side? I also found this solution for the problem
In PHP:
header ( "p3p:CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");

But its not working on my case. I am not sure where should I put this, because I can change the code of my website if require. But I can't change the Iframe site, Since we are not the owner.
This project is built in PHP.
Any help would be much appreciated.
Thanks in advance

A: The subframe's cookies are blocked by the browser's Cookie Privacy feature.
That subframe (the one setting the cookies) must send a P3P statement indicating how the cookies will be used in order for the browser to accept them.
Specifying the P3P statement in the outer frame is not sufficient and will not help anything.

A: Are you runnig IE in protected mode? It can be a security exception. Go to a IE settings and take a look if IFRAME isn't disabled.


text:
Q: Is it possible to connect 300 devices with openthread? I am looking for a stack allowing to connect several hundred devices,
Openthread has max numbers of hopes equal 16.
Is it possible to extend that number to have 300 devices connected sequentially?
What are requirements to the chip in this case if possible or what limits the max number of connected routing devices?

A: The Thread Protocol Specification currently has a limit of 15 hops between routers (or 17 hops between end devices).  It is not possible to connect hundreds of devices sequentially.  At the same time, the Thread Protocol does connecting hundreds of end devices to each router.  However, in most practical cases, the number of end devices a router supports is determined by its memory resources.


text:
Q: Copy files to a particular remote server from a list of servers I have 3 remote servers to which I need to copy files from the source server rather than having to run same command multiples times for each server, can it be possible to select one server from the list and then transfer files to that server?
My aim here is to avoid writing same piece of code for each server individually.
Eg:
A = source server
B = remote server 1
C = remote server 2
D = remote server 3
(there may be more remote servers in future)

Enter which server you want the files to be copied to (B/C/D):
if I choose B on command line, following command gets executed:
scp xyz.txt user@remoteserver2:/home
scp jkl.txt user@remoteserver2:/home

Similarly if other options are chosen, files should get copied to that server.
Here's the code that i have for copying files on 1 server.
#!/bin/sh
today=`date '+%Y%m%d'`;
min_date=`date -d "$today -14days" +%Y%m%d`
max_date=`date -d "$today -1days" +%Y%m%d`
read -p "Enter the date you want input files for [yyyymmdd]: " user_date
udate=$user_date
if [[ $user_date -ge $min_date && $user_date -lt $today ]]
then
  ssh user@server2 mkdir -p /data/${udate}_inputfiles/{f1,f2,f3,f4,f5,f6}
   echo "Starting to copy files"
    cd /homepath1
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f1
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f2
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f3
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f4
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f5
    scp *${udate}* user@server2:/data/${udate}_inputfiles/f6

else
    echo "Entered date is invalid: Please specify date between $min_date and $max_date"
fi

A: It's simple, write a function:
function serverscp () {
s="$1"
ssh user@$s mkdir -p /data/${udate}_inputfiles/f{1,2,3,4,5,6}
echo "Starting copy"
cd /homepath1
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f1
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f2
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f3
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f4
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f5
scp *${udate}* user@${s}:/data/${udate}_inputfiles/f6
cd $OLDPWD
}

Later in your script,
for tgt in server1 server2 server3 ; do
  serverscp $tgt
done

Warning untested code, not even checked with https://shellcheck.org


text:
Q: invalid handle exception when debugging I have following message while I am in debug mode in Visual studio 2010 Unhandled exception at 0x76c5f9e2 in test.exe: 0xC0000008: An invalid handle was specified.When I run this in regular mode I don't get this error.
The debugger stops in close.c at this line
CloseHandle( (HANDLE)_get_osfhandle(fh) ) )

Does anyone have any sugestion how such error could be avoided?

A: Don't handle this exception, but avoid the situation were you pass an invalid handle!
Edit:
In debug mode, the code gives you a hint that something is wrong. So you should fix that error instead of handle the exception afterwords!

A: I just had the same problem.
I checked for stack corruption, corruption of the handle etc. Eventually I discovered that I shouldn't have been calling CloseHandle()!
This was a handle returned by FindFirstFile(), the correct disposal function is FindClose(), not CloseHandle().


text:
Q: Jquery-UI diagloge scrolls to top of the page I am using jquery-ui and I am trying to have it so when clicking the "click me" link it opens the modal. However, since the link is directed to "#" it also scrolls to the top of the page. How can I prevent it doing that? I think it is something to do with e.preventdefault
    $( "#dialog" ).dialog({
  autoOpen: false,
  show: {
    effect: "blind",
    duration: 1000
  },
  hide: {
    effect: "explode",
    duration: 1000
  }
});

$( "#btn_sec2" ).click(function() {
  $( "#dialog" ).dialog( "open" );
});

And the button to open it:
Click me!

A: Try to use e.preventDefault():
$( "#btn_sec2" ).click(function(e) {
    e.preventDefault();
    $( "#dialog" ).dialog( "open" );
});


text:
Q: SQL Server 2012: Dynamic crosstab in stored procedure Im trying to use a stored procedure to create a pivot table between two declared variables @rvar (as rowvariable) and @cvar (as columnvariable). The point is to call the stored procedure from VBA using these two as dynamic input when executing the stored procedure.
My code has three parts:

*

*creating test-data

*declaring locals

*finding names of columns in crosstab an storing in new local @sql1

*executing crosstable with the pivotfunction using the names stored in @sql1.

My problem: The code below works but I would like to make it dynamic regarding the variable defining the column structure - currently set to "q10_1_resp" - so that I only have to declare the local @cvar and use that in part 3 (like in part 4). I have succeeded in making part 3 into a sql-string with subsequent execution but then the column names stored in @sql1 cannot be used in the code in part 4 (I guess it is a scope thing).
--Part 1

create table [user].[test]
    (rowvar nvarchar(max),
    q10_1_resp int,
    q10_2_resp int)
    GO

INSERT [user].[test]
        VALUES ('PH',1,2),
            ('PH',2,3),
            ('EA',1,5),
            ('EA',5,4),
            ('PH',3,4),
            ('PH',6,6),
            ('EA',4,1),
            ('PH',5,3),
            ('PH',2,1)
        GO

-- Part 2
declare @rvar as nvarchar(max) = 'rowvar'
declare @cvar as nvarchar(max) = 'q10_1_resp' --this input should be dynamic as well
declare @sql1 as nvarchar(max)= ''
declare @sql2 as nvarchar(max)= ''

-- Part 3
select @sql1 = @sql1 + [a].[col] + char(44)
    from
        (select distinct QUOTENAME(q10_1_resp) as [col]
        from [user].[test]
        group by q10_1_resp) as a

SET @sql1 = left(@sql1, len(@sql1) - 1)

-- Part 4
SET @sql2 = 'select ' +
    + @rvar + ','
    + @sql1
    + ' from (Select '
    + @rvar + ', '
    + @cvar
    + ' from [user].[test]) sq pivot(count('
    + @cvar
    + ') for '
    + @cvar + ' IN ('
    + @sql1
    + ')) as pt'

exec sp_executesql @sql2

A: After a great deal of trying to globalize the scalarvariable without success using a temporary table to store the string was the key. The temporary table created at the beginning of the stored procedure can be assigned and referenced the entire time of the procedure. Thus assigning within execution of @sql and then referencing the string at execution of @sql2. I hope it makes sense.
CREATE PROCEDURE [dbo].[sp_crosstab]
    -- Add the parameters for the stored procedure here
    @rvar nvarchar(max) = '',
    @cvar nvarchar(max) = '',
    @data nvarchar(max) = '',
    @sql nvarchar(max) = '',
    @sql2 nvarchar(max) = '',
    @sql3 nvarchar(max)=''
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

create table #temp_crosstab
(
   sqlstr nvarchar(max)
)

set @sql ='
declare @sql1 nvarchar(max) = char(00)
select @sql1 = @sql1 + [a].[col] + char(44)
    from
        (select distinct QUOTENAME(' + @cvar + ') as [col]
        from ' + @data + '
        group by ' + @cvar + ') as a

    SET @sql1 = left(@sql1, len(@sql1) - 1)

insert into #temp_crosstab values (@sql1)'

execute sp_executesql @sql

select @sql3 = [sqlstr] from #temp_crosstab

set @sql2 = '

select ' + @rvar + char(44) +
        @sql3 + 'from (Select '
        + @rvar + char(44) + ' '
        + @cvar
        + ' from ' + @data + ') sq pivot(count('
        + @cvar
        + ') for '
        + @cvar + ' IN ('+@sql3+')) as pt'

exec sp_executesql @sql2
    END
GO


text:
Q: extract a line from text file python Hi I am new to python and dont really know where to start, so here goes
i have the below portion of a text file text file the file is much longer and i want to pick out some information from it if a line in the file begins with "Error" then i want to print that information in another text file
1 warning message
Warning 1 - Loop End (SGLoopControl2) - errors were encountered during run
2 error messages
Error 1 - 0952 RHFDShaftTorq Not Found in asd22961ck99_
Error 2 - Multi-column property values processing halted at loop iteration 2 (run failed)

any help much appreciated.

A: with open('path_to_file', 'rb') as f:
    for line in f:
        if line.startswith('Error'):
            do_something_with_line(line)

You might also want to strip the line with line.strip().


text:
Q: How does tension apply a downward force parallel to mg? I was stuck on part "e" and my teacher told me that due to N1L the normal force is equal to the downwards force. So I thought that the downwards force would be the sum of the weight of the system which is the normal force. However he said that it is actually the weight of the stand  and pulley plus tension1 and tension2. My question is how and why on earth does the tension contribute to the downwards force. It is a internal force so it is not even act on the system.

A: It depends on how you define the system.  If the system is the pulley and stand, then tension is an external downward force, and the mass of the system is the mass of the pulley plus the mass of the stand.
If the system is the pulley, stand, and masses, then tension is an internal force, as you say.   In that case the mass of the system is the mass of the pulley plus the mass of the stand plus the masses of the two hanging weights.

A: If you make FBD of pulley you will find that tension1 and tension2 acts downwards on it
You can understand it easily if you consider that since the weight of the 2 loads are supported by pulley hence by newtons third law of motion pulley will experience equal and downwards force due to blocks

A: According to your question why and how tension contributes to the downward force?? Yes the answer is that hence in a system like pulley a tension is force that must be to balance with weight mg in order a body to undergo acceleration! But there some internal force like friction force your question don't specify!!


text:
Q: Java regex - Not Coloring on target My Question Based from here
I got an answer :
Matcher komen=Pattern.compile(pattern).matcher(source.getText());
while(komen.find())
{
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Background, randomColor);
    aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Concolas");

    source.select(komen.start(), komen.end());

    source.setCharacterAttributes(aset, false);
}

but, it's not coloring on target.
for example, here my pattern.
1. Pattern.compile("package").matcher(paket.group());
2. String getPack=Pattern.compile("(package\\s+)|(\\/\\/.*)|(;)").matcher(paket.group()).replaceAll("");
   Pattern.compile(getPack.replaceAll("\\s", "")).matcher(paket.group());
3. Pattern.compile("import").matcher(impor.group());
4. Pattern.compile("pustaka").matcher(impor.group());
5. String getPack=Pattern.compile("(import\\s+)|([\\w$*]+\\s*;)|(\\/\\/.*)|(\\s)").matcher(impor.group()).replaceAll("");
   Matcher getPackage=Pattern.compile(getPack.replaceAll("\\.$", "")).matcher(impor.group());

here my result :


text:
Q: why is SQL CASE returning both true and false? I'm hitting a baffling issue in SQL. Somehow, a JOIN in a CASE statement is returning both TRUE and FALSE!
If you run the below (I'm using SQL Server 2008), you'll see the effect. The JOIN creates 2 records, based on the CASE statements.
Any ideas how to stop this?
CREATE TABLE #table1(id int PRIMARY KEY, fieldA nvarchar(MAX))
    INSERT INTO #table1
    SELECT 1, 'ABC Airlines'

    CREATE TABLE #table2(field_id int PRIMARY KEY, fieldB nvarchar(MAX))
    INSERT INTO #table2
    SELECT 1, 'ABC Airlines'
    UNION
    SELECT 2, '*** OTHER ***'

    SELECT  *
    FROM    #table1 t
    JOIN    #table2 t2 ON t2.fieldB =  CASE WHEN t.fieldA <> t2.fieldB THEN '*** OTHER ***' ELSE t.fieldA END

A: It seems that you are using #table2.fieldB as a JOIN condition, so you are getting 2 values ('ABC Airlines' and 'Other'). Your expected result can be achieved if you change your query this way
SELECT  *
FROM    #table1 t
JOIN    #table2 t2 ON t.fieldA = CASE WHEN t.fieldA <> t2.fieldB THEN '*** OTHER ***' ELSE t2.fieldB END

A: When you will insert data into #table1 & #table2 then your tables will look like below
table1
id  fieldA
1   ABC Airlines
table2
id  fieldB
1   ABC Airlines
2   * OTHER *
Now when you are joining both table your where condition says that if fieldA not equal to fieldB then '* OTHER ' otherwise fieldA, so as a result when ABC Airlines<> OTHER  then you are passing  OTHER * as a substitute while joining. So for both rows data will match and you will get both result. Please change case condition based on your requirement

A: why wouldn't you want:
SELECT  *
FROM    #table1 t
JOIN    #table2 t2 ON t.fieldA =  t2.fieldB

It is a bad practice to use case statements and inequalities in joins. Based on your end result desired all you want is an ordinary inner join.

A: Why not just do this?
SELECT  *
FROM #table1 t JOIN
     #table2 t2
     ON t2.fieldB = t.fieldA OR t2.fieldB = '*** OTHER ***' ;

The only time this is not equivalent to your logic is when fieldA is NULL, but that doesn't seem to be an issue with your data.
My guess is, however, is that you want the '* OTHER *' value when there is no match at all.  That is no what your logic would do.  If that is the case, then apply solves the problem:
select *
from #table1 t apply
     (select top 1 t2.*
      from #table2 t2
      where t2.fieldB = t.fieldA or t2.fieldB = '*** OTHER ***'
      order by (case when t2.fieldB = t.fieldA then 1 else 2 end)
     ) t2;


text:
Q: Finding the constant of gravity in a game Minecraft is a game of mining where one digs and finds ore (to put it simply). the world is composed of "blocks" 3 dimensional cubes that have different "pictures" on them, that make them appear like grass or rock or Steele or diamonds...ect. In minecraft there is also TNT which is a block just like all others except it explodes. That does not relate to the question however which is, How do i find the gravitational constant? I mostly need the formula, which my 10th grade physics class has not taught me yet so i can find the neccesary factors to solve it. Aside from just giving me the formula what ways do you think I could find G? Also, just for more info, most block dont fall but sand and gravel do so they could be key to this problem perhaps.

A: Just use the free-fall equation. The time spent in falling from a height $ h $ verifies this:
$ h - \frac{g}{2} t^2 = 0 $
So you get:
$ g = \frac{2h}{t^2} $
Note that you have to determine the height $ h $. How?, maybe you can estimate it thinking that the game's character is about 1.80 m.
The $ g $ you are obtaining here is the acceleration of the gravity. In order to get the "universal" gravity constant for the game's universe, $ G $, you'll need to know, or at least estimate, the mass of the planet and the radius of the planet... or the ratio $\frac{M}{R^2}$


text:
Q: Object doesn't support this property or method I am essentially trying to match a series of cells from 2 worksheets and obtained values from a corresponding column.
When I run this code, I get an error:

object doesn't support this property or method

My Code
Sub Macro2()

Dim rowcount As Integer
Dim target As Variant

rowcount = Range("E2", Range("E2").End(xlDown)).Count
For i = 1 To rowcount + 1
    target = Application.Match(ActiveSheet.Cells(i, 6) & "-" & Cells(i, 5) & "-" & Cells(i, 4) & "-" & Cells(i, 3), Worksheets(14).Range("A6:A3000"), 0)
    If ActiveSheet.Cells(i, 6) & "-" & Cells(i, 5) & "-" & Cells(i, 4) & "-" & Cells(i, 3) = _
        ActiveSheet.Cells(i + 1, 6) & "-" & Cells(i + 1, 5) & "-" & Cells(i + 1, 4) & "-" & Cells(i + 1, 3) Then
        ActiveSheet.Cells(i, 17) = Worksheets(14).target.Offset(0, 10)
    End If
Next i

End Sub

A: If you want to find the Row count, you need to use the syntax:
rowcount = Range(Range("E2"), Range("E2").End(xlDown)).Rows.Count , also it's better to use Long than Integer.
Also, you need to trap a possible error when unable to find a successful match with the Application.Match function, do it by using If Not IsError(target) Then.
Note: try to avoid using ActiveSheet, instead use fully qualified worksheet, by using Worksheets("YourSheetName") in your code.
Code
Sub Macro2()

Dim rowcount As Long
Dim target As Variant

rowcount = Range(Range("E2"), Range("E2").End(xlDown)).Rows.Count
For i = 1 To rowcount + 1
    target = Application.Match(ActiveSheet.Cells(i, 6) & "-" & Cells(i, 5) & "-" & Cells(i, 4) & "-" & Cells(i, 3), Worksheets(14).Range("A6:A3000"), 0)
    If Not IsError(target) Then ' successful Match
        If ActiveSheet.Cells(i, 6) & "-" & Cells(i, 5) & "-" & Cells(i, 4) & "-" & Cells(i, 3) = _
            ActiveSheet.Cells(i + 1, 6) & "-" & Cells(i + 1, 5) & "-" & Cells(i + 1, 4) & "-" & Cells(i + 1, 3) Then
            ActiveSheet.Cells(i, 17) = Worksheets(14).target.Offset(0, 10)
        End If
    Else
        MsgBox "Unable to find a Match !"
    End If
Next i

End Sub

A: target is not a Property or Method of a Worksheets object.
I believe you need to change Worksheets(14).target.Offset(0, 10) to Worksheets(14).Range("A5").Offset(target, 10).

You should also be consistent in your coding.  In your code you have things like ActiveSheet.Cells(i + 1, 6) & "-" & Cells(i + 1, 5) ..., where you specifically qualify Cells(i + 1, 6) to be on ActiveSheet but allow Cells(i + 1, 5) to default to being on the ActiveSheet.  Although it works, it will get very confusing if you ever need to reread your code later on.


text:
Q: Wrap part of text into new element tag I have a text into a  tag. I want wrap part of that text into another element tag with an ID which is not in the base HTML code.
Since I cannot modify the base HTML code, I'm forced to use JavaScript/JQuery to do so.
I have this HTML code:
John<input type="hidden" name="firstname" value="John" id="my_input1">

Smith<input type="hidden" name="lastname" value="Smith" id="my_input2">

I want to add an  tag with ID to the texts within that span. The text I want to wrap is dynamic so I cannot use the value inside as such to search for it and target it. The HMTL code should look as shown below after the JavaScript/JQuery code is applied:
John<input type="hidden" name="firstname" value="John" id="my_input1">

Smith<input type="hidden" name="lastname" value="Smith" id="my_input2">

Sounds simple but I haven't been able to achieve it.
I will need to target those newly added IDs for something else later on.
I appreciate your replies.

A: Use jquery's .contents() to get the contents of your . Then filter to only text nodes (nodeType of 3). Then loop through each, and wrap it with an  tag if it is not empty. (If you don't perform the trim and empty check, you'll end up with  tags for any newline characters inside your span).
See the working example below.

$(document).ready(function() {
  var count = 0;
  $('#my_span').contents()
    .filter(function() {
      return this.nodeType === 3
    })
    .each(function() {
      if ($.trim($(this).text()).length > 0) {
        $(this).wrap('');
      }
    });
});

  John<input type="hidden" name="firstname" value="John" id="my_input1">

  Smith<input type="hidden" name="lastname" value="Smith" id="my_input2">

A: Have another  element with a know ID around your text by default.
John

Now change the element type dynamically
var currentText = $("#name_1").innerHTML;
 $("#name_1").replaceWith('' + currentText + '');

You can change an index suffix in the id within a loop if you have a series of inputs like this.

A: Try using .map() , Array.prototype.forEach() , .html() , .replace()

$("#my_span").map(function() {
  // split new line character of `#my_span` `.textContent`
  var txt = this.textContent.split("\n").filter(Boolean);
  // iterate each `txt`
  txt.forEach(function(val, index) {
    $(this).html(function(_, html) {
      // replace `val` with `a` element
      return html.replace(val, $("", {
        "text": txt[index],
        "id": "added_a_tag" + (index + 1),
        "href": "#"
      })[0].outerHTML)
    })
  }.bind(this))
})

John<input type="hidden" name="firstname" value="John" id="my_input1">

Smith<input type="hidden" name="lastname" value="Smith" id="my_input2">


text:
Q: Shade Matrix Plot in R I'm trying to create a shade plot in R, like the ones you can make in PRIMER like this one: Shade plot made in PRIMER
Are there any packages or functions that could do this in R?
Thanks!

A: Seems you are looking for a geom_tile from the ggplot2 package.
Example Data
library(tidyverse)

df  <- structure(list(`Sampling Location` = c("A", "A", "A", "B", "B",
"B", "C", "C", "C"), Taxa = c("X", "Y", "Z", "X", "Y", "Z", "X",
"Y", "Z"), value = c(1, 0.3, 0.1, 0.8, 0.4, 0, 0.6, 0, 0.1)), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

Plot
ggplot(df) +
  geom_tile(aes(x = `Sampling Location`,  y = Taxa,
                fill = value)) +
  scale_x_discrete(position = "top") +
  labs(title = "Untransformed")

Plot


text:
Q: Dropdowns registering clicks in wrong place on mobile. Why? I have a calorie calculator working here:
https://www.padthaiwokbar.com/Calorie/Hun/
Thing is, it works fine, but when I try to filter on a calorie with an iphone 6 / 6 plus, it registers my click events in the wrong place. Meaning I can't unfilter my diet preferences.
Any idea as to what might be causing this?

A: I've had a little look into your code and my first suggestion would be using
event.preventDefault();

inside your .diet-filter-button on click function because the dropdown menu items are anchor tags.
Hope this helps. P.s. I really like the visual design!
EDIT: Please see comments - the solution was actually CSS related, due to  :hover being triggered by touch/click events on mobile devices.


text:
Q: Need solution for redirecting the users to the site after credit card payment through Paypal I am using Paypal plugin in my virtuemart 2.0.8 for Joomla 2.5. When any user is making payment via credit card, after completion of their payment they are getting option to create their Paypal account or a link is given to redirect to mysite.com and the user gets stuck there.
How will the credit card user get redirected automatically to my site once the payment is made? Please advice.

A: I think the standard PayPal plugin only uses the basic PayPal service which doesn't "automatically" return the user to the merchant, it just presents them with the link to click.
I believe you would have to use PayPal Pro (which keeps the user on your site) — looking at the Virtuemart Extensions directory there is a PayPal Pro plugin.
By the way you really should update your Virtuemart installation as there have been dozens of bug fixes since 2.0.8.

A: When you are using Paypal payments standard, it's a hit or miss situation. If the user does not log in to their Paypal account to make the payment, then they cannot be automatically redirected after they finish the transaction, they best they can do is click the link.
If they do log in, then you can redirect them, but you have to set it up in your Paypal account. Details here - https://www.paypal.com/cgi-bin/webscr?cmd=p/mer/express_return_summary-outside
Also, @cppl is correct, you need to update your site, particularly when you do e-commerce. The most common reason sites are hacked is out of date extensions or Joomla. Keep everything updated, it's easy insurance to keep your site safe.


text:
Q: How to launch email client from my app in such a manner that I could see inbox, sent items etc When I launch email client from my application, a compose window of email client gets opened but when I launch like this, I am unable to see inbox, sent items etc...
In short how to launch email client from app exactly like launching from desktop?
Any suggestions will be appreciated.

A:
in short how to launch email client from app exactly like launching from desktop..

There is no standard Intent for this, sorry.

A: you can try this from your activity object:
it will not necessarily take you to the Inbox directly but it will open the email application:
Intent intent = getPackageManager().getLaunchIntentForPackage("com.android.email");
startActivity(intent);

Samer Alameer

A: Just in case anyone else gets here with the same question, there is a solution.
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.google.android.email/com.android.email.activity.Welcome"));
intent.addCategory("android.intent.category.LAUNCHER");
startActivity(intent);

You can get the component name from LogCat. The only problem is, I think, if the user uses another application for email.


text:
Q: How to get a second specific word inside a string in PHP Hey guys so I have a question,
Lets say someone puts "Hi lets have #fun and than more #fun" Now lets say I want to grab the second hashtag including the word connected to it and store it into a variable.
How would I go about getting the second part because using (strpos($a,'#fun') would only return the first one.
Thank you for your time!
David
Edit:
Here's what I did:
$code = "Hi lets have #funfgs and than more #funny";
$pos1 = strpos($code, '#');
$pos2 = strpos($code, '#', $pos1 + strlen('#'));
echo substr($code, $pos2);

A: You can use following Regular Expression
$code = "Hi lets have #fun and than more #fun";

$pattern = "$#[^\s]*$i";

preg_match_all($pattern, $code, $matches);

print_r($matches);


text:
Q: Multiple Tables for one Django Model How can I dynamically create multiple tables for one specific model?
I have a model (e.g. "Data") and want each user to get a separate database table for this model.
There will be between 30 and 40 users, each with about 20 million entries in "Data". So that the database table does not get 800 million rows, I would like to split it.
Of course, it is also possible that there will be more in the future
Is this still possible with Django ORM?
I'm on PostgreSQL
Thanks :)

A: For a strict requirement, I had to go through this. I will just leave my solution here for future reference.
After User creation, let's say we want to create a "user_data_100" table with model "UserData" with pgsql database.
Note: here "100" is the "User" model(table entries) primary key value.
in app/model.py create the user model.
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.db import connection
from django.contrib.auth.models import User

class UserData(models.Model):

    class Meta:
        pass

    dt_column_one = models.CharField(max_length=10,)
    dt_column_two = models.CharField(max_length=5,)

def create_model_by_prototype(model_name, schema_name, tbl_name, prototype):
    import copy
    class Meta:
        pass
    setattr(Meta, "db_table", schema_name + "\".\"" + table_name)
    fields = {}
    for field in prototype._meta.fields:
        fields[field.name] = copy.deepcopy(field)

    attrs = {'__module__': "app.models.models", 'Meta': Meta}
    attrs.update(fields)
    model = type(model_name, (models.Model,), attrs)

    return model

Note: function "create_model_by_prototype" will generate a model with given table name.
Now let's use the function. I assume the user will get created from the admin site. Let's create a post_save function to create UserData table.
@receiver(post_save, sender=User)
def create_user_data_table(sender, instance, *args, **kwargs):
print('User post save')

if kwargs['created']:
    user_id = instance.id
    dy_table_name = "user_data_" + str(user_id)
    model= create_model_by_prototype("MyUserData", "public", dy_table_name, UserData)
    with connection.schema_editor() as schema_editor: schema_editor.create_model(model)
else:
    print('updated')

hope this works for you. Thanks.


text:
Q: SoundPool doesn't play sounds When I try to start a sound in my application it doesn't play. I have seen that the method does get called however soundPool just doesn't want to play the sound. The app starts as intended, however, it just doesn't want to play the queued sound. Is it something I am doing wrong? is the music file I am trying to play just too large? (35.4MB)
Any input is appreciated!
StartActivity (relevant bit)
public class StartActivity extends AppCompatActivity {
    private Button startButton;

    //Sounds
    private SoundManager soundManager;
    private int ambient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_activity);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        startButton = (Button) findViewById(R.id.startButton);

        //Setting Up sounds
        soundManager = new SoundManager(this);
        ambient = soundManager.getSoundID(R.raw.music_ambient);

        soundManager.playLoop(ambient);
        Application.setSoundManager(soundManager);

Application

public class Application {
    public static SoundManager soundManager;

    public static SoundManager getSoundManager() {
        return soundManager;
    }

    public static void setSoundManager(SoundManager soundManagerIns) {
        soundManager = soundManagerIns;
    }
}

SoundManager class

import android.content.Context;
import android.media.SoundPool;
import android.util.Log;

public class SoundManager {

    private Context context;
    private SoundPool soundPool;
    private boolean isPlaying = false;

    SoundManager(Context context) {
        this.context = context;

        SoundPool.Builder builder = new SoundPool.Builder();
        builder.setMaxStreams(10);
        soundPool = builder.build();
    }

    int getSoundID(int resourcesID) {
        return (soundPool.load(context, resourcesID, 1));
    }

    void play(int soundId) {
        soundPool.play(soundId, 1, 1, 1, 0, 1);
    }

    void playLoop(int soundId){
        if(!isPlaying) {
            Log.d("LEADER", "called this");
            soundPool.play(soundId, 1, 1, 1, -1, 1);
            isPlaying = true;
        }
    }

    void stop(int soundId){
        isPlaying = false;
        soundPool.stop(soundId);
    }
}

A:
is the music file I am trying to play just too large? (35.4MB)

That might be the case. I have seen several StackOverflow answers (including recent ones) that claim that the uncompressed in-memory limit per sound is 1 MB for SoundPool, though I haven't been able to check that in the official documentation. If it is indeed the case, you might be able to see this error in your log as described by https://stackoverflow.com/a/18548242/9543944 :

If your clip is too big in memory, sound pool will fall silent, and you'll find following error: "AudioFlinger could not create track. status: -12"

You should be able to see the log from inside Android Studio, and you can then filter for errors to more quickly search for the above error.
If this is indeed the case, MediaPlayer might be a good alternative: https://developer.android.com/guide/topics/media/mediaplayer .


text:
Q: Webservice delete error Estou com um problema no meu webservice. Está dando esse erro:

SolicitaçãoFailed RequestFailed --> Status: (405)

O código que estou utilizando:
@DELETE
@Produces("text/plain")
@Path("ExcluirLista/{usuario}")
public boolean excluirTodos(@PathParam("usuario") String usuario)
{
    ProdutoDAO dao = new ProdutoDAO();
    return dao.excluir(usuario);
}

public boolean excluir(String usuario)
{
    String sql = "delete * from listaproduto where uclogin=?";
    Boolean retorno = false;
    PreparedStatement pst = Conexao.getPreparedStatement(sql);
    try {
        pst.setString(1,usuario);
        if(pst.executeUpdate()>0)
        {
            retorno = true;
        }
    } catch (SQLException ex) {
        Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);
        retorno = false;
    }
    return retorno;
}

A: O erro 405 é o Method not allowed. Este erro indica que houve uma requisição em uma determinada URL utilizando-se de um verbo HTTP que não era o adequado.
O @DELETE deixa bem claro que a requisição deveria ser feita por meio do método HTTP DELETE. Se este erro foi produzido, é porque algum outro método HTTP (tal como POST) foi utilizado em seu lugar.

E embora não seja o que você perguntou, é possível melhorar o seu código assim:
@DELETE
@Produces("text/plain")
@Path("ExcluirLista/{usuario}")
public void excluirTodos(@PathParam("usuario") String usuario) {
    ProdutoDAO dao = new ProdutoDAO();
    dao.excluir(usuario);
}

public void excluir(String usuario) {
    String sql = "delete * from listaproduto where uclogin = ?";

    try (PreparedStatement pst = Conexao.getPreparedStatement(sql)) {
        pst.setString(1, usuario);
        if (pst.executeUpdate() == 0) throw new RuntimeException();
    } catch (SQLException ex) {
        Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException(ex);
    }
}

Não use booleans para indicar erros, isso é uma má prática de programação. As exceções foram concebidas exatamente para que os programadores não tivessem que fazer isso, e portanto aproveite-se desse recurso que a linguagem te oferece.
E nunca deixe PreparedStatements abertos por aí a toa. A melhor forma de gerenciá-los é por meio do try-with-resources.


text:
Q: Windows Forms: How to extend a button? How can I extend a Button?
I want a Button that has an additional property IsSwitchOffable.
Do I have to write an extra custom control?
EDIT:
I want that the button is usable as a standard WindowsFormsButton.
This includes that I can add the button at design time!

A: Extending a button control is no different then extending any class in C#. Simply do the following:
class ToggleButton : Button {
// Add your extra code
}

A: You need to create a class that inherits the System.Windows.Forms.Button class and adds your property and associated behavior.
After compiling your project, your new class will appear in the toolbox.

A: I know this is old and has been answered - however,
Why make life difficult?
Each control has a Tag property which you can easily set to IsSwitchedOffable - or better English CanBeDisabled
Far easier.

A: In my puzzle application 2d button's location is to be changed... So i need extra facilities...
My button ButObj  extends Button class
Public Class ButObj : Button
         {
            Point initloc;
          Public ButObj(Point loc)

 {   this.Location=initloc=loc ;   }
           Public bool isNearto(ButObj X)
               {
                 if (this.Location.X==X.Location.X || this.Location.Y==X.Location.Y)
                   return true;
        else  return false;
               }
           Public bool isSettled()
             {
                if(this.Location==initloc)
                   return true ;
                else return false;
             }
         Public void Replace (ButObj X)
     {
           Point temp ;
             temp=this.Location;
       this.Location=X.Location;
    X.Location=temp;
    }
         }

Following code is written in form 1_load ()
ButObj[ ][ ] B=new ButObj[4][4];
   char c='A';
    for (int i=0;i<4;i++)
      for (int j=0;j<4;j++)
       {   B[i][j]=new ButObj(new Point (i*100+10,j*100+10));
B[j][i].Text = ""+c++;
B[i][j].Font =new Font ("Arial", 24);
this.Controls.Add (B[i][j]);

B[i][j].MouseClick += new MouseEventHandler(MouseClick); }
Coding in mouse click event
private void MouseClick(Object sender, EventArgs e)
    {
       ButObj b=(ButObj)sender;
       if (b.isNearto(B[3][3]))
         b.Replace(B[3][3]);
\\ checking after replace
     if(AllSolved());\\game over
     }

bool AllSolved()
      {
         for (int i=0;i<4;i++)
           for (int j=0;j<4;j++)
             if (!B[i][j].isSettled)
               return false ;
        return true;
      }


text:
Q: Use jQuery to Output JSON from PHP Page I have a PHP page that outputs some JSON. After the page loads, I would like to output the JSON using jQuery AJAX. However, nothing is happening. The alert() dialog isn't appearing and it doesn't work with the JavaScript console, either. What is wrong with my jQuery AJAX call?
<script type="text/javascript">
jQuery.ajax({ url: 'http://www.domain.com/page.php',
    dataType: 'json',
    success: function(data) {
        var obj = jQuery.parseJSON(data);
        alert(obj.json_array[0]);
        alert(obj.json_array[1]);
        alert(obj.json_array[2]);
    }
});
</script>

The PHP is:
<?php
$array = [
    'foo' => 'bar',
    'bar' => 'foo',
    'int' => 4
];

$json_array = json_encode($array);
echo $json_array;
?>

A: In PHP, you can have arrays where each element has a key and a value, but once you parse it in javascript, that becomes an object. So using [0], [1], or [2] is invalid. You must use foo, bar, or int. Also, when you echo a string, the name of the variable that holds the string is not saved in any way. The only thing saved (echoed) is, well, the string. In your example, echo $json_array; echoes {"foo":"bar","bar":"foo","int":4}, and when it is parsed, you get an object. So you don't need to say obj.json_array, you just say obj. So to fix your issue,
Replace
alert(obj.json_array[0]);
alert(obj.json_array[1]);
alert(obj.json_array[2]);

with
alert(obj.foo);
alert(obj.bar);
alert(obj.int);


text:
Q: Facebook Messenger API can't send attachments I'm trying to send an attachment via the Facebook API using Python Requests, but I keep getting the following error:
"message":"(#100) The parameter recipient is required"

My code is:
import requests

url = "https://graph.facebook.com/v6.0/me/messages?access_token=<API_TOKEN>"

headers = {
    'Content-Type': 'multipart/form-data;'
}
payload = {
    'recipient': {"id": user_id},
    'message': {
        "attachment": {
            "type": "image",
            "payload": {}
        }
    },
}
files = {
    'filedata': open('C:/Users/user-pc/Downloads/duck.jpg', 'rb')
}
response = requests.post(url, headers=headers, data=payload, files=files)

My code is based on the following two links:
https://developers.facebook.com/docs/messenger-platform/send-messages/#file
https://developers.facebook.com/docs/messenger-platform/reference/attachment-upload-api/
Note: I did manage to send using CURL and through Postman.
On a secondary note, is it possible to send an attachment using just the byte string of the attachment? That is instead of needing the actual path to the file, how would I do this on a server environment?

A: Using https://webhook.site/ I was checking what I was sending through to Facebook and I found out that it was not actually processing the Key-Value pair in my dictionary properly. So through some experimenting, I found that you need to make use of Tuples, not entirely sure why, if anyone can explain that would be much appreciated.
import requests

url = "https://graph.facebook.com/v6.0/me/messages?access_token=<API_Key>"

payload = {
    'recipient': (None, {"id": user_id}),
    'message': (None, {"attachment": {"type": "image", "payload": {}}}),
}

files = {
    'filedata': ('duck', open('C:/Users/user-pc/Downloads/duck.jpg', 'rb'), 'image/jpg')
}

response = requests.post(url, data=payload, files=files)

print(response.text.encode('utf8'))

The headers aren't really necessary as well it seems, as the Requests library seems to handle it automatically.
As @CBroe mentioned, the path doesn't really matter, as it will just read the binary data anyways.


text:
Q: Service accessing a database Ok guys, I did ask before on how to create a way to run a code always in my app. It's similar to how say iMobeter or something like that check your hp, if it's less than max it'll add to it every 5 mins.
Some people told me to use service which sounded good. Problem is, I need a service that is always running in the background. Plus, I could not create a service that can access the database. I cant use the cursor there as in it does not support the method.
I would appreciate pointing me to a good example or a better way to do it.

A:
Problem is, I need a service that is always running in the background.

That is not possible. Users can stop your service whenever they want, and Android will stop your service if it lives too long.

Plus, I could not create a service that can access the database. I cant use the cursor there as in it does not support the method.

Yes, it does. Use SQLiteOpenHelper, the same way you would with an activity, content provider, etc.


text:
Q: Learning Core Data. Entities, Adding and Loading So, I'm trying to use Core Data to save instances of a "Screenshot" class, which consist of:
NSString *note;
NSData *screenshot;
NSData *thumbnailOfScreenshot;
NSTimeInterval date;

In my Core Data file, i have two entities because i want to fetch the large images only when necessary, and only 1 at a time (it is to be used in a UITableView).
Entity 1 is called Screenshot and consists of the 4 attributes above, whereas the *screenshot is transient. This entity also has a to one relationship with entity 2(an int called index).
Entity 2 only has 1 attribute which is a Binary data field for the Large images. Also a to one relationship with entity 1.
So, my first question: Is this remotely close to being correct? I'm a little unsure if i even need the Transient attribute "screenshot", in entity 1. And i am also confused if i need to create a new class for entity 2, which seems abit odd, since it will just contain the images.
For now, I'm only trying to add and load instances to and from the DB.
Here is how i (think) i add an instance to the DB, but i am not sure it actually puts it in the DB right away?:
Screenshot *s = [NSEntityDescription insertNewObjectForEntityForName:@"Screenshot" inManagedObjectContext:context];

I am in over my head, so any help will be appreciated. I have read several guides, but none was targeting something similar to this.

A: Transient properties are not saved to Core Data (they are neither retrieved nor saved out from the backing store). They are most often useful for calculating some sort of property based on stored properties (e.g. I use them for queries based on the first letter of a person's last name -- I'm storing the full last name, but the firstLetterOfLastName is a transient property -- but one that I can order results on since Core Data knows about it).
If I'm understanding your model correctly, you likely want no transient properties at all.
I also don't think you need an entirely new model for your "large images". You can instruct Core Data to optimize it's backing store for large binary attributes by turning on "Store in External Record File". You'll find this in the Data Model Inspector pane underneath where Transient and Optional are set. This will keep the actual backing DB snappy, but allow Core Data to retrieve these large binary attributes and you may still work with them seemlessly with a Core Data NSManagedObject instance.
Also, in general, do not relate items by an "index" value of some other stored Core Data object. There's plenty of reasons to do so, but in general, this is  what Core Data relationships are for. If "Movie" has multiple "Screenshots", for e.g, you would have a relationship on a Movie instance called "screenshots" that you simply add each screenshot to (it's effectively an NSMutableSet as far as you care).
Core Data is an object graph, not a relational database. If you add the same object instance to two relationships on different owner-object instances, you aren't duplicating the child-object -- Core Data does all the work to interrelate them for you (assuming your models are setup in a good way).

A: I'd rethink this. I think a single entity is enough for this. I'd either add a BOOL value named 'large' and do a fetch when "large = NO" to get the small images. Alternatively, if you want more control, add a 'pixels' or 'megapixels' field which describes the size of the image. Then you can fetch where 'pixels > 3000000' for instance.
If you have a special relationship between two images (i.e. one image is a thumbnail of another), I'd just add a relationship to another Screenshot entity.
Alternatively, you could also make one Entity the "Parent Entity" of the other (see the Data Model inspector when you have an entity selected).
You're on the right track. Keep thinking about how you want to use your entities. This should help you describe the relationships better. Quite often I write the code that uses the entities before I define them in a data model. This lets me end up with cleaner interfaces and less overlap between entities.


text:
Q: URL Rewriting in Asp.net 2.0 and IIS 6 I have read numerous articles/forum posts on this topic and I have yet to find a solution that would work for me (or maybe I'm not understanding them correctly). I'm trying to implement URL rewriting on an existing website to make more "SEO friendly" URLS.
The current URL structure is: http://www.website.com/campgrounds/CampgroundDetails.aspx?CampgroundId=xxxx
I grab the CampgroundId from the query string and pull the data from SQL.
Is there a way to still use these URLs, but have them appear to the user like: http://www.website.com/campgrounds/country/state/campgroundname.aspx
Country/State/CampgroundName would be pulled from our SQL database
Any help would be greatly appreciated!


text:
Q: C++ Static Variable in Class I want to have static variables in a C++ class (const if possible). How can I set their value? I want them to be dynamically allocated.
Here is my class:
class Color
{
public:
    static int* BLACK;
    static int* WHITE;
};

I have done this, which seems to be working fine:
int* Color::BLACK = new int[3];
int* Color::WHITE = new int[3];

But how do I set their value after that? And is it possible to make them const?

A: It's probably better to not have colors dynamically allocated in the first place because it'll prevent the compiler from being able to do various optimizations. Ideally:
class Color
{
public:
  static int const BLACK[3];
};
int const Color::BLACK[3] = {0,0,0};

However if you do want them on the heap then it depends on whether you want the pointer to be const, the values const or both!
If you want the pointer and values to be const then you may have to do this:
class Color
{
public:
  static int const * const BLACK;
};
int const * const Color::BLACK = new int[3]{0,0,0};

To be honest I am unsure of what context would demand the pointer and allocation. It seems unnecessary.
EDIT: For a pre-C++11 compilers you could do something like this:
int * make_black()
{
  int * color = new int[3];
  color[0] = color[1] = color[2] = 0;
  return color;
}

class Color
{
public:
  static int const * const BLACK;
};
int const * const Color::BLACK = make_black();


text:
Q: How to add hours and minutes to ajax request sent from p:calendar primefaces widget? I am trying to use p:calendar widget with hours and minutes selector from primefaces framework.
<p:calendar id="dateSel" pattern="dd.MM.yyyy HH:mm" converter="ruDateConv"
showOtherMonths="true" selectOtherMonths="true"
mode="inline" locale="ru" value="#{model.date}">
    <p:ajax event="dateSelect" listener="#{model.onDateSelect}"/>
</p:calendar>

Hours and minutes selectors showing ok, but there is no hours and minutes parameter in ajax request (I'am using wireshark to monitor raw tcp). Only date sent. Thus, I cannot get the hours and minutes on the server side.
My converter:
@FacesConverter(value="ruDateConv")
public class RuDateConverter implements Converter {

    private static Logger logger = LoggerFactory.getLogger(RuDateConverter.class);

    private SimpleDateFormat df = new SimpleDateFormat("dd.MM.YYYY HH:mm");

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
        logger.debug("Try to convert {}", string); //there is no hours and minutes in log
        Date d = null;
        try {
            d = df.parse(string);
            return d;
        } catch (ParseException ex) {
            logger.error("Can't convert "+string, ex);
            throw new ConverterException("Can't convert "+string);
        }
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
        logger.debug("Convert {}", o);
        return df.format((Date)o);
    }

}


text:
Q: Can a executable behave differently when run on a Virtualized Server? Let's say I have a piece of code that runs fine on an OS. Now, if I install that OS on a virtual machine (server virtualization), and run that code on that, is it possible that the code behaves differently?
If so, what are the prerequisites for that? For example, does it have to be compiled machine code (in other words, are interpreted languages safe?)? Does it have to be certain OS instructions? Specific virtualization technology (Xen, KVM, VMware..)?
Also, what are the possible different behaviors?

A: Yes. Like any machine, the virtual machine is just another computer (implemented in software instead of hardware).
For one, lots of commercial apps will blow up when you run them on a VM due to:

*

*copy protection detecting the VM

*copy protection rigging your hardware, using undocumented features of BIOS/Kernel/hardware

Secondly, a VM is just another computer consisting of hardware implemented in assembly instead of circuits/dye/microcode/magic. This means the VM must provide the emulated hardware either through pass-through or emulation. The fact that hardware is very diverse can cause all kinds of different behavior. Also note the possible lack of drivers for or acceleration of the emulated hardware.
But of course a typical business application for example isn't nearly as likely to rely on any hardware details as all it does is call some GUI API.
Interpreted languages are only safe from this to the extent that they are "interpreted", if the interpreted language calls out to some native code, all this is possible again.
For an example of something detecting that it's running under a VM, check this, it's just one of the literally thousands of ways to detect the VM.

A: In theory the program should run exactly the same as on a physical machine.
In practice however, there may be differences due to

*

*Machine\OS configuration and drivers

*Load of the virtual machine host.

Differences in machine configuration are similar to difference you would see between any difference physical machine.   Depending on how critical you application is to the end user, you should run the same set of tests that you would a physical box to determine whether the environment is acceptable for use.
Depending on the virtualisation technology, the host may not have the ability to guarantee the client resources at specific times.  This can lead to weird behavior on the client.  Potentially you would see more occurrences of application errors due to IO timeouts an starvation of memory.
To successfully virtualise an application for production use you need to do a bit of work to understand the resource profile of the application\client and virtual host.


text:
Q: loading respond.js async via modernizr.load is slow? I am using the Modernizr.load() method to test, whether the browser (ie) understands media queries or not, and if not I load the respond.js libary.
however, I see that loading the respond.js via the modernizr.load method gets me a FOUC, where the inline script method doesn't.
modernizr.load method:
<script>
  Modernizr.load([{
    load: 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
    complete: function () {
      if (!window.jQuery) {
        yepnope('js/libs/jquery.js?v=1.7.2');
      }
    }
  },
  {
    test: Modernizr.mq('only all'),
    nope: 'js/plugins/respond.js?v=v1.1'
  }])
</script>

inline method:
<!--[if lte IE 8]>
  <script src="js/plugins/respond.js?v=v1.1"></script>
<![endif]-->

why is that so? shouldn't be the async method faster? or is the inline method better, because the script is blocking the DOM and waiting until the script is loaded...?

A: It depends how much you care about the FOUC. The advantage to the async method is that it's non-blocking. I would switch it around so that Respond is first so that you don't have to wait for jQuery to be parsed. That'd probably solve the FOUC. Call Modernizr.load in your <head> (see here) like this:
Modernizr.load([{
    test: Modernizr.mq('only all'),
    nope: 'js/plugins/respond.js?v=v1.1'
  },{
    load: 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
    complete: function () {
        window.jQuery || Modernizr.load('js/libs/jquery.js?v=1.7.2');
    }
}]);

Your IE conditional is great solution too—arguably better. If you do that, then just put it before jQuery and you'll be fine:
<!--[if lt IE 9]>
    <script src="js/plugins/respond.js?v=v1.1"></script>
<![endif]-->

Modernizr.load([{
    load: 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
    complete: function () {
        window.jQuery || Modernizr.load('js/libs/jquery.js?v=1.7.2');
    }
}]);


text:
Q: Lost address book contacts in upgrade to Yosemite I upgraded from the Mavericks to Yosemite on a Macbook Pro. All the contacts in the address book which is now Contacts in Yosemite are gone and when I try to restore it from the back up it gives a message that all the contacts will be replaced which is ok in this case. However when I close the address book after the import and re open it the address have disappeared. After a few attempts it now gives the same message but now the contacts don't even show in the address book anymore. Is there a solution for this?
Thanks
Usman


text:
Q: In Rails 3.1 how can I check if any instances of a model's has_many association have changed? In Rails 3.1 I know you can check if a given instance of a model object can be changed, but how would I check if any instances of a model's has_many association changed.
For example assume I have an Order that has many LineItems. LineItems get added to an Order and I want to be able to check if any of the Order's LineItems has changed.  I suppose one way of doing it would be to loop through each of the LineItems in the Order model like so:
def line_items_changed?
  self.line_items.each do |item|
    if item.changed?
      return true
    else
      return false
    end
  end
end

but was curious if there was a built in or more efficient way.

A: Shorter solution:
def line_items_changed?
  line_items.any?(&:changed?)
end


text:
Q: Dual Ethernet controller Ubuntu I just got a server and it has dual ethernet ports.  Is the purpose of that to have one inbound and one outbound?  I've done some quick googling and didn't see any straight up configurations for it.  How do I set this up?
I'm running a PHP/MySQL server and I'm wondering if I can utilize these dual ports to allow my server to handle more traffic or something....

A: There's a lot of different ways to configure two ethernet ports. Off the top of my head you can use them for redundancy, doubling the throughput, different networks, and plenty more.
What exactly do you want to do??

A: You don't need to use both, you can only use one if you would prefer. If you aren't comfortable setting up bonding, I would just setup one and leave it be.


text:
Q: Replacing ItemsControl ContentPresenter entirely with control being rendered i'm using an ItemsControl to generate a list of controls based on my model.
When looking at the visual tree, i noticed that each of the rendered control is wrapped in a ContentPresenter.  The controls that are added are a 3rd party control and are designed to display a splitter between each control if they are siblings..this allows a user to size each control. For example the following will show a splitter between each of the controls at run time.
<StackPanel>
<3rdPartyControl />
<3rdPartyControl />
<3rdPartyControl />
</StackPanel>

When using an ItemsControl, each of the 3rdPartyControl are wrapped in a ContentPresenter, and thus no splitter is shown.  I have tried various ways to try and solve this problem but unable to get this to work unless i write code behind to add each control rather than rely on Xaml.
Does anyone know of a way to replace the contentpresenter completely (in my case with 3rdpartyControl)?
Thanks

A: In order to replace the ContentPresenter you could derive from ItemsControl and override the GetContainerForItemOverride method to create a specialized container control.
ListBox for example overrides this method to create a ListBoxItem as container for a new item object.

A: That's true, every element that you add to ItemsControl is wrapped with ContentPresenter, you can find more details about it in the greate series of articles from dr.wpf ItemsControl a-z
One way I would suggest to try is to change ItemsControl to ListBox and make ListBox act like ItemsControl. In this case you can re-style/re-template ListBoxItem and replace ContentPresenter with your control. You would also need to stop selection support. Here is ListBox style that you need to change.


text:
Q: MySQL groupwise maximum performance issues on a million row table I am trying to find a straightforward way to improve the performance for very active forums where there are a huge number of posts and mysql can no longer do table sorts in memory and doesn't seem to take full advantage of indexes.
This simple query finds the most recent post in each topic for a user to determine if they have any replies since (by later comparing the topic_time)
SELECT p.*, MAX(post_time) as post_time FROM forum_posts AS p
WHERE p.poster_id = '1' AND p.post_status = '0'
GROUP BY p.topic_id
ORDER BY post_time DESC
LIMIT 50

simple, flat table looks something like
post_id | poster_id | topic_id | post_status | post_time | post_text

However it's performance falls apart when there are a million posts and the user themselves have tens of thousands of posts. MySQL can either no longer sort the table in memory or there are far too many rows to scan. It can take up to 3 seconds in realworld use which is unacceptable imho because it's spiking the CPU during that time and slowing everyone else down.
I can make any combination of index of course, but mysql seems to mostly like to use  a combo of
poster_id + post_time

So it just selects the one user's 50k posts out of the million and then starts grouping by topic_id and sorting. Strangely adding topic_id into the index mix doesn't seem to help the performance, though it may be the order of the index fields?
I've tried to write an equivalent JOIN instead so I can use more than one index but I run into problems with the fact that each side has to be filtered by post_status and poster.
I was thinking it would be faster, at least for the first few pages, if mysql could be made to FIRST sort the data via it's index by post_time and then start picking out the distinct topic_id for the user in descending order. I guess that would require a subquery and not sure a 50k result subquery would be any better, still needs a temporary table.
Of course a fundamental solution would be to augment the core design so that there is another table which just stores the max post_time for each user in each topic but this is far too big of a change unless no other solution can be found.
Thank you for any suggestions!

adding realworld example and EXPLAIN:
slow log
# Query_time: 2.751334  Lock_time: 0.000056 Rows_sent: 40  Rows_examined: 48286
SELECT   p.*, MAX(post_time) as post_time FROM forum_posts AS p   WHERE p.poster_id = '2' AND p.post_status = '0' GROUP BY p.topic_id  ORDER BY post_time DESC LIMIT 7000, 40;

explain
select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
SIMPLE          p   ref poster_time poster_time 4   const   27072   Using where; Using temporary; Using filesort

A: First, fix your query to provide determinate results:
SELECT p.topic_id,
       MAX(post_time) as post_time
FROM forum_posts AS p
WHERE p.poster_id = '1' AND p.post_status = '0'
GROUP BY p.topic_id
ORDER BY post_time DESC
  LIMIT 50 ;

Then try it after adding an index on (post_status, poster_id, topic_id, post_time).


text:
Q: Can't find ResourceDictionary to load in code I'm trying to load a ResourceDictionary object into code so that I can check if it contains a certain value before trying to bind to it, but for some reason it can't find the resource. It might be something basic, ie having the wrong build action or URI but can someone point me in the right direction?
The .cs file and the Images.xaml resource dictionary are both in the same folder and namespace
This is the code that is failing
ResourceDictionary resourceDictionary = new ResourceDictionary();
resourceDictionary.Source = new Uri("Images.xaml", UriKind.Relative);

Any idea what I'm doing wrong? getting error message
{"Cannot locate resource 'images.xaml'."}

A: The XAML parser probably adds an application authority when converting URIs, in code you may need to add that yourself. Build action should just be the default for ResourceDictionaries, whatever that may be.


text:
Q: 240V Mains - Current draw and when to use Solder vs Welding No specific application, just for interest - I opened up a multiplug/multiboard and noticed that all the contacts for welded (i.e. no solder).  I was just wondering if this had anything to do with current draw, and (if so) what's the upper 'safe limit' for solder - and when should you be thinking about using welds instead ?

A: It's more likely to do with manufacturing cost, multiplugs/boards are built down to a price. Once you're into manufacturing volumes, spot-welding is fast and can be automated.

A: There is not going to be some specific number here because it depends a lot on other aspects of the design besides just the solder joint.
The upper safe limit for a solder joint really depends on several factors.

*

*The geometry of the joint (length and cross section), which determines dissipated wattage at a specific current level.  Making the joint wider or shorter will reduce wattage and allow you to carry more current.

*The melting point of the solder.

*What paths the heat has to get out of the joint.

Typically solder joints have resistances in the range of micro-ohms and melting points of hundreds of degrees C.
For example,  Lead Free Solder Sn96 (SAC 305) has a resistivity of 13 micro-ohm-cm.
A joint made from this solder with a 100 mils x 100 mils cross section and thickness of 20 mils would have a resistance of only 10 micro ohms.
You would have to run 100A through it to generate even 0.1W of heat.


text:
Q: How to avoid duplication of headers when exporting CSV from SSRS I'm trying to export .csv from SQL Server Reporting Services 2012.
The output is like:

I want output like:
Header1 Header2
Data1   Data2
Data3   Data4

How can I achieve this?


text:
Q: How to disable blue selection on double click, in table header? I have followed table header structure:

       Some text

The problem is, when I double click on header link, the background is selected (blue color) and seems messy.
How to avoid this behavior?
Thanks,

A: You could use user-select:none, which will disable selection of the th element.
jsFiddle example - try highlighting the element.
th {
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

Support for this property can be found here.

If you are concerned about support, you could alternatively use ::selection to change the color from blue to transparent. This method has a little more support.
jsFiddle example - try highlighting the element.
th::selection {
    color:transparent;
}
th::-moz-selection {
    color:transparent;
}

It is supported in IE9. Reference here.


text:
Q: Migration from Android to Flutter implications I have taken time to to see that I get my hands on flutter ever since I started to hear of it from my fellow android developers. It has not been easy am glad am getting somewhere in terms of progress of earning flutter. I have began to rewrite one of my android project in flutter. However my greatest concern is that if I rewrite my android project in flutter and use the package name i used in the other project. Am using sqlite database in my project and it has been passed on from version to version as I have been updating my app and users like it that. However am not very sure if the migrating my project to flutter affect the users who were using my earlier application loose their data?
I need someone to enlighten me on how to handle such an issue if its not possible to maintain what was in my android project in terms of database. Or rather what options are available.

A: Play store cares about your apk, as long as your source code uses the same sql-lite cache, should be ok. You can easily test such scenario on the same emulator for instance.


text:
Q: Using a code without compiling it to a library My question may be silly, but I need to use a library from its source code without compiling it to a library form first. The tool in question is FreeType. Is this possible?

A: You can add all the files from the FreeType source distribution into your own project, and try to get them to compile alongside. However, the FreeType compilation procedure is a bit tricky, if I recall correctly.
It is probably easier to compile FreeType as a static library, then link your own program with the generated library. If you do that, your executable will have no dependency on the FreeType runtime library.

A: It's called bundling: instead of shipping your code with JAR files of some library, or even just requiring the library in your INSTALL document, you simply copy the source code into your project and have it built by your build system instead of using it pre-built. It may require adapting your build system a bit, and you need to make sure you have the right to redistribute the library in source form, but it can sometimes make sense.
MPlayer did this with ffmpeg for a long time, and XEN with the Linux kernel (notionally, they ship patches instead of the entire kernel tree). The disadvantage is, of course, that you effectively fork the library, and don't get any updates of the code whatsoever unless you re-rip their code and get it to build in your project again.

A: You can get the sourcecode of FreeType from http://freetype.sourceforge.net if that's what you mean.


text:
Q: SAP Macro running through Excel, how to get data to populate on Excel sheet? I created an SAP Macro that gets the data that I need:
If Not IsObject(application) Then
   Set SapGuiAuto  = GetObject("SAPGUI")
   Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
   Set connection = application.Children(0)
End If
If Not IsObject(session) Then
   Set session    = connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject session,     "on"
   WScript.ConnectObject application, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").text = "ZPRS"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/ctxtP_PLANT").text = "1707"
session.findById("wnd[0]/usr/ctxtS_ARBPL-LOW").text = "BSLSR"
session.findById("wnd[0]/usr/ctxtS_ARBPL-LOW").setFocus
session.findById("wnd[0]/usr/ctxtS_ARBPL-LOW").caretPosition = 5
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]/tbar[1]/btn[8]").press

then What I did next was make a button with this through Excel to get the data that I need:
Private Sub CommandButton1_Click()
If Not IsObject(SAPGuiApp) Then
   Set SapGuiAuto = GetObject("SAPGUI")
   Set SAPGuiApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
   Set Connection = SAPGuiApp.Children(0)
End If
If Not IsObject(session) Then
   Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject session, "on"
   WScript.ConnectObject SAPGuiApp, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "ZPRS"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/ctxtP_PLANT").Text = "1707"
session.findById("wnd[0]/usr/ctxtS_ARBPL-LOW").Text = "BSLSR"
session.findById("wnd[0]/usr/ctxtS_ARBPL-LOW").SetFocus
session.findById("wnd[0]/usr/ctxtS_ARBPL-LOW").caretPosition = 5
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]/tbar[1]/btn[8]").press

End Sub

After running the script, everything works well. However, the issue that I'm having is that, the excel macro is creating a new Excel sheet every time, I want it to populate on the Excel sheet in where the button is. I don't really know how to word it and was wondering if anybody might have any insight ?


text:
Q: Is every context free language equivalent to one whose grammar has only one non-terminal symbol? A context free language is generated by a context free grammar, which can be expressed in the Backus-Naur form e.g. I believe that if we only allow one nonterminal symbol in the grammar, the resulting languages must be simpler, possibly even regular. I don't see how to prove this yet, so can you help me:
Is every context free language equivalent to one whose grammar has only one non-terminal symbol?

A: Consider the language $L = 0 \cup 1^* = \{0\} \cup \{\varepsilon,1,11,111,\ldots\}$. This is obviously context-free, even regular. However, it cannot be generated by a grammar with only one non-terminal symbol. Assume $G$ would be such a grammar and its only non-terminal symbol is $S$. Since $G$ has only finitely many productions there is some $n$ such that $1^n \in L$ cannot be generated in one step, i.e. it has a derivation $S \Rightarrow^* xSy \Rightarrow^* 1^n$ where $x,y$ are not both empty. Then $x$ and $y$ can cannot contain the symbol $0$. All occurences of $S$ in $x$ and $y$ can be replaced by $1$ as $S \Rightarrow 1$, so we can derive a word $1^aS1^b$ where $a,b$ are not both zero. However, we also have a production $S \rightarrow 0$, so that $G$ also generates the word $1^a01^b$ which is not in $L$; contradiction.


text:
Q: The reciprocal matrix of positive semidefinite matrix is also positive semidefinite? Let matrix $A=(a_{i,j})_{n\times n}$ is a positive semidefinite matrix,and each element is positive. Is the matrix
$$
\left(\frac{1}{a_{ij}}\right)_{n\times n}
$$
also a positive semidefinite matrix?

A: No this is not correct for instance
$$A=
\left (\begin{array}[cc]
11&1/4 \\
1/4&1
\end{array}\right)
$$
Then $|A|=15/16>0$
But if you denote $B$ the matrix with the reciprocal entries then
$|B|= -15.$


text:
Q: google translate changes currency symbols I'm integrating google's website translator[1]  to a client's site.
Everything worked fine and translations were working... however it seems to erronously (and inconsistently) translate the GBP symbol (£) to whatever currency the target language uses. For instance for French and German the symbol is (sometimes) replaced by a EUR symbol (€).
This only happens sometimes, but I can't find a common link between the occurrences other than the currency symbol, so unsure what to do to prevent it.
Obviously £10 will never be the same as $10 or R10 or €10 - so I find myself needing to prevent google from translating currency symbols while allowing it to translate everything else.
The only lead I could find was from their own help[2], but it involves wrapping every instance of the currency symbol in a span or div which is completely impractical for this application.
Does anyone know a better way?
[1] http://translate.google.com/manager/website/add?hl=en
[2] http://support.google.com/translate/#2641276

A: The only way I could find to control this was by using the class='notranslate' method and wrapping every instance of a price that I could find in a span with that class.
Google's support say that you can use that class on any (valid) HTML element and it will be left alone, so I used it on some selects with prices in them, etc.
All in all, a horrible solution but it beats having prices displayed wrongly to anyone who can't read english.


text:
Q: SmarterAsp.Net Connection String I have a program I wrote in ASP.Net MVC.  When I run the file inside Visual Studio it runs great.  I uploaded the file on SmarterAsp.Net.  Now everything comes up except my database part of the file and I get an error 52 when I bring up the database part.  Here is the link to my site.  http://dwmurphy67-001-site2.smarterasp.net/.  When you click on the tab that says patches that's where my database should come up.  This is what SmarterAsp.Net gave me for the connection strings:
ASP.net
"Data Source=SQL5011.Smarterasp.net;Initial Catalog=DB_9B2856_Product;User Id=DB_9B2856_Product_admin;Password=YOUR_DB_PASSWORD;"
Classic ASP
"Provider=SQLOLEDB;Data Source=SQL5011.Smarterasp.net;Initial Catalog=DB_9B2856_Product;User Id=DB_9B2856_Product_admin;Password=YOUR_DB_PASSWORD;"
This is what I have in my web.config file:

 <add name= "Product" connectionString="Data Source=SQL5011.Smarterasp.net;Initial Catalog=DB_9B2856_Product;User Id=DB_9B2856_Product_admin;Password:#######"/>
<add name="ProductEntities" connectionString="metadata=res://*/Models.Product.csdl|res://*/Models.Product.ssdl|res://*/Models.Product.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Product.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
  providerName="System.Data.EntityClient" />
<add name="EmailmeContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=EmailmeContext-20140604141117; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|EmailmeContext-20140604141117.mdf"
  providerName="System.Data.SqlClient" />

Can anyone help me with this?
I know somewhere my connection string is wrong where I'm hooking up to the database on SmarterAsp.Net.


text:
Q: Suppress Group Header when no record below Is it possible to suppress Group header in page 3/8 when group header no record in this page.

A: Try Group Expert/Options/Options Tab and check Keep Group Together.  If this does not work, I would add a count formula to count records in that group, and suppress group if that count is zero.

A: I found a guide that shows how to prevent orphaned headers. Have a look method 2 of it.
The idea is that you setup a group header that acts as a detail section, but only for the first row of each group. On that first the detail section will be suppressed.

*

*Add an additional group header for your group B. Now you have a header B1 (your old one) and B2 (the new one).

*Format B2 like your detail section, copy all fields etc.

*In the section expert select the entry for all B headers (not B1 or B2). Tick Keep together.

*Add a formula to the Suppress box of your Detail section with the following content (replace {database.field} with the field by which you are grouping):
WhilePrintingRecords;
Onfirstrecord or {database.field} <> Previous({database.field})

A: Here it goes a solution for the problem, but you will have to adjust something else to keep the group header repeating for each page.
The main idea is to simulate the group header as a detail section and show it only together with the first record of the group.
Step by step:

*

*Create a running total field to count the records in your group: field to summarize = any, type of summary = count, evaluate for each record, reset on change of group. Let's assume the name of this formula is {#RTotal0}.

*Suppress your group header.

*Create another detail section above your current detail section. So, you will have "Details a" and "Details b". The section "Details a" will simulate the group header.

*Open the section expert, choose the section "Details a", open the formula editor for the option "Suppress", and put this formula: {#RTotal0} > 1. That means that this section will be shown only for the first record of the group.

*Open the section expert, choose the section "Details" (the parent of "Details a" and "Details b") and check the option "keep together".

This will solve your problem. But know the group header will not repeat for each page. One way to do that:

*

*Open the section expert for the group header option, open the formula editor for the option "Suppress", put the formula: {#RTotal0} = 1. It means that the group header will suppress initialy, but after a page break, it will show (if you the group is set to print the group header for each page).

But you may need to adjust it for your case.


text:
Q: Scala Built Tool in HP UX I was trying to install sbt on HPUX by downloading zip file https://www.scala-sbt.org/download.html
During Installation i encountered below error ""Caused by: lmcoursier.internal.shaded.coursier.cache.shaded.io.github.soc.directories.UnsupportedOperatingSystemException: directories are not supported on HP-UX"
Can anyone clarify is HP UX will not compatible with SBT ?


text:
Q: How to confidently and concretely state that a problem has no analytical solution I have the following equality
$f(\sigma, X) = g(\sigma, Y)$
where $\sigma$ is some parameter and $X$ and $Y$ are generic sets of other parameters/variables, where generally $X \neq Y$.
Say I would like to solve for $\sigma$ in terms of the other relevant variables and parameters, ultimately desiring a solution of the form
$\sigma = h(Z)$
where $Z$ is a set of parameters/variables that may be a subset or identical to $X\cup Y$.
Now, how do I state with concreteness that $\sigma$ has no analytical solution? That is, no such $h(Z)$ exists without including non-elementary functions which need be calculated numerically. For my specific problem, I known that no analytical solution is available simply for the reason that I tried with WolframAlpha to no avail. How do I communicate that no solution exists without having to state that I have made infinite attempts and none of them worked?


text:
Q: 1 to N relationship Let's say there is a (Head of School) that manages at least one academic  (1 to N) and both are mandotory. Academic has academic ID  as a primary key and other attributes and Head of School only has one attribute which is secretaryName. But SecretaryName is just an attribute.. It's not primary key in diagram. If I convert that statement to relational schema can I write secretaryName as foreign key ?
Academic(academic_ID, academicName, title, secretaryName)
As far as I know, there have to be primary key in both entites in order to create foreign key.

A: It is true that every relation must have a primary key.
In a 1:N relationship that involves two relations it's obvious what happens. Suppose we have two relations; let's call them A and B and say that every A has at least one B. This means that the primary key of B matches with a Foreign Key in A.
In your case the only difference is that the relation is connected to itself, so academic_ID is both the Primary Key and a Foreign Key. So mark it as such on your diagram.
When you map this design to a database you will need something like this:
Supervises (manager_ID, subordinate_ID)

to model the relationship. Here both attributes are Foreign Keys and together they form a composite primary key.


text:
Q: Change language to english after "software boutique" upgraded into a different language I chose to update the listings using the button that exists on the bottom left (I don't know what it says because it is no longer there).
Now, after upgrading, it is in a different language that is not english, although the OS is configured to be in english.
How do I change the language back to english?


text:
Q: How to switch to earSpeaker programmatically in iOS? I am currently playing an audio file with "MobileVlcKit" and I need to switch to earSpeaker (top speaker for phone calls) in the middle of playing audio file.
Currently I am using this code:
AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)

But it keep playing from main speaker.
Do anyone knows what is my problem?

A: I just checked my 2 years old objective-c code, not sure will it work for you, but worth to try. here is its swift version:
let audioSession = AVAudioSession.sharedInstance()
do {
    try audioSession.setActive(false)
    try audioSession.setCategory(.playAndRecord, options: .defaultToSpeaker)
    try audioSession.overrideOutputAudioPort(.none)
    try audioSession.setActive(true)
} catch {
    // handle error
    print(error)
}


text:
Q: '+entityForName: nil is not a legal NSManagedObjectContext parameter - Core Data I have added all of the relevant code to the App Delegate, and I am able to add to the data model and fetch from the data model in applicationDidFinishLaunchingWithOptions.
My problem comes when I am trying to write to the data model in my View Controller. I have added this code to the header file:
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;

@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

And this code to my implementation file:
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *model = [NSEntityDescription
                          insertNewObjectForEntityForName:@"Events"
                          inManagedObjectContext:context];
[model setValue:@"Sample Event" forKey:@"eventName"];

NSError *error;
if (![context save:&error]) {
    NSLog(@"Couldn't save: %@", [error localizedDescription]);
}

However, I get the following error:
'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Events''

Does anyone know what's going on? Any help would be appreciated.

A: I had forgotten to pass the context to the view controller. Rookie error.

A: You can pass the context by including the following code before you begin to fetch the data form the database:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
context = [appDelegate managedObjectContext];

A: If you are using segues you will get the same problems if you don't pass the context down the line. Use this code in the prepareForSegue method of class initiating the segue:
[[segue destinationViewController] setManagedObjectContext:self.managedObjectContext];

That assumes you hold your context in a property called "managedObjectContext" of course.

A: you should add this to your viewController:
 id delegate = [[UIApplication sharedApplication] delegate];
    self.managedObjectContext = [delegate managedObjectContext];

A: I got this problem and a colleague helped me out. If you got this error message:
"entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name". And you made changes in you coredata model. I think the problem might not be the code.
The solution can be simple. Try one of those options:

*

*Just delete the app from the device you are testing, it should have the old version of your model.

*Create another database version using Xcode, >Editor>Add Model Version.

Hope it helps.

A: In my case the .xcdatamodeld was mislabeled in the AppDelegate:
 let container = NSPersistentContainer(name: "name of data model")

A: If the destination view controller is embedded in a NavigationController, the context needs to be set appropriately as follows-
  self.mydetailViewController = [[[segue destinationViewController] viewControllers] objectAtIndex:0];
 [self.mydetailViewController setManagedObjectContext:self.managedObjectContext];

A: I'm a fan of lazy initialization. This way if you need to inject a new context for testing you can, or it'll get it's context from the app delegate if you set up your MOC there.
class.h
@property (strong, nonatomic,getter=getManagedObjectContext) NSManagedObjectContext *managedObjectContext;

class.m
    -(NSManagedObjectContext *)getManagedObjectContext {
        if (_managedObjectContext) {
            return _managedObjectContext;
        }
        _managedObjectContext = [[(AppDelegate *)[[UIApplication sharedApplication]delegate]sharedDataModel]managedObjectContext];
        return _managedObjectContext;
    }


text:
Q: how to run firebase query inside a function in node js I have a function which should query firebase db and return a result.
 function verifyToken(token)
 {
    var androidId = 'xxxxx';
    admin.database(dbDEV).ref('profiles').orderByChild('androidId').equalTo(androidId).on('value',(snapshot)=>{
    console.log(snapshot.val());
    return snapshot.val();
   });
 }

I am using firebase functions for this . so the result is getting logged in firebase logs but i am not getting and return value while executing the function.

A: Two things:

*

*Use once() instead of on() to query data a single time.  on() establishes a listener that listens forever, until you remove the listener.

*Realtime Database queries are all asynchronous, meaning they return immediately, and the callback function you provide is invoked some time later with the results.  You can't simply return the results from the callback in order to return those results from the enclosing function.  If you want verifyToken to yield query results to the caller, you should return a promise that resolves with the data.

A: You can start by using promises. For example:
function verifyToken(token) {
    return new Promise(resolve => {
        var androidId = 'xxxxx';
        admin.database(dbDEV).ref('profiles').orderByChild('androidId').equalTo(androidId).on('value',(snapshot)=>{
            console.log(snapshot.val());
            resolve(snapshot.val());
        });
    });
}

And when you need the result:
verifyToken(token).then(result => {
    ... do stuff
});

To improve on this, you can use an async function. For example:
async function foo() {
    const result = await verifyToken(token);
    console.log(result);
}