text:
Q: Check if date is in specific date range PHP I'm trying this one out and it's been a while since I last coded in PHP.
I have a function that checks if given date is in between the range of dates:
pr($this->isDateBetween("2014-11-15", "2014-12-05", "2014-06-14"));

public function isDateBetween($dt_start, $dt_check, $dt_end){
        if(strtotime($dt_check) >= strtotime($dt_start) && strtotime($dt_check) <= strtotime($dt_end)){
            return true;
        } else{
            return false;
        }
    }

But seems like I'm getting false. The expected result should be true because 2014-12-05 is less than 2014-06-14 .
December is less than June so that should be true?
Also,
When I change 2014-06-14 to 2014-12-14 it became true.
Sorry, I'm not updated anymore with PHP. Please bear with me.
EDITS
Tried converting those to strtotime but still getting wrong results

A: The solution exist here:
How to check if a date is in a given range?
SOLUTION:
Converting them to timestamps is the way to go alright, using strtotime, e.g.
$start_date = '2009-06-17';

$end_date = '2009-09-05';

$date_from_user = '2009-08-28';

check_in_range($start_date, $end_date, $date_from_user);

function check_in_range($start_date, $end_date, $date_from_user)
{
  // Convert to timestamp
  $start_ts = strtotime($start_date);
  $end_ts = strtotime($end_date);
  $user_ts = strtotime($date_from_user);

  // Check that user date is between start & end
  return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}

A:
The expected result should be true because 2014-12-05 is less than 2014-06-14 .

Totally wrong. The code IS Working. June 14th is "less" than December 12th. So your Dec 12th date is NOT between the start/end dates. it's past the end of the range.

A:
The expected result should be true because 2014-12-05 is less than 2014-06-14 .

Absolutely not. The expected result is not true. It is false, because "2014-12-05" is not less than "2014-06-14". December less than June? Never heard of such a peculiar logic before.

Also, When I change 2014-06-14 to 2014-12-14 it became true.

That's right. Because "2014-12-05" is definitely less than "2014-12-14", it is true. 5 December is obviously smaller than 14 December.
This has nothing to do with PHP versions or PHP built-in methods. This is all about your logic.
I think this is what you're looking for:
pr($this->isDateBetween("2014-06-14", "2014-11-15", "2014-12-05"));

public function isDateBetween($dt_start, $dt_check, $dt_end){
        if(strtotime($dt_check) >= strtotime($dt_start) && strtotime($dt_check) <= strtotime($dt_end)){
            return true;
        } else{
            return false;
        }
}

This will return true.


text:
Q: I am trying to access the dictionary I made so that the command only runs if the user's ID is listed in the dictionary I am trying to access the dictionary I made so that the command only runs if the user's ID is listed in the dictionary
This is what I have come up with so far but it keeps on failing:
import discord
client = discord.Client()

dict = {'rand ID 1':'rand ID 2', 'rand ID 3':'rand ID 4'}

@client.event
async def on_message(message):
  if message.content.lower().startswith('.test'):
    if message.author.id == "dict":
      embed1 = discord.Embed(title='Hello World!')
      await message.channel.send(embed=embed1)

A: One option would be to use the values() method and search if it contains the message.author.id- https://www.programiz.com/python-programming/dictionary
I notice that your dictionary does not have the expected key,values
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

It actually looks like a regular array/list, that you can iterate/or check that it contains the given element message.author.id

A: You might want to use a set to store the ids.
whitelisted_ids = {'rand ID 1', 'rand ID 2', 'rand ID 3', 'rand ID 4'}

Also, you can use a predicate for extract this behavior from the command itself.
whitelisted_ids = {'rand ID 1', 'rand ID 2', 'rand ID 3', 'rand ID 4'}
# Might be in capital if constant

class NotWithinWhitelist(commands.CheckFailure):
  pass

def is_within_whitelist():
  async def predicate(ctx):
    if ctx.author.id not in whitelisted_ids:
      raise NotWithinWhitelist("You are not whitelisted for that command")

    return True

  return commands.check(predicate)

@client.command()
@is_within_whitelist
async def test(ctx):
    test_embed = discord.Embed(title='Hello World!')
    await message.channel.send(embed=test_embed)

@test.error
async def test_error(ctx, error):
    if isinstance(error, commands.NotWithinWhitelist):
        await ctx.send(str(error))

redpajama_set_name: RedPajamaStackExchange


text:
Q: QML: in loading images dynamically I am trying to load different images dynamically based on a button press.
Rectangle {
    id: rect
    width: 800
    height: 600
    color: "black"
    x: 300
    y: 10

    MediaPlayer {
        id: mediaplayer
        source: "images/video10.avi"
         autoPlay: true
        onError: videoPage1.sendToPost(mediaplayer.errorString)
     }

    VideoOutput {
        id: videoOutput
        anchors.fill: parent
        source: mediaplayer
        fillMode: VideoOutput.Stretch
     }

    MouseArea {
        id: playArea
        anchors.fill: parent
         onPressed: {
            if(!mediaplayer.hasVideo){
                console.log("No media");
            }
             pressX = mouse.x
            pressY = mouse.y
        }

        onReleased: {
            releaseX = mouse.x
            releaseY = mouse.y
            doSomething();
            roi_flag=0;
        }
    }
}

Component {
    id: highlightComponent;
    Rectangle {
        color: "transparent";
        border.color: "black"
        border.width: 2
        property alias text:t1.text;
        property alias ss: image.source;

        Text {
            id: t1
            text: "click"
            anchors.centerIn: parent
            width: 5
        }

        Image {
            id:image
            //  width: 130; height: 100
            //  source: (direction_flag ? "images/top.png" : "images/right.png")
            source : ss
            anchors.centerIn: parent
        }

    }

}

function doSomething(){
     console.log(rOI);

         count++;
        var obj = 'highlightItem' + count;
        var dir;
        if(direction_flag == 0){
            if((pressX - releaseX) > 0){
                 dir= "images/left.png";
            }else if((pressX - releaseX) < 0){
                 dir="images/right.png";
            }
        }else{
            if((pressY - releaseY) > 0){
                 dir="images/top.png";
            }else if((pressY - releaseY) < 0){
                 dir="images/down.png";
            }
        }

        highlightComponent.incubateObject (rect, {
                                               "x" : pressX,"y":pressY,width:releaseX - pressX,height: releaseY - pressY,text:count,ss:dir});
 }

The method works when changing the text but its not working when changing the image, I am getting the error "QML Image: Protocol "" is unknown".
Any suggestions will be helpful, thanks.


text:
Q: Google analytics API missing data? I am trying to access data via the analytics reportingv4 API. I am using the.net version in visual studio. I can get it to return data but just not the data I want.
I am using a specific account that only has one view attached to it. If I try to view the data I'm looking for, using the web interface, it works, by filtering it using the search box. For example, there is currently 20 page hits for today. If I try the same, using the API, no data is returned. If I remove the filter, from my code, data is returned but none of the pages that I am looking for.
Any ideas?
Thanks

A: I was being silly. I eventually noticed that I was supplying a date range for the year 2017! The processing which


text:
Q: Running a CMD or BAT in silent mode How can I run a CMD or .bat file in silent mode? I'm looking to prevent the CMD interface from being shown to the user.

A: Use Advanced BAT to EXE Converter from http://www.battoexeconverter.com
This will allow you to embed any additional binaries with your batch file in to one stand alone completely silent EXE and its freeware

A: Use Bat To Exe Converter to do this
http://download.cnet.com/Bat-To-Exe-Converter/3000-2069_4-10555897.html (Choose Direct Download Link)
1 - Open Bat to Exe Converter, select your Bat file.
2 - In Option menu select "Invisible Application", then press compile button.
Done!

A: Include the phrase:
@echo off

right at the top of your bat script.

A: Try SilentCMD. This is a small freeware program that executes a batch file without displaying the command prompt window.

A: I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)
That should answer your question.
Here it is:

From your first script, call your second script with the following line:
wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

*

*the [path]\name of your script

*all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

*

*intWindowStyle : 0 means "invisible windows"

*bWaitOnReturn : false means your first script does not need to wait for your second script to finish

See the question for the full invis.vbs script:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
                                                         ^
                             means "invisible window" ---|

Update after Tammen's feedback:
If you are in a DOS session and you want to launch another script "in the background", a simple /b (as detailed in the same aforementioned question) can be enough:

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window.

A: If i want to run command promt in silent mode, then there is a simple vbs command:
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM iexplore.exe"

if i wanted to open an url in cmd silently, then here is a code:
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("iexplore.exe http://otaxi.ge/log/index.php", 0)
'wait 10 seconds
WScript.sleep 10000
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM iexplore.exe"

A: I'm pretty confident I like this method the best. Copy and paste the code below into a .vbs file. From there you'll call the batch file... so make sure you edit the last line to specify the path and name of the batch file (which should contain the file you'd like to launch or perform the actions you need performed)
Const HIDDEN_WINDOW = 12

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")

Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("C:\PathOfFile\name.bat", null, objConfig, intProcessID)

It definitely worked for me. Comments are welcomed :)

A: Another way of doing it, without 3rd party programs nor converters ("batch to exe" programs actually just put your batch file in the tmp folder and then run it silently so anyone can just fetch it from there an get your code) no vbs files (because nobody knows vbs) just one line at the beginning of the batch file.
@echo off > NUL

A: I think this is the easiest and shortest solution to running a batch file without opening the DOS window, it can be very distracting when you want to schedule a set of commands to run periodically, so the DOS window keeps popping up, here is your solution.
Use a VBS Script to call the batch file ...
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run chr(34) & "C:\Batch Files\ mycommands.bat" & Chr(34), 0
Set WshShell = Nothing

Copy the lines above to an editor and save the file with .VBS extension. Edit the .BAT file name and path accordingly.

A: The below silent .bat file code prevents the need to have two bat files (using "goto" and ":").
It does it all in the same .bat file. Tested and confirmed working in Windows 10
Make sure you replace "C:\pathToFile\ThisBatFile.bat " with the path to this same .bat file! Keep the space after ".bat".
@echo off
if [%1]==[] (
    goto PreSilentCall
) else (
    goto SilentCall
)

:PreSilentCall
REM Insert code here you want to have happen BEFORE this same .bat file is called silently
REM such as setting paths like the below two lines

set WorkingDirWithSlash=%~dp0
set WorkingDirectory=%WorkingDirWithSlash:~0,-1%

REM below code will run this same file silently, but will go to the SilentCall section
cd C:\Windows\System32
if exist C:\Windows\Temp\invis.vbs ( del C:\Windows\Temp\invis.vbs /f /q )
echo CreateObject("Wscript.Shell").Run "C:\pathToFile\ThisBatFile.bat " ^& WScript.Arguments(0), 0, False > C:\Windows\Temp\invis.vbs
wscript.exe C:\Windows\Temp\invis.vbs Initialized
if %ERRORLEVEL%==0 (
    echo Successfully started SilentCall code. This command prompt can now be exited.
    goto Exit
)

:SilentCall
cd %WorkingDirectory%
REM Insert code you want to be done silently.
REM Make sure this section has no errors as you won't be able to tell if there are any,
REM since it will be running silently. You can add a greater than symbol at the end of
REM your commands in this section to output the results to a .txt file for the purpose
REM of debugging this section of code.

:Exit

If your .bat file needs more than just the "Initialized" argument (which tells the bat file to go to :SilentCall section), add "^& WScript.Arguments(1)," , "^& WScript.Arguments(2)," ,etc. depending on the number of arguments, then edit the line where wscript.exe is called:
"wscript.exe C:\Windows\Temp\invis.vbs Initialized BatFileArgOne BatFileArgTwo"

A: I'm created RunApp to do such a job and also using it in my production env, hope it's helps.
The config like below:
file: config.arg
:style:hidden

MyBatchFile.bat
arg1
arg2

And launch runapp.exe instead.


text:
Q: sudoku solver stuck in infinite loop for some puzzles I have the following solver built out following various tutorials and my own knowledge and now i want to input the following puzzle from Peter Norvig's puzzle site and it gets stuck in an infinite loop but works for easier problems.
the puzzle that works:
[
  [5,3,0,0,7,0,0,0,0],
  [6,0,0,1,9,5,0,0,0],
  [0,9,8,0,0,0,0,6,0],
  [8,0,0,0,6,0,0,0,3],
  [4,0,0,8,0,3,0,0,1],
  [7,0,0,0,2,0,0,0,6],
  [0,6,0,0,0,0,2,8,0],
  [0,0,0,4,1,9,0,0,5],
  [0,0,0,0,8,0,0,7,9]
]

a puzzle that runs into an infinite loop:
[
  [4,0,0,0,0,0,8,0,5],
  [0,3,0,0,0,0,0,0,0],
  [0,0,0,7,0,0,0,0,0],
  [0,2,0,0,0,0,0,6,0],
  [0,0,0,0,8,0,4,0,0],
  [0,0,0,0,1,0,0,0,0],
  [0,0,0,6,0,3,0,7,0],
  [5,0,0,2,0,0,0,0,0],
  [1,0,4,0,0,0,0,0,0]
]

and of course, the solver:
sudokuSolver(puzzle) => {
  let nonPossibilities = {},
    impossibleNumbers, count = 81;
  while (count > 0) {
    count = 0;
    for (let v = 0; v < puzzle.length; v++) {
      for (let h = 0; h < puzzle.length; h++) {
        //if value is a empty or 0
        if (puzzle[v][h] === 0) {
          //reset
          nonPossibilities = {};
          //check the box
          for (let i = 0; i < 9; i++) {
            //first check vertically
            if (puzzle[v][i] > 0) {
              nonPossibilities[puzzle[v][i]] = true;
            }
            //followed by horizontally
            if (puzzle[i][h] > 0) {
              nonPossibilities[puzzle[i][h]] = true;
            }
          }

          for (let vertBox = Math.floor(v / 3) * 3; vertBox < Math.floor(v / 3) * 3 + 3; vertBox++) {
            for (let horiBox = Math.floor(h / 3) * 3; horiBox < Math.floor(h / 3) * 3 + 3; horiBox++) {
              if (puzzle[vertBox][horiBox]) {
                nonPossibilities[puzzle[vertBox][horiBox]] = true;
              }
            }
          }

          impossibleNumbers = Object.keys(nonPossibilities);
          if (impossibleNumbers.length === 8) {
            for (let ii = 1; ii < 10; ii++) {
              if (impossibleNumbers.indexOf(ii.toString()) < 0) {
                // console.log(vert,horz);
                puzzle[v][h] = ii;
              }
            }
          } else {
            count++;
          }
        }
      }
    }
  }
  return puzzle;
}


text:
Q: Two columns, elements within the two columns stacked using css I have searched everywhere for an answer, but I don't think I'm asking the question in the right way. I have two columns, but I need the elements to stack and cant seem to make anything work. I also want to add a background color to make the elements stand out.

Product Spotlight

<? while($row = mysql_fetch_array($products_showcase_query)): ?>

        <?=              $row['product_headline'] ?>

        <img src="../product_images/<?= $row['product_image'] ?>" style="width: 134px; float: left;" />

            <?= $row['product_summary'] ?>

        <img src="../product_logos/<?= $row['product_logo'] ?>" />

<? endwhile ?>

layout example
Any help would be appreciated! Thank you :)


text:
Q: how i can Get record from sales_order_grid table in Magento 2 i have added a Custom Attribute in sales_order_grid table now I want to get a record from sales_order_grid by entity_id. Is there any model that I can use easily o inject and get sales_order_grid Data in Magento 2

A: within the file vendor/magento/module-sales/etc/di.xml, I extract a small part of it:

this describes the grid component pulls its data using the model: Magento\Sales\Model\ResourceModel\Order\Grid\Collection.
So my answer would be to pull the order like the grid does to use this resource Model. Now, if you do need only order data given an entity id, the recommended way is to use the sales order repository, and that is \Magento\Sales\Model\OrderRepository


text:
Q: How to adjust Django query set value? I have a view:
def get_comment_tree(request):
    news_id = request.GET.get("news_id")
    ret = list(Comment.objects.filter(news_id=news_id).values("nid", "content", "parent_comment_id", "user", "create_time"))
    return JsonResponse(ret, safe=False)

The return of the view will be sent back to ajax.Now problems are,how can I convert the value "user" to "username",now I only get the user_id and the "create_time" to naturalday or naturaltime format.
If I use python to convert these data I think it would be a little complicated,any friend can help?
This is my comment model:
class Comment(models.Model):
    """

    评论表

    """
    nid = models.AutoField(primary_key=True)
    news = models.ForeignKey(verbose_name='评论文章', to='News',to_field='id',on_delete=models.CASCADE)
    user = models.ForeignKey(verbose_name='评论者', to='User',to_field='id',on_delete=models.CASCADE)
    content = models.CharField(verbose_name='评论内容', max_length=255)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    parent_comment = models.ForeignKey('self', null=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.content

A: Give this a try
from django.db.models import F

Comment.objects.filter(news_id=news_id).values("nid", "content", "parent_comment_id", "create_time", username=F('user__username'))

A: If user is foreign key relation with models.user , then you can access username as user.username.
And for create_time , it depends on the datatype you have configured for it in models.py file.
If it is datetime object then you can convert it into string using datetime.strftime() as create_time.strftime("%m/%d/%Y, %H:%M:%S")

A: if in Comment model user is ForeignKey, you can use user__username to get the value, if you whant to change user__username to user, you can try this:
list(Comment.objects.filter(news_id=news_id).values("nid", "content", "parent_comment_id", user='user__name', "create_time"))

A: ret = list(Comment.objects.filter(news_id=news_id).values("nid", "content", "parent_comment_id", "user__username", "create_time"))

This query will show username with key as user__username.


text:
Q: Removing a class to a parent td element with a child button I am trying to remove a class to a parent td from a child button element thru jQuery. I can remove the class when the outer tr element is clicked with no problem but when trying to add the class back to the parent td it doesn't do anything. When debugging it seems to work. I am trying to do it without reloading the page hence the preventDefault method on the button click. Any ideas on what might be causing the issue?
My html is this:

          Order Number

          Project Number

          1313

          50

              <button class="close">
                X
              </button>

                            Verify Order

                        Item Number

                        Item Description

                    123456

                    Description

              <button class="btn btn-default" type="button"     onclick="window.print()">
                Print
              </button>

Here is the javascript:
 $('.click').on('click', function() {
  var $td = $(this).find('#orderNumber');
  var td = "#td" + $td.text().trim();
  $(td).removeClass('hidden');
 });

 // Closes verification window
 $('.close').on('click', function(e) {
  e.preventDefault();
  var $td = $(this).closest('td');
  $td.addClass('hidden');
 });

I have also including fiddle
https://jsfiddle.net/tspuq9vo/3/

A: You've set the click class on the tr causing it to get fired straight after the click event for the close button.
As a quick fix you can stop the click event from propagating by using

 $('.click').on('click', function() {
     var $td = $(this).find('#orderNumber');
     var td = "#td" + $td.text().trim();
     $(td).removeClass('hidden');
 });

 // Closes verification window
 $('.close').on('click', function(e) {
     e.preventDefault();
     e.stopPropagation();
     var $td = $(this).closest('td');
     $td.addClass('hidden');
 });

Otherwise you should really only target the clickable td-s directly


text:
Q: How do I deal with [Errno 5] Input/output error when reading a csv in Python? I am currently reading a csv in Python and writing to it. I have it running on an ec2 server but I do the development on my local windows laptop before pushing updates. I recently got the following error:[Errno 5] Input/output error, but it only occurs on the ec2 server. The code runs fine on my local windows laptop. Additionally, it says that it is an OS error. Here's the part of the code causing the problem:
        with open(filename, 'rt') as f:
            reader = csv.reader(f, delimiter=',')
            lines = []
            if sum(1 for row in reader) < len(players):
                f.seek(0)
                for row in reader:
                    row_len = len(row)
                line = []
                for i in range(row_len):
                    line.append('')
                f.seek(0)
                for i in range(len(players) + 1 - sum(1 for row in reader)):
                    lines.append(line)
            f.seek(0)
            title = next(reader)
            counter = 0
            for line in reader:
                lines.insert(0, line)

I can include surrounding code if it would be useful. The error says the problem occurs on the very first line in the code above. Why would I be getting this error on my ec2 Ubuntu server but not on my local windows machine?


text:
Q: On an AVR (ATtiny2313), which is serviced first when TIMER0_OVF and TIMER0_COMPA are due at the same time? If an AVR's 8-bit timer compare register is 255 and the timer overflows (according to the datasheet, the compare interrupt happens on the next timer clock cycle) then both the overflow interrupt and the compare interrupt should be due at the same time. Which will be serviced first?

A: See the datasheet for the ATtiny2313: http://www.atmel.com/dyn/resources/prod_documents/doc2543.PDF
The priority of interrupts is determined by the order of the interrupt vectors.  See page 46 for the list.  The lower the number, the higher the priority.  Since Timer/Counter0 Overflow has a lower number (7) than Timer/Counter0 Compare Match A (14), the overflow ISR will run first.

A: I really hope somebody knows this, and that you get a straightforward answer with good reasoning from the docs, examples of how to plan for simultaneous interrupts, etc. but all I can tell you right now is that it's the one that's still running when you do
ISR(TIMER0_OVF_vect)
{
  printf("OVF ISR Ran First\n"); //or whatever your console output uses
  fflush(stdout);

  while(1);
}

ISR(TIMER0_COMPA_vect)
{
  printf("COMPA  ISR Ran First\n"); //or whatever your console output uses
  fflush(stdout);

  while(1);
}


text:
Q: Uncaught SyntaxError: Unexpected token < --> jsonp  jsonp = (url, callback) => {
        var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
        window[callbackName] = function(data) {
            delete window[callbackName];
            document.body.removeChild(script);
            callback(data);
        };

        var script = document.createElement('script');
        script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
        document.body.appendChild(script);
    }

componentDidMount() {
 this.jsonp('https://www.naver.com');
}

i want a xml data. but Uncaught SyntaxError: Unexpected token < error occurs...
how should i do?
help me.


text:
Q: How to modify my existing query to create a new column in my table and feed it with this specific data? I am using SQL Server 2014 and I have the following T-SQL query which extract all duplicate records based on the "Email" column of my Table (t1):
use MyDatabase

;WITH [CTE1] AS (
    select
        RowNum = ROW_NUMBER () OVER(PARTITION BY [Email] ORDER BY [Email])
        , *
    from [t1]
)
SELECT *
FROM [CTE1]
WHERE [RowNum] > 1

The query runs fine and gives the following output (extract):
 RowNum      ID       Name    Email
   2         100      John    john@xyz.com
   2         255      Allan   ag@mail64.com
   2         211      Allan   ag@mail64.com
   2         126      Peter   ps@noemail.com
   2         110      Peter   ps@noemail.com
   3         144      Peter   ps@noemail.com
   4         220      Peter   ps@noemail.com
   ...

How can I modify my query to get the following output (note: Column "Tag" should be created on the table t1:
 RowNum      ID       Name    Email             Tag
   2         100      John    john@xyz.com      dup
   2         255      Allan   ag@mail64.com     dup
   2         211      Allan   ag@mail64.com     dup
   2         126      Peter   ps@noemail.com    dup
   2         110      Peter   ps@noemail.com    dup
   3         144      Peter   ps@noemail.com    dup
   4         220      Peter   ps@noemail.com    dup
   ...

Note: Records with RowNum = 1 should have a blank in the "Tag" column.
Thanks for your help.

A: Presumably you won't want to filter out rows with Rownum=1, simply use a case expression.
SELECT *, case when rownum=1 then '' else 'dup' end as Tag
FROM [CTE1]

If you have the column Tag on your table t1 you can include it in the select and run an update on the CTE
update CTE1 set
  Tag=case when rownum=1 then '' else 'dup' end

You should probably change your ordering criteria to be based on Id to consistently keep the highest/lowest id of each group, currently you are assigning duplicates based on the alphabetical sorting of the email.

A: Try this:
USE MyDatabase;

DECLARE @Table  TABLE (RowNum int , ID int, Name varchar(50), EMail varchar(100), Tag varchar(3));

INSERT INTO @Table
    SELECT
            RowNum  =   ROW_NUMBER () OVER(PARTITION BY T1.[Email] ORDER BY T1.[Email])
        ,   ID      =   T1.ID
        ,   Name    =   T1.Name
        ,   EMail   =   T1.[EMail]
        ,   Tag     =   ''
    FROM    T1
;
UPDATE T1
    SET Tag = CASE RowNum WHEN 1 THEN '' ELSE 'dup' END
;

SELECT *
FROM @Table


text:
Q: ScheduledThreadPoolExecutor initialize resource on thread start and inject it to worker-runnable I have a resource (in my case zmq socket, but this detail can be ignored).
The resource is not thread safe, and can be used only from a thread, that opened connection.
I want to use it in ScheduledThreadPoolExecutor.
So my ideal workflow would be:

*

*thread on startup opens a connection

*every worker task should implement and interface (socketAware)

*socket from current thread gets injected to a worker via the method of the interface.
ScheduledExecutorService service = Executors.newScheduledThreadPool(5, new SocketAwareThreadFactory(socket));
service.scheduleAtFixedRate(new SocketAwareRunable(), 0, 5, TimeUnit.SECONDS);

public class SocketAwareThreadFactory implements ThreadFactory {
    private final Proxyable socket;

    SocketAwareThreadFactory(Proxyable socket) {
        this.socket = socket;
    }

    @Override
    public Thread newThread(@Nonnull Runnable action) {
        return new SocketAwareThread(socket, action);
    }
}

public class SocketAwareThread extends Thread {

    private final Socket proxy;

    public SocketAwareThread(Proxyable socket, Runnable action) {
        super(action);
        proxy = socket.proxy();
    }

    @Override
    public void run() {
        proxy.open();//connection opens here
        super.run();
    }
}

Is there any way now to propagate opened socket back to every Runable that is executed by this thread, except of using reflection ?
It looks like ThreadPoolExecutor.beforeExecute could do the trick, but it does not work with ScheduledThreadPoolExecutor, since runnable is not what I have submitted, but something already decorated.


text:
Q: How to Update List with jQuery in MVC 4 I am currently trying to create a settings page using a modified Index view. The goal is that the users get all settings displayed and can change all settings within one view and save all settings using one single button. The setting should be updated using Ajax.
My current approach:
View:

[ ... ]

@using (Ajax.BeginForm("Edit", "Settings", new AjaxOptions {UpdateTargetId = "result"}, new { @class = "form-horizontal", @id = "editSettings" } ))
{
    foreach (Setting item in ViewBag.Settings)
    {
        @Html.Partial("_SingleSetting", item)
    }
    <input type="submit" value="modify" />
}

Partial View to load the setting:

            @settingName

                @Html.EditorFor(model => model.Value)
                @settingDescription

Model:
[Table("Settings")]
public class Setting
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int SettingId { get; set; }

    public string Name { get; set; }

    [Required(AllowEmptyStrings = true)]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string Value { get; set; }
}

I am setting the ViewBag using ViewBag.Settings = _db.Settings.ToList();
The jQuery parses the Data to the following method:
    [HttpPost]
    public ActionResult Edit(IList<Setting> setting)
    {
        Console.WriteLine(setting.Count);
        return Content(""); // Currently for testing purposes only. Breakpoint is set to setting.Count
    }

Count throws an error because setting is null. I am quite unsure how to fix this problem.
Can someone can give me a hint?
This topic on SO already covers updating a Collection without Ajax. But I won't get the point.
Thank you for your help.

A: You are using an Ajax.BeginForm and ajaxifying the form once again with jQuery. That's not necessary. But the real problem with your code is the names of the input fields in your partial. You are not respecting the naming convention used by the default model binder for binding to lists.
Let's take a complete example (removing all noise such as Entity Framework for simplicity):
Model:
public class Setting
{
    public int SettingId { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

Controller:
public class SettingsController : Controller
{
    public ActionResult Index()
    {
        // No idea why you are using ViewBag instead of view model
        // but I am really sick of repeating this so will leave it just that way
        ViewBag.Settings = Enumerable.Range(1, 5).Select(x => new Setting
        {
            SettingId = x,
            Name = "setting " + x,
            Value = "value " + x
        }).ToList();
        return View();
    }

    [HttpPost]
    public ActionResult Edit(IList<Setting> setting)
    {
        // Currently for testing purposes only. Breakpoint is set to setting.Count
        return Content(setting.Count.ToString());
    }
}

View (~/Views/Settings/Index.cshtml):
@using (Html.BeginForm("Edit", "Settings", FormMethod.Post, new { @class = "form-horizontal", id = "editSettings" }))
{
    foreach (Setting item in ViewBag.Settings)
    {
        @Html.Partial("_SingleSetting", item)
    }
    <input type="submit" value="modify" />
}

@section scripts {

}

Settings partial (~/Views/Settings/_SingleSetting.cshtml):
@model Setting
@{
    var index = Guid.NewGuid().ToString();
    ViewData.TemplateInfo.HtmlFieldPrefix = "[" + index + "]";
}

<input type="hidden" name="index" value="@index" />

    @Html.LabelFor(x => x.Name)

        @Html.EditorFor(model => model.Value)

Notice how inside the partial it is necessary to change the HtmlFieldPrefix in order for the html helpers generate proper names for your input fields and respect the naming convention.

Alright, now let's cut the ViewCrap and do the things properly (i.e. using view models of course).
As always we start by writing a view model:
public class MyViewModel
{
    public IList<Setting> Settings { get; set; }
}

Then we adapt the controller:
public class SettingsController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();

        // you will probably wanna call your database here to
        // retrieve those values, but for the purpose of my example that
        // should be fine
        model.Settings = Enumerable.Range(1, 5).Select(x => new Setting
        {
            SettingId = x,
            Name = "setting " + x,
            Value = "value " + x
        }).ToList();
        return View(model);
    }

    [HttpPost]
    public ActionResult Edit(IList<Setting> setting)
    {
        // Currently for testing purposes only. Breakpoint is set to setting.Count
        return Content(setting.Count.ToString());
    }
}

View (~/Views/Settings/Index.cshtml):
@model MyViewModel

@using (Html.BeginForm("Edit", "Settings", FormMethod.Post, new { @class = "form-horizontal", id = "editSettings" }))
{
    @Html.EditorFor(x => x.Settings)
    <input type="submit" value="modify" />
}

@section scripts {

}

Editor template for the Settings model (~/Views/Settings/EditorTemplates/Settings.cshtml):
@model Setting

    @Html.LabelFor(x => x.Name)

        @Html.EditorFor(model => model.Value)

All works now by convention. No need to write any foreach loops. The @Html.EditorFor(x => x.Settings) call in the Index view analyzes the Settings property of the view model and detects that it is a collection of some other model (Setting in this case). So it will start looping through this collection and search for a corresponding editor template (~/Views/Settings/EditorTemplates/Setting.cshtml) which will automatically be rendered for each element of this collection. So you don't even need to be writing any loops in your view. And in addition to simplifying your code, now the Html.EditorFor(x => x.Value) in the editor template will generate proper names for the input field.


text:
Q: How the Vue JS component work in Twig x-template file I've been struggling for a week now trying to understand how the Vue component work within a Twig file with x-template.
I've test my code for number of time without any luck.

new Vue ({
 el: '#app',
 data: function () {
   return {
      fname: 'John',
      lname: 'Smith'
   }
 }
});

new Vue ({
 template: '#my-template',
 data: function () {
   return {
     fname: 'Paul',
     lname: 'Smith'
   }
  }
});

Test

<my-template></my-template>

A: If you are initializing Vue and want to use a component in it, you must register it. Component name and template ID are also two different things.

Vue.component('my-template', {
  template: '#my-html-template',
  data: function() {
    return {
      fname: 'Paul',
      lname: 'Smith'
    }
  }
})

new Vue({
  el: '#app',
  data: function() {
    return {
      fname: 'John',
      lname: 'Smith'
    }
  }
});

Test

  <my-template></my-template>

A: How about this setup? https://codepen.io/fuleinist/pen/KKwdwdp

  <my-template></my-template>

Then in your js file
var myTemplate = Vue.component('my-template', {
 template: '#my-template',
 props: {
    fname: String,
    lname: String,
},
 data: function () {
   return {
     fname: 'John',
     lname: 'Smith'
   }
 },
 });

new Vue({
  el: '#app',
  components: {
    myTemplate: myTemplate,
  },
})


text:
Q: decimal numbers in EXT.JS i want the number field to take 8 digits after the point instead it is taking only 4 and rounding the last digit:
i tried using decimalPercision:8, it is doing the same and adding zeros,
 {
        name: "latitude",
        fieldLabel: "<spring:message code='input.latitude' text='Latitude' />",
        xtype: "numberfield",
        decimalPercision:8,
        value:0
    },

A: You can use toFixed() function of javascript. toFixed convert numbers to string and keep specified number of decimals, like value.toFixed(8)


text:
Q: Implementing onChanged of MapChangeListener - why this lambda In my JavaFX, I attempted to have an ObservableMap<String, String> and a MapChangeListener that listens to keys and values changes(adding/removing a key or the corresponding value) and then does its job.
To make the listener be effective, the method to implement is:
void onChanged(MapChangeListener.Change<? extends K,? extends V> change)

What I first did, with a lambda expression, that doesn't generate any error:
map.addListener((MapChangeListener.Change<? extends String, ? extends String> change) -> {
    //code here to implement onChange method
}

And here is what I discovered, that still doesn't generate any error:
map.addListener((MapChangeListener<String, String>) change -> {
    //code here to implement onChange method
}

Note the position of the round brackets in this two different examples. The second seems to me to be a cast, but I really don't understand why this second option works.
Can anyone explain me this, please?
P.S.: Actually, I came accross this because I was dealing with a
ObservableMap<String, List<String>>,
that is a multimap, and the first "way" of the two above didn't work (with the right adjustments). /EDIT: I tried again with the first "way" and actually it does work, there was an error on the code I didn't notice END EDIT/. Then I tried with the second option, and it did work, and I was dazed. Then I discovered this same "behaviour" with a simple map <String, String> and this question has arisen.

A: These two are equivalent. The first one, you are defining the parameter of the lambda expression - note that your bracket covers the whole change parameter. This allows the compiler to know which overload to match it against.
The second one is simply a cast. You are telling the compiler what kind of method signature to match this lambda against. (MapChangeListener<String, String>) casts the whole lambda expression into a MapChangeListener, so the compiler knows that it really is addListener(MapChangeListener). Since you have defined the single parameter defined by MapChangeListener, the compiler doesn't complain that it is wrong either.
Edit
Now that I have a bit more time, I would give you some concrete example that will help you understand a little more in depth.
public class Foo {
    public final void bar(IntfA a) {}
    public final void bar(IntfB b) {}
    public final void bar(IntfC c) {}
}

@FunctionalInterface
public interface IntfA {
    void doSomething(Double a);
}

@FunctionalInterface
public interface IntfB {
    void doSomething(Integer a);
}

@FunctionalInterface
public interface IntfC {
    void doSomething(Double a);
}

public class Test {
    public static void main(String[] args)
    {
        Foo foo = new Foo();

        foo.bar(a -> {}); // Ambiguous
        foo.bar((Integer a) -> {}); // Okay, this is IntfB
        foo.bar((Double a) -> {}); // Ambiguous between IntfA and IntfC
        foo.bar((IntfC) a -> {}); // No longer ambiguous since you specified that it's IntfC
        foo.bar((IntfC) (a, b) -> {}); // Method signature does not match IntfC
    }
}

Edit 2
It seems like you need a little more help here.
When you define a method bar(IntfA), you are expecting an object of IntfA, regardless whether IntfA is an interface type or a class type.
Then, lambda expressions are just compile-time convenient syntax. When I write foo.bar((Integer a) -> {}), the compiler will eventually turn it into Java bytecodes (within .class file) that is equivalent to this:
foo.bar(new IntfB() {
    public void doSomething(Integer a) {
    }
});

That equivalence is what we call Anonymous Class.
The biggest and possibly only difference in using lambda is, it makes your code shorter. Sometimes it makes your code more readable, sometimes it makes your code less readable.
Since lambda reduces the amount of things that you need to type out, it is very easy to have a lambda expression that is ambiguous for the compiler when there are overload methods like in the example. Remember that the compiler needs to figure out which overload first, then it will help you to instantiate the object for you.
When you write foo.bar((Double a) -> {}), the compile notices that you have a lambda expression that takes in one Double parameter and returns nothing. It will then look at the three overloads of bar(). It notices that both bar(IntfA) and bar(IntfC) takes in a functional interface, and both interface's method takes in one Double parameter and returns nothing. At this point, the compiler is not sure whether it should generate bytecodes equivalent to which two set of codes:
Choice 1:
foo.bar(new IntfA() {
    public void doSomething(Double a) {
    }
});

Choice 2:
foo.bar(new IntfC() {
    public void doSomething(Double a) {
    }
});

If you write foo.bar((IntfC) a -> {}), you are already hinting to the compiler that you want it to match foo.bar(IntfC) overload. The compiler sees that you have one parameter of unknown type, but since you have already tell it to match to IntfC, it will assume that parameter is Double.
Now to the last part, calling foo.bar(IntfA) doesn't automatically call the doSomething(Double a) method specified by IntfA. In my example the bar() methods did nothing, but normally people would write something useful.
Example again:
public final void bar(IntfB obj) {
    if (obj == null)
        System.out.println("I was waiting for an IntfB object but I got nothing!");
    else
        obj.doSomething(100);
}

foo.bar((Integer a) -> {
    System.out.println("I got " + a + " marks for my exam!");
});

This causes "I got 100 marks for my exam!" to be printed on the console.

A: Lambda in reality doesn't require its type to be expressed unless there is an ambiguity.
If you would not type change it would conflict with addListener(InvalidationListener) that has the same argument length. There are 2 ways of solving this, either by explicitly expressing the type (your first snippet) or by directing the compiler to the correct overload (second), which has nothing to do with lambda semantics.
To reiterate the second point, say you have
void print(String s)

and
void print(Integer i)

calling
print(null) would cause an ambiguity. The solution is print((String)null) which is of course not a type cast, as null has no type, but rather a compiler note.


text:
Q: generic requests on agatha does anyone know why I can't do this ?
public class CreateScenarioHandler :
GL.RRSL.RequestHandler<CommandRequest<ScenarioProfileData>,
                       CommandResponse<ScenarioProfileData>>

why is it imposible for Agatha to figure out the type of the generic Request. It is defined there. ?

Type 'GL.RequestResponse.CommandRequest`1[T]' cannot be exported as a schema type because it is an open generic type. You can only export a generic type if all its generic parameter types are actual types.

any ideas of how to do this. It feels so restrictive to have to create a request object for each type of operation.

A: I'm actually using generic requests/responses successfully.
The trick was to register closed generic requests/responses as known-types.
In order to achieve this, I'm using the following conventions:

*

*generic requests/responses can have only one generic parameter

*that generic parameter should has a generic constraint that specifies that  it should implement a given interface

I'm using this convention to construct every possible closed generic type
that I'm going to be using as request or response.
For example, I can have something like this:
interface IDtoWithId
{
 int Id { get; }
}

public class GetEntityRequest<TDto> : Request where TDto : IDtoWithId
{
   ....
}
public class UserDto : IDtoWithId
{
   public int Id { get; set; }
   public string Name { get; set; }
}

Then, when configuring Agatha, I'm using something like
this https://gist.github.com/916352 and doing:
....
configuration.Initialize();
KnownTypeProvider.ClearAllKnownTypes();
KnownTypeHelper.RegisterRequestsAndResponses(typeof(UserDto).Assembly);

The KnownTypeHelper registers the GetEntityRequest type as a
known-type and that allow me to handle that request using a handler
hierarchy like this:
public abstract class GetEntityHandler<TEntity, TDto> :
RequestHandler<GetEntityRequest<TDto>, GetEntityResponse<TDto>>
{
   ...
}

public class GetUserHandler : GetEntityHandler<User, UserDto>
{
}

I'm using this approach for the CRUD part of an application and it is
working very well.

A: The problem here has to do with how CommandRequest and CommandResponse are defined.
Agatha looks at the classes which extends Request and Response and add's them to the known types in the WCF.
When the server starts the service, WCF complains that the type CommandRequest is generic and can't be used. WCF if saying that it can't claim to know about a generic type.
When I define CommandRequest and CommandResponse as abstract, and then create classes like ScenarioIORequest/Response which extend CommandRequest and CommandResponse respectively with the apropiate type to be wrapped, WCF does not complain.
It feels like a waste that I have to define specific types when I would like to have generic requests and responses for different DTO. Maybe this will change at some point, but it seams to be WCF issue rather then the Agatha project issue.


text:
Q: access sql query to select from multiple tables I am new to sql and have a simple question. I have two tables, t1 and t2, both have same fields A, B, C,D
I want to create a sql that
select
   *
from t1
where (t1.A exist in t2.A)
AND (combination (ABC) from t1 not exist in t2)

I am using access 2013
Thank you!

A: You may try using exists logic:
SELECT t1.*
FROM table1 t1
WHERE
    EXISTS (SELECT 1 FROM table2 t2 WHERE t2.A = t1.A) AND
    NOT EXISTS (SELECT 1 FROM table2 t2 WHERE t2.B = t1.B AND t2.C = t1.C);

A: Something like this may work:
SELECT *
FROM t1
WHERE
    A in (SELECT A from t2) AND
    NOT EXISTS (
        SELECT *
        FROM t2
        WHERE t1.B = t2.B AND
        t1.C = t2.C AND
        t1.D = t2.D
    );


text:
Q: Laravel Eloquent after save id becomes 0 It's a table migrated from https://github.com/lucadegasperi/oauth2-server-laravel
In the table oauth_clients, the field data type of id is varchar(40), not int.
$name = Input::get('name');
$id = str_random(40);
$secret = str_random(40);

$client = new oauthClient;
$client->name = $name;
$client->id = $id;
$client->secret = $secret;
$client->save();

After save(); the $client->id become '0', not the string I assigned.
That makes the following relation table save fail.
$endpoint = new OauthClientEndpoint(array('redirect_uri' => Input::get('redirect_uri));
$client->OauthClientEndpoint()->save($endpoint);

I checked the $client->id: after save, it becomes 0 and I get an error including this one:
(SQL: insert into `oauth_client_endpoints` (`redirect_uri`, `client_id`, `updated_at`, `created_at`) values (http://www.xxxxx.com, 0, 2014-09-01 11:10:16, 2014-09-01 11:10:16))

I manually saved an endpoint to prevent this error for now. But how do I resolve this issue?
Here's my model:
class OauthClient extends Eloquent {

  protected $table = 'oauth_clients';

  public function OauthClientEndpoint(){
    return $this->hasOne('OauthClientEndpoint', 'client_id', 'id');
  }

}

class OauthClientEndpoint extends Eloquent {

  protected $table = 'oauth_client_endpoints';
  protected $fillable = array('redirect_uri');

  public function OauthClient(){
    return $this->belongsTo('OauthClient', 'client_id', 'id');
  }

}

class CreateOauthClientsTable extends Migration {
  public function up() {
    Schema::create('oauth_clients', function (Blueprint $table) {
      $table->string('id', 40);
      $table->string('secret', 40);
      $table->string('name');
      $table->timestamps();

      $table->unique('id');
      $table->unique(array('id', 'secret'));
    });
  }

  public function down() {
    Schema::drop('oauth_clients');
  }
}

class CreateOauthClientEndpointsTable extends Migration {
  public function up() {
    Schema::create('oauth_client_endpoints', function (Blueprint $table) {
      $table->increments('id');
      $table->string('client_id', 40);
      $table->string('redirect_uri');

      $table->timestamps();

      $table->foreign('client_id')
        ->references('id')->on('oauth_clients')
        ->onDelete('cascade')
        ->onUpdate('cascade');

    });
  }

  public function down() {
    Schema::table('oauth_client_endpoints', function ($table) {
      $table->dropForeign('oauth_client_endpoints_client_id_foreign');
    });

    Schema::drop('oauth_client_endpoints');
  }
}

A: When you are setting your own ID and not using auto_increment be sure to add public $incrementing = false; to that model. In your case you want:
class OauthClient extends Eloquent {

  public $incrementing = false;
  protected $table = 'oauth_clients';

  public function OauthClientEndpoint(){
    return $this->hasOne('OauthClientEndpoint', 'client_id', 'id');
  }

}

This is a tiny red block in the huge Laravel documentation:

Note: Typically, your Eloquent models will have auto-incrementing keys. However, if you wish to specify your own keys, set the incrementing property on your model to false.


text: Q: Merging two allure reports into one How can we merge two set of allure reports into one? I have two seperate set of project repositories which I need to run seperately and it generates indiviual Allure reports. Now I neeed to merge both the allure reports into one and present as a combination.


text:
Q: Hibernate: Enabling lazy fetching in Criteria API I am writing a query against a domain model where (for whatever reason) a one-to-many association is mapped with lazy="false". In my particular query, I'd rather fetch that collection lazily, because I don't care about its contents. How can I reenable laziness for my particular query? Is this possible at all?
So far, I looked at Criteria.setFetchMode, but FetchMode.LAZY is merely a deprecated alias for FetchMode.SELECT ...
Changing the mapping would probably be ideal, but I'd rather not risk affecting the existing queries.
Edit: We use Hibernate 3.3.2

A: In case somebody stumble across this (like me), please refer to this. It appears that this was a Hibernate documentation error, and FetchMode.SELECT does cause a lazy load.

A: The accepted answer is wrong. Hibernate allows you to lazy fetch in criteria something that is by default eager in the mapping. Simply call
criteria.setFetchMode("propertyName", FetchMode.SELECT);

I have tried this and it worked. FetchMode.LAZY is marked deprecated in the source code, and all it does is point to FetchMode.SELECT
Hibernate code:
public static final FetchMode LAZY = SELECT;

A: I am not an expert myself, but browsing through the Hibernate book and consulting with a colleague didn't give me any hint that this would be possible, rather the contrary.
Yours seems to be an unusual situation, not covered by Hibernate. The typical use case is the opposite: to use lazy fetching by default, and selectively enable eager fetching for queries where it is justified.


text:
Q: Allow multiple files to be uploaded I have a script I found online that I modified a little. I'd like to allow five files to be uploaded at one. Here is my script:

// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER','../uploads/');

// Maximum allowed file size, Kb
// Set to zero to allow any size
define('MAX_FILE_SIZE', 10240);

// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','my info');

// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array('jpg', 'jpeg', 'png', 'gif');

// rename file after upload? false - leave original, true - rename to some unique         filename
define('RENAME_FILE', true);

// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING', '');

// Need uploads log? Logs would be saved in the MySql database.
define('DO_LOG', true);

// MySql data (in case you want to save uploads log)
define('DB_HOST','my info'); // host, usually localhost
define('DB_DATABASE','my info'); // database name
define('DB_USERNAME','my info'); // username
define('DB_PASSWORD','my info'); // password

/*CREATE TABLE uploads_log (
  log_id int(11) unsigned NOT NULL auto_increment,
  log_filename varchar(128) default '',
  log_size int(10) default 0,
  log_ip varchar(24) default '',
  log_date timestamp,
  PRIMARY KEY  (log_id),
 KEY (log_filename)
);*/

####################################################################
###  END OF SETTINGS.   DO NOT CHANGE BELOW
####################################################################

// Allow script to work long enough to upload big files (in seconds, 2 days by default)
@set_time_limit(172800);

// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");

function showUploadForm($message='') {
  $max_file_size_tag = '';
  if (MAX_FILE_SIZE > 0) {
    // convert to bytes
    $max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."'         type='hidden' >\n";
  }

  // Load form template
  include ('index.php');
}

// errors list
$errors = array();

$message = '';

// we should not exceed php.ini max file size
$ini_maxsize = ini_get('upload_max_filesize');
if (!is_numeric($ini_maxsize)) {
  if (strpos($ini_maxsize, 'M') !== false)
    $ini_maxsize = intval($ini_maxsize)*1024*1024;
  elseif (strpos($ini_maxsize, 'K') !== false)
    $ini_maxsize = intval($ini_maxsize)*1024;
  elseif (strpos($ini_maxsize, 'G') !== false)
    $ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
}
if ($ini_maxsize < MAX_FILE_SIZE*1024) {
  $errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less         than script's MAX_FILE_SIZE";
}

// show upload form
if (!isset($_POST['submit'])) {
  showUploadForm(join('',$errors));
}

// process file upload
else {

  while(true) {

    // make sure destination folder exists
    if (!@file_exists(DESTINATION_FOLDER)) {
      $errors[] = "Destination folder does not exist or no permissions to see it.";
      break;
    }

    // check for upload errors
    $error_code = $_FILES['filename']['error'];
    if ($error_code != UPLOAD_ERR_OK) {
      switch($error_code) {
        case UPLOAD_ERR_INI_SIZE:
          // uploaded file exceeds the upload_max_filesize directive in php.ini
          $errors[] = "File is too big (1).";
          break;
        case UPLOAD_ERR_FORM_SIZE:
          // uploaded file exceeds the MAX_FILE_SIZE directive that was specified in         the HTML form
          $errors[] = "File is too big (2).";
          break;
         case UPLOAD_ERR_PARTIAL:
          // uploaded file was only partially uploaded.
          $errors[] = "Could not upload file (1).";
          break;
        case UPLOAD_ERR_NO_FILE:
          // No file was uploaded
          $errors[] = "Could not upload file (2).";
          break;
        case UPLOAD_ERR_NO_TMP_DIR:
          // Missing a temporary folder
          $errors[] = "Could not upload file (3).";
          break;
        case UPLOAD_ERR_CANT_WRITE:
          // Failed to write file to disk
          $errors[] = "Could not upload file (4).";
          break;
        case 8:
          // File upload stopped by extension
          $errors[] = "Could not upload file (5).";
          break;
      } // switch

      // leave the while loop
      break;
    }

    // get file name (not including path)
    $filename = @basename($_FILES['filename']['name']);

    // filename of temp uploaded file
    $tmp_filename = $_FILES['filename']['tmp_name'];

    $file_ext = @strtolower(@strrchr($filename,"."));
    if (@strpos($file_ext,'.') === false) { // no dot? strange
      $errors[] = "Suspicious file name or could not determine file extension.";
      break;
    }
    $file_ext = @substr($file_ext, 1); // remove dot

    // check file type if needed
    if (count($exts)) {   /// some day maybe check also $_FILES['user_file']['type']
      if (!@in_array($file_ext, $exts)) {
        $errors[] = "Files of this type are not allowed for upload.";
        break;
      }
    }

    // destination filename, rename if set to
    $dest_filename = $filename;
    if (RENAME_FILE) {
      $dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
    }
    // append predefined string for safety
    $dest_filename = $dest_filename . APPEND_STRING;

    // get size
    $filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);

    // make sure file size is ok
   if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
      $errors[] = "File is too big (3).";
      break;
    }

    if (!@move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
      $errors[] = "Could not upload file (6).";
      break;
    }

    if (DO_LOG) {
      // Establish DB connection
      $link = @mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
      if (!$link) {
        $errors[] = "Could not connect to mysql.";
        break;
      }
      $res = @mysql_select_db(DB_DATABASE, $link);
      if (!$res) {
        $errors[] = "Could not select database.";
        break;
      }
      /*$m_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
     $m_size = $filesize;
      $m_fname = mysql_real_escape_string($dest_filename);
      $sql = "insert into _uploads_log (log_filename,log_size,log_ip) values         ('$m_fname','$m_size','$m_ip')";
      $res = @mysql_query($sql);
      if (!$res) {
        $errors[] = "Could not run query.";
        break;
      }*/
      @mysql_free_result($res);
      @mysql_close($link);
    } // if (DO_LOG)

   // redirect to upload success url
    header('Location: ' . SUCCESS_URL);
    die();

    break;

  } // while(true)

  // Errors. Show upload form.
  $message = join('',$errors);
  showUploadForm($message);

}

?>

and my html form looks like:
<form method="post" enctype="multipart/form-data" action="file-upload.php">

<?php echo $message; ?>
<?php echo $max_file_size_tag; ?>
        Please select file to upload:     <input multiple type="file" size="20" name="filename">
     <input type="submit" multiple value="Upload" name="submit">

    Are you a bot?
<input type=checkbox name=honeypot value=1>

</form>

Like I said, I only want to allow 5 files to be uploaded at one so that the total size of the upload doesn't exceed 10 mb's. Thank you in advance!

A: You can use two options here.

*

*Setting the limit on client side
     By clicking the upload button you can call a JavaScript function and check the number of files are greater than 5, then show an alert message and stops the post function.
Visit How to limit maximum items on a multiple input (<input type="file" multiple />)

*Setting the limit on server side (PHP script)
     Your current script will upload only one file even if you are selecting multiple files. In order to handle multiple uploads you have to loop the $_FILES array through a foreach loop. And add a counter inside the foreach loop to process the first five files
Visit http://php.net/manual/en/features.file-upload.multiple.php


text:
Q: ¿Cómo solucionar el error "Primitivo JSON no válido"? Estoy enviando 4 parámetros a un JsonResult desde Ajax con Json:
$.ajax({
            type: "POST",
            url: '@Url.Action("GenerarCertificadosSeleccionados", "Firmar")',
            contentType: "application/json; charset=utf-8",
            data: {
                array_interesados: JSON.stringify(array_interesados),
                    id_charla: id_charla,
                    titulo_charla: titulo_charla,
                    fecha_charla: fecha_charla
                },
            dataType: "json",

Y al momento de ejecutar me aparece el error "Primitivo JSON no válido", pensé que se solucionaría con el JSON.strinfy(), pero no.
Aquí tengo mi JsonResult:
[HttpPost]
    public JsonResult GenerarCertificadosSeleccionados(List<ClsInteresado> array_interesados, string id_charla, string titulo_charla, string fecha_charla)
    {
        List<ClsInteresadoArchivo> temporal = new List<ClsInteresadoArchivo>();

        GenerarPdfs(array_interesados, id_charla, titulo_charla, fecha_charla);

        string[] archivos;

        try
        {
            archivos = ObtenerNombreArchivos();

            foreach (var item in array_interesados)
            {
                ClsInteresadoArchivo i = new ClsInteresadoArchivo();
                i.dni_Inter = item.dni_Inter;
                i.nombres_Inter = item.nombres_Inter;
                i.apePat_Inter = item.apePat_Inter;
                i.apeMat_Inter = item.apePat_Inter;

                temporal.Add(i);
            }

            for (int i = 0; i < archivos.Count(); i++)
            {
                temporal[i].nombreArchivo_Inter = archivos[i];
            }

        }
        catch (Exception e)
        {
            return Json("error");
        }

        return Json(temporal);
    }

Como pueden ver, estoy enviando una lista y 3 datos únicos. Quisiera saber qué estoy haciendo mal.

A: Tu JSON esta mal generado
Este es un JSON normal
var array_interesados= {
                   id_charla: id_charla,
                    titulo_charla: titulo_charla,
                    fecha_charla: fecha_charla
};

Este es un JSON como el que tu necesitas, que contiene un array Notese el []
var array_interesados= [
                       { id_charla: id_charla,
                        titulo_charla: titulo_charla,
                        fecha_charla: fecha_charla},
                        { id_charla: id_charla2,
                        titulo_charla: titulo_charla2,
                        fecha_charla: fecha_charla2 },
                       ];

Para generar tu JSON con arrays dinamicamente podrias usar lo siguiente:
for(var i in tusDatos) {

    array_interesados.push({
        "id_charla" : tusDatos[i].id_charla,
        "titulo_charla"  : tusDatos[i].titulo_charla,
        "fecha_charla"       : itusDatos[i].fecha_charla
    });
}

Y mandas tu objeto en data de esta manera
      $.ajax({
        type: "POST",
        url: '@Url.Action("GenerarCertificadosSeleccionados", "Firmar")',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(array_interesados),
        dataType: "json",


text:
Q: how to process fetch response from an 'opaque' type? I'm trying to correctly interpret the response from a fetch call to an URL, that I think is a json string. I've tried a many variations based on similar posts here, but nothing is getting me useful data to work with. Here is one attempt:
fetch('http://serverURL/api/ready/', {method: "POST", mode: "no-cors"})
    .then(function(response) {
        response.json().then(function(data) {
            console.log('data:' + data);
        });
    })
    .catch(function(err) {
        console.log('Fetch Error :-S', err);
    });

This returns a syntax error in the console:

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
  the JSON data

So maybe its not JSON...if I put in a breakpoint on the console.log line, and hover over response (line above), I see the response object (?) with various fields:

Not sure how to interpret that...status:0 suggests it did not get a valid response. However, if I check the Network tab in the developer tools, and click on the fetch line, status there is 200, and the Response window/JSON section shows the message info that you also see if you just put the URL into the browser URL bar directly. As does the "Response payload" section, which shows the JSON string:

{"msg": "API is ready.", "success": true}

So...it looks like json, no? But fetch is unable to ingest this as json?
Here's another variation, but using response.text() instead of response.json()
fetch('http://serverURL/api/ready/', {method: "POST", mode: "no-cors"})
    .then((response) => {
        console.log(response);
        response.text().then((data) => {
            console.log("data:" + data);
    });
});

This prints the response object in the console (same as above: ok: false, status:0, type:opaque etc). The second console.log file prints nothing after data:.  If I use response.json, again I get the syntax error about end of data as above.
Any ideas? I realize the server may not be providing what fetch needs or wants, but, it does provide some info (at least when using the URL directly in the browser), which is what I need to then deal with, as json or text or whatever.

A: Essentially, you cannot access response body from an opaque request.

Adding mode: 'no-cors' won't magically make things work. Browsers by
  default block frontend code from accessing resources cross-origin. If
  a site sends Access-Control-Allow-Origin in its responses, then
  browsers will relax that blocking and allow your code to access the
  response.
But if a site doesn't send the Access-Control-Allow-Origin header in
  its responses, then there's no way your frontend JavaScript code can
  directly access responses from that site. In particular, specifying
  mode: 'no-cors' won't fix that (in fact it'll just make things worse).

From https://stackoverflow.com/a/43268098/1666071
And also from fetch documentation:

no-cors — Prevents the method from being anything other than HEAD, GET
  or POST, and the headers from being anything other than simple
  headers. If any ServiceWorkers intercept these requests, they may not
  add or override any headers except for those that are simple headers.
  In addition, JavaScript may not access any properties of the resulting
  Response. This ensures that ServiceWorkers do not affect the semantics
  of the Web and prevents security and privacy issues arising from
  leaking data across domains.

https://developer.mozilla.org/en-US/docs/Web/API/Request/mode


text:
Q: Why is this Javascript/HTML5 Canvas not working? I am trying to create a simple game and on pressing the right and left buttons a picture is supposed to move (and vary between another picture, trexf and trexb).
<canvas id="canvas" width="640" height="480" >
    Browser doesn't support canvas.
</canvas>

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var width, height, rightKey = false, leftKey = false, upKey = false, downKey = false, rex_x, rex_y = 300, trexf, trexb;

trexf = new Image('Trexf.png');
trexb = new Image('Trexb.png');

function clearCanvas() {
    canvas.width = canvas.width;
}

function drawRex() {
    if(rightKey) {
        rex_x += 5;
    } else if(leftKey) {
        rex_x -= 5;
    }

    ctx.drawImage(trexf, rex_x, rex_y);
    if(rightKey == false || leftKey == false) {
        ctx.drawImage(trexb, rex_x, rex_y);
    }
}

function loop() {
    clearCanvas();
    drawRex();
}

function keyDown(e) {
    if(e.keyCode == 39)
        rightKey = true;
    else if(e.keyCode == 37)
        leftKey = true;
}

function keyUp(e) {
    if(e.keyCode == 39)
        rightKey = false;
    else if(e.keyCode == 37)
        leftKey = false;
}

function init() {

    ctx.canvas.width = window.innerWidth - 30;
    ctx.canvas.height = window.innerHeight - 30;

    document.addEventListener('keydown', keyDown, false);
    document.addEventListener('keyup', keyUp, false);

    rex_x = canvas.width / 2;

    setInterval(loop, 1000);
}

init();

Try it on JSFiddle.
Why does this not work as I expect?

A: This works for me in Chrome, but your draw interval is too large (1 second) so the key up event is firing before the redraw.

A: dial down your interval timer delay count:
http://jsfiddle.net/bTvBn/42/
It works fine now.


text:
Q: Conditional yup validation based on state I have this validation:
    ticket: yup
      .number()
      .required(I18n.t("is_required"))
      .when([], {
        is: () => {
          return timeFramedExperience;
        },
        then: yup.number().nullable(),
      }),
    max_p: yup
      .number()
      .required(I18n.t("is_required"))
      .when([], {
        is: () => {
          return timeFramed;
        },
        then: yup.number().nullable(),
      }),

timeFramed is a react hook state set to true. I want these fields, max_p and ticket to not be required when timeFramed is true.
but, on submit, I get this error:
Cannot read properties of undefined (reading 'reduce')

A: *

*Use different schemas as OP mentioned:

   condition ? : schema1 : schema2

*Use yup context:

   yup
   .string()
   .when("$condition", (condition, schema) =>
     condition ? schema : schema.required()
     // Here `condition` is passed as context to yup.
   )

*Use a hidden field or add the state to the form somehow.

I created a codesandbox which uses react-hook-form and yup to validate and has implemented the 3 solutions mentioned above.
If your state may change during the time user is filling in the form, be careful about calling trigger. Calling trigger before your state updates in the next render could lead to bugs.


text:
Q: Set-Cookie Response Header not setting cookie? Possible path issue I have a page:
http://localhost:4201/login
Which, when the user hits login, makes a request to:
http://localhost:4201/api/login/authenticate
Which is then proxied to:
https://myserver.com/xms_webapp_dev10/login/authenticate
Whose response contains the following set-cookie response header:

set-cookie: JSESSIONID=B82FB6A0B9E66E822977F954A5ACB14B; Path=/xms_webapp_dev10; HttpOnly

The problem is that the cookie is not getting set on the client browser. This exact same code works in different environments. The only difference I can see between a working environment and this one is the Path value of the cookie. In a working environment Path=/ but here it is Path=/xms_webapp_dev10
Given this setup, any thoughts on why path might be causing an issue or what the problem might be?
Does the path http://localhost:4201/login need to contain /xms_webapp_dev10?
Or is some other URL wrong? Or something totally different is wrong?

A: The cookie is set, but only for requests on path /xml_webapp_dev10, therefore you will never see it sent with a request made to /api/.... When proxying requests, you must change the cookie paths if you want the cookies to be sent by your browser.


text:
Q: I have Anatidaephobia - can we change the duck as it is always watching me? Related to this question, is there an option to change the duck to something like a large purple Gorilla? I suffer from Anatidaephobia and it is realized when the duck is actually there, watching, always watching.
No, stop, please, I didn't mean to spill my water. No, please, stop looking at me like that.
I know! I know!
I'm a bad coder! Stop reminding me! IT WASN'T MY FAULT THAT I FORGOT CASE-SENSITIVITY!
I'll never do it again, coding duck, I promise, VBA is never a solution to anything.

A: The duck's been gone for days. If you're still seeing the duck... erm, I'd be a little worried.


text:
Q: Page Fault on Call Instruction I am trying to boot a custom fork of Apple's XNU kernel (sources available here). The kernel is triple-faulting on line 325 of start.s.
Examining the QEMU log points to a page fault for the address 0x10BFF8. This address is one 4K page + 8 bytes before the PML4, which is located at address 0x10D000. Thing is, though, I do not know why the call instruction would page-fault like this. Does anyone have any thoughts?


text:
Q: How much does the C standard library extensibility affect C++ programs? Take this code:
int issuecode(int i)
{
  return 2 * i;
}

int main(int argc, char **argv)
{
  return issuecode(argc);
}

The way I understand it, if compiled as a C program, it will have undefined behaviour. I reason based on these standard quotes:
C99, 7.26 (or C11, 7.31)

The following names are grouped under individual headers for convenience. All external names described below are reserved no matter what headers are included by the program.

C99, 7.26.2 (or C11, 7.31.2)

Function names that begin with either is or to, and a lowercase letter may be added to the declarations in the <ctype.h> header.

C99, 7.1.3 (or C11, 7.1.3)

*

*Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.
[...]

*

*All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.

*[...] If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

Based on the above, I believe the function name issuecode is actually reserved for use in <ctype.h>, and so the program technically has UB.
Question 0 (sanity check): Is my reading of the standard correct and the program's behaviour technically undefined?
Question 1: Will the program have UB if compiled as C++ code?
I believe the answer is "no," as from the following quotes, I'd say the "future library directions" of C are not part of the C++ standard library, but I am not really sure.
C++11, 21.7

*

*Tables 74, 75, 76, 77, 78, and 79 describe headers <cctype>, <cwctype>, <cstring>, <cwchar>, <cstdlib> (character conversions), and <cuchar>, respectively.

*The contents of these headers shall be the same as the Standard C Library headers <ctype.h>, <wctype.h>, <string.h>, <wchar.h>, and <stdlib.h> and the C Unicode TR header , respectively, with the following modifications:

None of the "following modifications" mentions the additional reserved identifiers. Table 74 is a taxative list of function names like isdigit and isalnum.
C++11, C.2

1. This subclause summarizes the contents of the C++ standard library included from the Standard C library. It also summarizes the explicit changes in definitions, declarations, or behavior from the Standard C library noted in other subclauses (17.6.1.2, 18.2, 21.7).
7. The C++ standard library provides 209 standard functions from the C library, as shown in Table 153.

Again, table 153 is a taxative list.
Question 2: Assuming I am wrong on question 1 and the program actually does have UB in C++ as well, would the following change affect this?
namespace foo {

  int issuecode(int i)
  {
    return 2 * i;
  }

}

using namespace foo;

int main(int argc, char **argv)
{
  return issuecode(argc);
}

Note: The standard quotes are taken from drafts N1256 (C99), N1570 (C11) and N3242 (C++11), which are the latest publically available drafts for the respective language versions.

A:
The following names are grouped under individual headers for convenience. All external names described below are reserved no matter what headers are included by the program.

There is a predefined list of functions that are reserved, if your function does not conflict name wise there is no issue.

Function names that begin with either is or to, and a lowercase letter may be added to the declarations in the <ctype.h> header.

The operative term there is may be added to the <ctype.h> header. The "is or to" bit is just guidance on organization of declarations.
So there never really was undefined behavior there...
As for C++ I think this follows the same idea take for example:
namespace foo{
  int isupper ( int c );
}

#include <cctype>
using namespace foo;
int main(void){
    isupper(92);
}

That should produce a compiler error because your function collides name wise with the C function, but due to namespaceing this is easily fixable by either appending an std:: or a foo:: to the beginning of the call.

A: C++11 17.6.1.2 Headers

172) The C standard library headers (Annex D.5) also define names within the global namespace, while the C ++ headers for C
  library facilities (17.6.1.2) may also define names within the global namespace.
In the C ++ standard library, however, the declarations (except for
  names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is
  unspecified whether these names are first declared within the global namespace scope and are then injected
  into namespace std by explicit using-declarations (7.3.3).

So if you don't include <cctype> the behavior is well-defined. If you do, it is unspecified.


text:
Q: Misaligned UILabel I have a view placed within a scrollview, and within this view there is a UILabel.
The UILabel is defined as following:
label_ = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
and without autoresizing mask.
When I turn on 'Color misaligned images' in Instruments in the 'Core Animation' tool, all the views are ok but the single UILabel is marked as misaligned.
What am I missing here?

A: Alignment.  You are missing alignment.
EDIT:  Sorry, couldn't help myself.  I've never used that functionality in X-code, but my advice would be if the view looks ok in the app, then who cares what IB thinks...


text:
Q: Distnace route sequence calculate based on gps cordinates in presto sql within multiple store sample
How we can calculate Output in below criteria:

*

*Area level

*find out the nearest store from the "starting point" within the area

*"starting point" will be 1st store and the nearest store will be 2nd store

*From the 2nd store which one is the nearest 3rd store

*this will be a sequence of stores

Cross join gives me each store's location but the output is required as per the above steps.


text:
Q: Puttin a imgae on top of another HTML

   .........

No, this didn't work, the animal.png is below the back.png, I want it to be on top.
I like  tag because it allows to scale the image size.

A: Z-index requires that the position property is not static (which is the default value for the property). Try this:
#animal
{ position: relative; z-index: 1;}


text:
Q: Hiding a portion of the UI in android I have a group of controls (edittexts, buttons etc..) which I want to show/hide programmatically, without showing/hiding them one by one. I have read about fragments and view groups but couldn't figure out how to use them for this purpose. How to do this, any examples?

A: The simplest method would be to wrap the portions you want to hide in a single Layout container with an ID (LinearLayout, RelativeLayout, etc - whichever you need).  Then programmatically set the visibility.
LinearLayout myLayout = (LinearLayout) findViewById(r.layout.myLayout);
myLayout.setVisibility(View.GONE);

or
myLayout.setVisibility(View.VISIBLE);

You could also start the layout either visible or not in the XML.

A: View.setVisibility(View.INVISIBLE) or View.setVisibility(View.VISIBLE)
Will control visibility, you can also use GONE but that may change your layout, which could or couldn't be desired.


text:
Q: Find regex in file with boost I'd like to do something like this:
boost::regex re("tryme");
ifstream iss;
iss.open("file.txt");
istream_iterator<string> eos;
istream_iterator<string> iit (iss);

find(iit,eos,bind2nd(boost::regex_match),re));

The errors are following:

Could not find a match for 'bind2nd<_Fn2,_Ty>(bool (*)       (BidiIterator,BidiIterator,match_results &,const basic_regex &,unsigned long))'
Could not find a match for 'find(istream_iterator,int>,istream_iterator,int>,undefined,regex)'

Could you please help me to do it correctly? Thanks.

A: The first problem is that std::find() tries to match values, i.e., you need to replace std::find() by std::find_if(). That's simple to do.
The next problem is that boost::regex_match isn't one function but a family of functions. std::bind2nd() has no idea which member of this family you want to match against. Also, the function overload you apparently want to use takes three, not two, arguments: the last argument of type boost::match_flag_type is defaulted. I got it to work with std::bind() using this:
std::bind(static_cast<bool (*)(std::string const&,
                               boost::regex const&,
                               boost::match_flag_type)>(&boost::regex_match),
         std::placeholders::_1, re);

If you really want to use std::bind2nd() it is probably easiest to create a simple forwarding function:
bool my_regex_match(std::string s, boost::regex const& r) {
    return boost::regex_match(s, r);
}

void f() {
    boost::regex re("tryme");
    std::ifstream iss(file.txt);
    std::find_if(std::istream_iterator<std::string>(iss),
             std::istream_iterator<std::string>(),
             std::bind2nd(std::ptr_fun(&my_regex_match), re));
}

The std::bind2nd() template cannot really work with raw function pointers. This is why std::ptr_fun() needs to be used. In general, when any of the standard functions called *_fun() need to be used, the fun actually stops: these functions cannot cope with functions taking arguments by reference. Thus, my_regex_match() takes its std::string argument by value: std::bind2nd() would try to create a function object taking a reference to reference as argument otherwise. This is another reason why you might want to use std::bind() or boost::bind().


text:
Q: MediaWiki on MAMP, OSX 10.8.5: Unknown error in PHP's mail() function I maintain a Mediawiki website, and until recently, everything was running fine. Users could login, create pages, register email address, etc.
But when one of my user tried to make a new account, she never receive the email confirmation from the server, but there never was any error message. Previously, users would receive something from 'apache@myurl.org' with the link and everything. I dabbled with the issue, and tried switching to another email address, going through the preference menu. However, after entering the new email address, the page showed the following error message, in bright red:

Error sending mail: Unknown error in PHP's mail() function."

I tried to create a test user, and after creating the account, I got this slightly different message (the email was a simple gmail, no weird characters or anything):

wikiname could not send your confirmation mail. Please check your email address for invalid characters.
      Mailer returned: Unknown error in PHP's mail() function."

I googled the error, and found that this error appears when admins would set up a SMTP server, nothing related to what I have done. I couldn't find any other helpful info.
I made sure the mysql database is accessible by the wiki user and that the LocalSettings.php has the correct mysql login info.
The emails settings have not changed in LocalSettings.php  (and have worked before):
$wgEnableEmail = true;
$wgEnableUserEmail = true; # UPO
$wgEmergencyContact = "apache@myurl.org";
$wgPasswordSender = "apache@myurl.org";

The only other thing I can think of is that I changed the Apache port a while ago, but other users have created accounts and successfully verified their email since then.
I am running MAMP on OSX 10.8.5, with:

*

*MediaWiki 1.22.5

*php 5.5.10

*mysql 5.5.34

A: solution found on mediaWiki Docs.
Put the following into LocalSettings.php, making the necessary substitutions for yourEmailAccount and yourEmailPassword:
$wgSMTP = array(
        'host' => 'ssl://smtp.gmail.com',
        'IDHost' => 'gmail.com',
        'port' => 465,
        'username' => 'yourEmailAccount@gmail.com',
        'password' => 'yourEmailPassword',
        'auth' => true
);

Then install the packages required to send the mail.
$ sudo pear install mail
$ sudo pear install net_smtp

After this you may get an authentication failure type error. You will need to sign into the gmail account you are using and verify that the person that just signed in is you. You only need to verify this one time. (gmail will send you an email and you just follow the instructions)

A: I just figured it out!
For those who ran into the same problem, here is how I fixed it:

*

*Open MAMP

*Open the preference menu, select the PHP tab

*In the Cache drop-down menu, select 'APC' (mine was 'off')

*Click 'OK', then type in your admin password

Now go back to the wiki and resend the confirmation email.
I haven't tried the other cache options, but they might work too.

A: https://phabricator.wikimedia.org/T32260#1093954
Problem is includes/mail/UserMailer.php sets sendmail's -f option even if already set elsewhere (php.ini for instance).
Just comment out this line for now:
# $extraParams .= ' -f ' . $returnPath;


text:
Q: How can I separate the horizontal rule from the table. They are mixed together. I want the horizontal rule below my table My horizontal rule is mixed up with part of the information on a table
So, my issue is to create two separate tables side by side, instead of one table below the other like usual. I did something that made it work but now my
 tag is mixed together with the tables.

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★

That is the code. Can someone please help me put the horizontal rule below the table? As you can see from my code, the hr tag comes after closing the second table tag but my final output has mixed up the horizontal rule together with the table, instead of below it. What error have I made in my code? Any help would be appreciated, especially from my code. Somebody advise me on what's wrong with my code.
Also, I'm not pretty sure what is the work of the div tag since this was kinda an assignment if anybody can explain to me well, and why I put it in my code, I honestly don't know.

A: Change the styles of the
s to be displayed as inline:

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★

JSFiddle.

A:

table {
  float: left
}

hr {
  clear: both
}

Skills

    Sleeping
    ★★★★

    Eating
    ★★★

    Gaming
    ★★★★★

    Reading
    ★★★★★

A: Just an educated guess at this stage you have two

 have you tried

 for your second table? instead of left? Hope this helps!!

A: I've found the solution
I just had to put my two tables inside one main table, the two tables would be table data inside table rows

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★


text:
Q: Return value queue in Laravel 5.2 Can queue in Laravel 5.2 have a return value?
I need all data that processed in the queue has a return value. Is it possible?
Example that I needed : If the user request has been processed, so the results (form the database) will be returned to the user.

I read the documentation in (https://laravel.com/docs/5.2/queues) but the example described here is an asynchronous model (without return value).
Please advise..
Thank you.

A: Queues are for asynchornous calls. If you need to use queues, you should do something to get the return value, using dispatch, e-mails, etc.
If you need the response in your front-end, I think the best way is to use REDIS + socket.io. After process your queue, you send the message to REDIS and listen with socket.io (google for or try this guide: https://laracasts.com/discuss/channels/general-discussion/step-by-step-guide-to-installing-socketio-and-broadcasting-events-with-laravel-51).
If you need in your back-end only, use jobs (https://laravel.com/docs/5.2/queues#writing-job-classes).


text:
Q: Does the "MS Access Database" ODBC driver support multiple users? I'm writing a tool in Excel VBA that will need to write to a simple table on the organization's network. Several people will be using the tool to write to that table, possibly at the same time.
I had hoped to use the ODBC text driver to write to a CSV file to use as the table, but I see that it does not support multiple users.
What about the "MS Access Database" odbc driver? If I use ADO to create and manage that database, will multiple users be able to write to it at the same time?

A: Generally, yes. I run some web based applications using Access as the back end via ODBC and there has never been a problem with concurrency.
Be aware however that the ODBC driver is not IP based, it needs local or network share access to the database file.

A: Excel VBA can via DAO connect to the Access database file directly and with a maximum of 255 users concurrently.
No need to bother with ODBC.


text:
Q: deploy soaplib webservice with apache2 I have set up apache2 and mod_wsgi. I have a wsgi directory in which i have some python code saved in a *.wsgi file. The code is pasted below. In the web browser when i enter the url (localhost/wsgi/ape.wsgi) it displays the records returned from the database as a joined string.
What I am trying to do is deploy this as a webservice and be able to see its wsdl (localhost/wsgi/ape.wsgi/?wsdl). Is this possible? P.s. I am a newbie to Python. Thanks
import sys
sys.stdout = sys.stderr

import atexit
import threading
import cherrypy

from soaplib.wsgi_soap import SimpleWSGISoapApp
from soaplib.service import soapmethod
from soaplib.serializers.primitive import*

cherrypy.config.update({'environment': 'embedded'})

if cherrypy.__version__.startswith('3.0') and cherrypy.engine.state == 0:
    cherrypy.engine.start(blocking=False)
    atexit.register(cherrypy.engine.stop)

class Root(SimpleWSGISoapApp):
    @soapmethod(_returns=String)
    def index(self):
        """Get the data from the database and return list of rows"""
        cursor = self._get_db_handle()

        sql = """select name, source_comment from public.carpark where public_toilet = %s """ % 'TRUE'
        results = []
        cursor.execute(sql)
        rows=cursor.fetchall()

        for row in rows:
            results.append(str(row))

        joinedlist = ', '.join(results)
        return joinedlist
        cursor.close()

    def _get_db_handle(self, host='xxxx.xxxx.com',
               dbname='xxxx',user='xxxx',
               password='xxxx',mapped=False):
        """Get the database handle"""
        import psycopg2
        from psycopg2 import extras
        conn = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s'" % (dbname,user,host,password))
        if not mapped:
            db_handle = conn.cursor()
        else:
            db_handle = conn.cursor(cursor_factory=extras.DictCursor)
        return db_handle

    index.exposed = True

application = cherrypy.Application(Root(), script_name=None, config=None)


text:
Q: User profile image can not show in laravel 8 I'm using laravel 8. I have used jetstream for user registration. Profile photo feature is being used, But it did not show profile image.
I help from you good people.
#coding

A: Make sure the APP_URL is correct in your .env file including port. ie. if you are running on localhost and port 8000 your APP_URL should be APP_URL=http://127.0.0.1:8000.
If the profile photo is stored successfully and that didn't work try:

*

*Deleting the shortcut folder storage created at /project/public/

*run php artisan storage:link
The photo should show up.


text:
Q: Template Expression Doesn't allow for Computer Expression in lightning-input-field I have been trying to iterate through and access some data that I'm getting from an apex call.
I have a list of field IDs that I get from a field set something like
this.positionFieldIds=['Name', 'Id', 'Contacts']
While my records are something like
[{recordTypeId:'000', fields:{'Name':{displayValue:'Placeholder', value:'5'}, 'Id':{displayValue:'Placeholder', value:'5'}, 'Contacts':{displayValue:'Placeholder', value:'2345'}}

I was trying to access the value and prepopulate my form with values that I get from a wire call, but I was getting the
Template Expression Doesn't allow for Computer Expression in lightning-input-field error message and I wasn't sure how to populate the template accurately.
<template for:each={positionRecords} for:item="rec" for:index="index">
<lightning-record-edit-form key={rec.id} object-api-name="Account">
   <template for:each={positionFieldIds} for:item="field">
     <lightning-layout-item key={field}>
     <lightning-input-field field-name={field} variant="label-stacked" value={rec.fields[field].value}></lightning-input-field>
     </lightning-layout-item>
   </template>
</lightning-record-edit-form>
</template>

Any help would be greatly appreciated.

A: Your problem is the attribute expression value={rec.fields[field].value}.
What you need to do is shift the expression handling into your JavaScript so you have a simple array of tuples to iterate, something like:
this.fields = Object.keys(this.rec.fields).
    map(key => {
      return {
               name: key,
               value: this.rec.fields[key].value
             };
    });

You need to do this when you get your record back.
You can then simply iterate the this.fields array and access the name and value properties in the template, something like:
<template for:each={fields} for:item="field">
  <lightning-layout-item key={field.name}>
  <lightning-input-field field-name={field.name} variant="label-stacked" value={field.value}></lightning-input-field>
  </lightning-layout-item>
</template>


text:
Q: $a_n=2a_{n-1}+1$; prove $a_n+1=2^n(a_0+1)$ If the sequence $a_n$ satisfies $a_n = 2a_{n-1}+1$ for all $n \geq 1$, show that for every $n \geq 0$, we have $a_n+1 = 2^n(a_0+1)$.
I thought of letting $a_n = c^n$ and $a^{n-1} = c^{n-1}$ then solving that way, but the extra $1$ makes it difficult.

A: HINT: $$a_n=2a_{n-1}+1$$
$$a_n+1=2a_{n-1}+2=2(a_{n-1}+1)$$
$$a_n+1=2(a_{n-1}+1)=2^2(a_{n-2}+1)$$ and so on.
Can you prove now?


text:
Q: Breeze not sending unmapped properties How do you get breeze to send client side only unmapped properties to the server? I've tried this as Ctor, initializer Es5 properties .. nothing gets sent to the server as far as these custom fields I'm trying to send along..

A: So you have to mark the entityAspect modified (model.entityAspect.setModified())


text:
Q: If the universe is expanding, how can constants not change? My understanding is that the universe expanding includes even individual atoms and I would guess that would mean the orbits of electrons, etc. If this is so, for things to continue to "keep working" would not constants for different forces have to change?

A: I was confused about this, too, when hearing for the first time about cosmology. The expansion of the universe does NOT include individual atoms, humans, planets, stars or galaxies. If that would be the case, we would not be able to notice this expansion.
In the first two cases, the electromagnetic forces binding the objects together are magnitudes stronger than any gravitational force, and in the case of galaxies (and the objects in them), the mass/energy density of the galaxies is much higher than the average mass/energy density of the universe. Because of that, galaxies themselves have 'decoupled' from the expansion of the universe and form gravitationally bound objects.
The universe as a whole is modeled in the simplest cosmological models as a uniform 'fluid' of matter and radiation (and dark energy, although nobody knows what that is). This is useful, because in the early times the contrast in density was not as strong as today, and still today the universe seems to be quite uniform on very big scales (on average).
Since we observe galaxies drift apart from each other, is seems that 'everything' was closer together in the beginning, therefore more dense and hot. This is possible (even when, of course, everything still attracts everything else gravitationally), as long as for some reason everything was drifting apart from the beginning (the why of that is a different question). But even in the early universe, this expansion, describes by gravity, made the uniform content of the universe drift apart, hence expand, but this did NOT affect the elementary particles, because the forces that describes their behavior and bind them together (quarks to protons and neutrons; electrons, protons and neutrons to atoms, although is only happens after the universe has cooled enough so these bound states are possible) are much stronger than gravity.


text:
Q: How is FireSheep able to open devices in promiscuous mode? FireSheep is able to use pcap in promiscuous mode to listen to other computers on the network.  But promiscous mode requires root privileges, or at least access to /dev/bpf* on *nix machines.  How is this done?  Do Firefox extensions run with root privs?

A: It has run_privileged methods which run the required operations as root using OS-specific mechanisms such as AuthorizationCreate (OS X), pkexec (Linux) (but this is apparently not supported, yet), and of course return true on Windows (since pretty much everyone runs as admin anyway).