text:
Q: Why isn't there a printf formatter for Rational? Simple inclusion of a Rational in printf output can be accomplished using %s and show:
> printf "... %s ...\n" (show $ 123 % 456)
... 41 % 152 ...

However, it would be useful to be able to use the %f format code as well:
> printf "... %.30f ...\n" (123 % 456)
... 0.269736842105263157894736842105 ...

Note that formatting via a conversion to Double (eg using fromRational) would not allow the arbitrary precision I'm looking for:
> printf "... %.30f ...\n" (fromRational $ 123 % 456)
... 0.269736842105263160000000000000 ...

The %v code could be used to produce the same output as show, and perhaps some modifiers could be allowed with it.
Is there any reason why this shouldn't be accomplished with a custom formatter (an instance of PrintfArg (Ratio a))?
For reference, here's a standalone function that I'm using as a partial workaround:
showDecimal :: RealFrac a => Int -> a -> String
showDecimal n r = printf "%d.%0*d" (i :: Integer) n (abs d :: Integer)
  where (i, d) = (round $ r * 10^n) `quotRem` (10^n)

> printf "... %35s ...\n" (showDecimal 30 $ 123 % 456)
...    0.269736842105263157894736842105 ...

However, this doesn't allow the use of modifiers, and involves specifying widths in separate places.

A: The consensus in the comments seems to be, because nobody got around to writing one, and it seems like a good idea.
I'm answering my own question so it can be marked as answered. I'll add a comment if I or anyone else get around to implementing it.


text:
Q: Jmeter - Time by Jmeter sampler and time by curl ( time_total) is different for same call I am new to Jmeter . I have a http sampler in Jmeter that gives average response time for 10 iterations as
854 ms.
Then I am using curl to get the time for same call like this and everytime I am getting 1500 ms .
curl -w %{time_total}\\n  https://someapicall.

Question is does any one know why there may be such a difference between these two above calls and how to correct this.

A: This is because by default JMeter reuses the cached SSL context between iterations, so it is faster.
To disable this behaviour set in user.properties:

*

*https.use.cached.ssl.context=false

Another possible explanation is warmup. In your config jmeter has warmed up on first request while curl does everytime the full reinit, to compare you would need to keep the curl session opened, something similar to this:

*

*http://php.net//manual/fr/book.curl.php
You may try ab to compare with jmeter.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CoreAudio: How to detect there's no device behind RemoteIO without starting it? I'm trying to use kAudioUnitSubType_RemoteIO unit on Catalyst on a Mac where there's no microphone.
The problem is, the whole initialization of bus 1 (that's input) goes fine, including setting the format, even enabling the bus, but then it fails at AudioOutputUnitStart(unit) with some obscure error -66628 that's not even listed on osstatus.com.
However, if I start the unit with only the output bus 0, then it runs fine and plays my audio.
So, is there an easy way to detect the situation when there's no device behind RemoteIO without enumerating all the devices? Just by trying some function (set or get a parameter?) that will definitely fail.
Here is my code:
    // Instantiate the unit
    var desc = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_RemoteIO, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0)
    let comp = AudioComponentFindNext(nil, &desc)!
    var unit: AudioUnit!
    NotError(AudioComponentInstanceNew(comp, &unit), 51000)

    // Set maximum buffer size as recommended by Apple
    var maxFramesPerSlice = UInt32(Self.maxFramesPerSlice)
    NotError(AudioUnitSetProperty(unit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, &maxFramesPerSlice, SizeOf(maxFramesPerSlice)), 51003)

    // Set format and sample rate to the same as hardware output
    var descr = AudioStreamBasicDescription.canonical(isStereo: true, sampleRate: hardwareSampleRate)
    NotError(AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &descr, SizeOf(descr)), 51022)

    // Set render callback
    var callback = AURenderCallbackStruct(inputProc: stereoInputRenderCallback, inputProcRefCon: Bridge(obj: self))
    NotError(AudioUnitSetProperty(unit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Output, 1, &callback, SizeOf(callback)), 51008)

    // Enable input - required as it's disabled by default
    var enable: UInt32 = 1
    NotError(AudioUnitSetProperty(unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enable, SizeOf(enable)), 51021)

    NotError(AudioUnitInitialize(unit), 51007)

So it passes all that and only fails with OSStatus(-66628) here:
    NotError(AudioOutputUnitStart(unit), 51009)

I think there has to be some way of detecting the absense of the device before trying to start it.
Edit: ideally I'm looking for a cross-platform way (ioS/macOS)

A: I believe that checking whether the AudioStreamBasicDescription returned for kAudioDevicePropertyStreamConfiguration, kAudioObjectPropertyScopeInput has  mBuffers > 0 will indicate if a device is present.


text:
Q: How to retrieve serialcomm from a query? I'm currently learning how to create batch scripts, but so far I am doing just queries. I am able to get a list of the current hardware, device map and serial com on the following registry path
HKLM\hardware\devicemap\serialcomm

The problem is that every computer is displaying a different serialcomm on the same device. So I am trying to capture the serialcomm based on the device name.
My current code below:
reg query HKLM\hardware\devicemap\serialcomm
pause

Below is an updated code I have tried to get the serialcomm based on the hardware name, but is not working :(
set "Comm="
reg query HKLM\hardware\devicemap\serialcomm
if %%hardware%% = ProlificSerial0 set Comm=%%serialcomm%%
pause

The above code was created based on all the information I have found on multiple websites, but as I said, I am still learning queries and it is a little bit complicated for me adding more code.
I will appreciate if anybody can tell me what is wrong with the updated code.

A: I have no serialcomm on my machine but you can use this as reference:
@echo off

for /f "tokens=3* delims= " %%a in (
    'reg query HKLM\hardware\devicemap\pointerclass'
) do (
    set "pointer=%%a"

)

echo %pointer%
if "%pointer%" equ "REGISTRY\MACHINE\SYSTEM\ControlSet001\Services\mouclass" echo need to set something

A: You should pass the specific value you are looking for as an argument to your batch file. For instance, if your batch file is named RegSearch, the command line syntax should be Something like:
RegSearch ProlificSerial0

You should therefore do a little bit of syntax checking inside the batch file to make sure you aren't forgetting to specify the argument when you run the batch file.
In addition, you can add the /v parameter to the Reg Query command in order to look for a specific value (rather than looking through all the keys). You can then filter the query results with findstr to determine if it was successful.
The following code should do all of that:
@echo off
setlocal enabledelayedexpansion
if /i "%1"=="" goto syntax
set myValue=%1
for /f "tokens=3 delims= " %%a in ('reg query hklm\hardware\devicemap\serialcomm /v *%myValue%* ^| findstr /i %myValue%') do (
  set comm=%%a
  echo !comm!
)

goto :eof

:syntax
echo.
echo ERROR : invalid syntax. You must pass the value to look for as the first argument, for example:
echo RegSearch Prolificserial0

A: Here is a batch code with some explaining comments which I wrote a few weeks ago to program Atmel AVR controllers via a batch file using mySmartUSB MK2 being mounted as virtual serial communication port after having once the device driver installed. The code part for programming the fuse bits, flash and eeprom of the AVR controllers is replaced here by a simple information message.
The batch file determines the COM port number

*

*from one of several optional command line parameters (special option), or

*queries it automatically directly from Windows registry (default method), or

*asks the user of the batch file for the port number (fail safe method).

For the question the identification from Windows registry is the most interesting part.
DeviceInstance, HardwareID and ProductName must be adapted for the Prolific USB-to-Serial converter.
Look with Windows registry editor on registry key
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB

for the device instance identifier and hardware identifier (vendor and product identifier) for the Prolific USB-to-Serial converter.
@echo off
setlocal EnableExtensions
set "ComPort="
set "DeviceInstance=mySmartUSB2-0001"
set "HardwareID=VID_10C4&PID_EA60"
set "ProductName=mySmartUSB MK2"

cls
echo.
call :ProcessArguments %*
call :CheckPort

echo Serial port of %ProductName% is: COM%ComPort%
echo.
endlocal
pause
goto :EOF

rem The subroutine ProcessArguments processes the optional parameters of
rem the batch file. For this demo everything except COMx with x being a
rem number in range 1 to 255 is interpreted as unknown parameter.

:ProcessArguments
set "EmptyLine=0"
:NextArgument
if "%~1" == "" (
    if "%EmptyLine%" == "1" echo.
    goto :EOF
)
set "SerialPort=%~1"
if /I "%SerialPort:~0,3%" == "com" (
    set "ComPort=%SerialPort:~3%"
) else (
    echo ERROR: Unknown parameter: %1
    set "EmptyLine=1"
)
shift
goto NextArgument

rem The subroutine CheckPort checks the port number specified as parameter
rem on calling the batch file.

rem In case of no COM port number was specified as parameter, it attempts
rem to determine the COM port number for the device as defined at top of
rem the batch file directly from Windows registry. The registry query is
rem written to work for Windows XP and any later Windows.

rem Last in case of a valid COM port was whether passed to the batch file
rem via COMx parameter nor could the port number be determined from Windows
rem registry automatically, the user is prompted in a loop to enter a valid
rem port number.

:CheckPort
set "EmptyLine=0"
if not "%ComPort%" == "" goto VerifyPort

for /F "skip=2 tokens=1,3" %%A in ('%SystemRoot%\System32\reg.exe QUERY "HKLM\SYSTEM\CurrentControlSet\Enum\USB\%HardwareID%\%DeviceInstance%\Device Parameters" /v PortName 2^>nul') do (
    if /I "%%A" == "PortName" set "SerialPort=%%B" && goto GetPortNumber
)
goto EnterPort

:GetPortNumber
if /I "%SerialPort:~0,3%" == "com" (
    set "ComPort=%SerialPort:~3%"
    goto VerifyPort
)

:EnterPort
set "EmptyLine=1"
set "ComPort=4"
set /P "ComPort=Enter number of COM port (default: %ComPort%): "

:VerifyPort
for /F "delims=0123456789" %%I in ("%ComPort%") do set "ComPort="
if "%ComPort%" == "" goto EnterPort
if %ComPort% EQU   0 goto EnterPort
if %ComPort% GTR 255 goto EnterPort
if "%EmptyLine%" == "1" echo.
goto :EOF

I think, processing HKLM\HARDWARE\DEVICEMAP\SERIALCOMM is not advisable as it lists all serial devices including for example also modems and not only serial ports. Also with hardware identifier known for the device, the COM port number can be found out more quickly directly as demonstrated above.
The DeviceInstance identifier often ends with an incrementing number in case of several devices with same vendor and product identifier are connected at the same time on different USB ports.
So for supporting multiple Prolific USB-to-Serial converters connected on same computer it would be better to query first just the hardware identifier to get all device instance identifiers.
Here is a very simple example for ATEN USB to Serial Bridge adapter:
@echo off
setlocal EnableExtensions
set "HardwareID=VID_0557&PID_2008"
set "RegistryPath=HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB"
set "ProductName=ATEN USB to Serial Bridge"
set "DeviceFound=0"

cls
echo.
for /F "delims=" %%I in ('%SystemRoot%\System32\reg.exe QUERY "%RegistryPath%\%HardwareID%" 2^>nul') do call :GetPort "%%I"

if "%DeviceFound%" == "0" echo WARNING: Could not find any %ProductName%.

echo.
endlocal
pause
goto :EOF

:GetPort
set "RegistryKey=%~1"
if /I not "%RegistryKey:~0,71%" == "%RegistryPath%\%HardwareID%\" goto :EOF

for /F "skip=2 tokens=1,3" %%A in ('%SystemRoot%\System32\reg.exe QUERY "%~1\Device Parameters" /v PortName 2^>nul') do (
    if /I "%%A" == "PortName" set "SerialPort=%%B" && goto OutputPort
)
goto :EOF

:OutputPort
set "DeviceFound=1"
set "DeviceNumber=%RegistryKey:~-1%"
echo %DeviceNumber%. %ProductName% is %SerialPort%.
goto :EOF

Note: Both batch code examples do not check if each found device is really currently connected to the computer. That would require additional code whereby even cross-checking with values registered currently under HKLM\HARDWARE\DEVICEMAP\SERIALCOMM is not enough as this registry key is not automatically updated when a (virtual) serial COM port device is unplugged. It is only always updated when a serial COM port device is plugged in.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*call /?

*cls /?

*echo /?

*endlocal /?

*for /?

*goto /?

*if /?

*pause /?

*reg /?

*reg query /?

*rem /?

*set /?

*setlocal /?

*shift /?


text:
Q: Tensorflow build is failing for GPU '__NV_EXTRA_INITIALIZATION' was not declared in this scope This is my first time working on a GPU. I have followed the Tensorflow installation guide https://www.tensorflow.org/install/gpu and am trying to build it using bezel. But I am getting the following error
INFO: From Compiling external/nccl_archive/src/collectives/device/min_all_reduce.cu.cc:
ptxas warning : Too big maxrregcount value specified 96, will be ignored
INFO: From Compiling external/nccl_archive/src/collectives/device/max_all_reduce.cu.cc:
ptxas warning : Too big maxrregcount value specified 96, will be ignored
ERROR: /home/ubuntu/.cache/bazel/_bazel_ubuntu/3be25c7517fcab2b83999fe3669ecd1f/external/nccl_archive/BUILD.bazel:139:1: C++ compilation of rule '@nccl_archive//:device_code' failed (Exit 1)
bazel-out/k8-opt/bin/external/nccl_archive/device_code.cc:19:2: warning: #warning "crt/link.stub is an internal header file and must not be used directly.  Please use cuda_runtime_api.h or cuda_runtime.h instead." [-Wcpp]
 #warning "crt/link.stub is an internal header file and must not be used directly.  Please use cuda_runtime_api.h or cuda_runtime.h instead."
  ^
bazel-out/k8-opt/bin/external/nccl_archive/device_code.cc: In function 'void __cudaRegisterLinkedBinary(const __fatBinC_Wrapper_t*, void (*)(void**), void*)':
bazel-out/k8-opt/bin/external/nccl_archive/device_code.cc:140:5: error: '__NV_EXTRA_INITIALIZATION' was not declared in this scope
     __NV_EXTRA_INITIALIZATION
     ^
bazel-out/k8-opt/bin/external/nccl_archive/device_code.cc:144:5: error: '__NV_EXTRA_FINALIZATION' was not declared in this scope
     __NV_EXTRA_FINALIZATION
     ^
bazel-out/k8-opt/bin/external/nccl_archive/device_code.cc:145:23: warning: statement has no effect [-Wunused-value]
     for (__i = 0; __i < NUM_PRELINKED_OBJECTS; ++__i) {
                       ^
bazel-out/k8-opt/bin/external/nccl_archive/device_code.cc:145:53: error: expected ';' before ')' token
     for (__i = 0; __i < NUM_PRELINKED_OBJECTS; ++__i) {

Additional info:
Cuda Version 10.0.130
CuDNN 7.3
Ubuntu 16.04.5 LTS
GPU:
00:03.0 VGA compatible controller [0300]: NVIDIA Corporation GK104GL [GRID K520] [10de:118a] (rev a1)
    Subsystem: NVIDIA Corporation GK104GL [GRID K520] [10de:1014]
    Kernel driver in use: nvidia
    Kernel modules: nvidia_410_drm, nvidia_410


text:
Q: Custom View won't inflate properly Trying to build an android game with a map (right now we're just trying to make it draw a circle though) and the view we created won't inflate properly, the app keeps crashing
The activity
package edu.virignia.cs2110.dlf4mf.ghostapocalypse;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class GameActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_game);
      MapView mv = (MapView)findViewById(R.id.map_view);

   }
}

The activity layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="${relativePackage}.${activityClass}" >

   <MapView
       android:id="@+id/map_view"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"/>

</RelativeLayout>

The custom view
package edu.virignia.cs2110.dlf4mf.ghostapocalypse;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.SurfaceView;
import android.view.View;

public class MapView extends SurfaceView {

    private final Paint mPaint = new Paint();

    public MapView(Context context) {
        super(context);
        init();
    }

    public MapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MapView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        int h = 500;
        int w = 500;
        Canvas grid = new Canvas(Bitmap.createBitmap(h,w, Bitmap.Config.ARGB_8888));
        draw(grid);
    }

    @Override
    protected void onDraw(Canvas canvas) {
         super.onDraw(canvas);
         mPaint.setStyle(Paint.Style.FILL);
         int c = R.color.material_deep_teal_500;
         mPaint.setColor(c);
         canvas.drawCircle(250, 250, 150, mPaint);
    }

}

A: Replace <MapView in your XML layout with <edu.virignia.cs2110.dlf4mf.ghostapocalypse.MapView. The class name for a custom view must be fully-qualified.


text:
Q: Plot using Flask and Web Scraping I am not able to obtain an output. Instead I am getting a 404 error. Here, in the code the image is getting saved offline, however I would like to the image to generate online instead of being saved locally and then show it on a webpage.
Following is my code for plotting an yield curve by web scraping the data.
from flask import Flask, render_template
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
import bs4
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen

app = Flask(__name__)

@app.route('/plot')
def plot():
    url = 'https://www.ccilindia.com/RiskManagement/SecuritiesSegment/Pages/ZCYCCurrent.aspx'
    try:
     page = urlopen(url)
    except:
     print('Error opening the URL')

    soup = bs4.BeautifulSoup(page,'html.parser')
    Beta_0 = float(soup.find_all('td',{'class': 'ms-vb2'})[4].text)
    Beta_1 = float(soup.find_all('td',{'class': 'ms-vb2'})[5].text)
    Beta_2 = float(soup.find_all('td',{'class': 'ms-vb2'})[6].text)
    Beta_3 = float(soup.find_all('td',{'class': 'ms-vb2'})[7].text)
    Tau_1 = float(soup.find_all('td',{'class': 'ms-vb2'})[8].text)
    Tau_2 = float(soup.find_all('td',{'class': 'ms-vb2'})[9].text)

    tenor = []; NSS = []
    for i in range(1,42):
        tenor.append(i)
    for i in range(len(tenor)):
        NSS.append(Beta_0+Beta_1*(1-np.exp(-tenor[i]/Tau_1))/(tenor[i]/Tau_1)+\
        Beta_2*(((1-np.exp(-tenor[i]/Tau_1))/(tenor[i]/Tau_1))-np.exp(-tenor[i]/Tau_1))+\
        Beta_3*(((1-np.exp(-tenor[i]/Tau_2))/(tenor[i]/Tau_2))-np.exp(-tenor[i]/Tau_2)))
    print(NSS)

    plt.title('Yield Curve')
    plt.xlabel('Tenor')
    plt.ylabel('Yield rate')
    plt.plot(tenor, NSS)

    plt.savefig('static/images/plot.png')

    return render_template('yield.html', url='/static/images/plot.png')

if __name__ == '__main__':
   app.run()

Below is the HTML code for yield.html

Price Chart

{{ name }}

My error
runfile('E:/MSE/Website/yield demo.py', wdir='E:/MSE/Website')
 * Serving Flask app "yield demo" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [14/Jul/2020 09:47:45] "GET / HTTP/1.1" 404 -
INFO:werkzeug:127.0.0.1 - - [14/Jul/2020 09:47:45] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [14/Jul/2020 09:47:57] "GET /plot.png HTTP/1.1" 404 -
INFO:werkzeug:127.0.0.1 - - [14/Jul/2020 09:47:57] "GET /plot.png HTTP/1.1" 404 -
127.0.0.1 - - [14/Jul/2020 09:48:35] "GET /static/images/plot.png HTTP/1.1" 404 -
INFO:werkzeug:127.0.0.1 - - [14/Jul/2020 09:48:35] "GET /static/images/plot.png HTTP/1.1" 404 -

A: A 404 Error indicates that the page you are trying to get to doesn't exist. I think if you want to save it offline, you should do it through an S3 instance from AWS, to make it as easy as possible to reference an image.


text:
Q: Advice on optimizing skills database tables I'm looking for advice on how I can optimize my tables so I'm not performing a bunch of joins. Right now I'd have to perform 3 or 4 joins just for one skill, which is turned into a tree structure by my php. Could anyone give me tips on how to cut down the joins, and suggest any way to cut the number of tables I'm using? I don't know anything about game mechanics and I'm not a great db designer either. Any tips, and/or suggestions are much appreciated.
Stats:
use skilltree;

create table stats
(
    id int not null auto_increment,
    title varchar(28) not null,
    rate int default null, # default value for number
    txt varchar(38) default null, # allows stat to hold string value or number
    increase int, # amount to increase every level up unless string
    icon varchar(128), # path or url to icon, optional
    position int not null, # position used for display
    active int not null default 1, # is stat usable
    primary key(id)
)

Skills:
use skilltree;

create table skills
(
    id int not null auto_increment, # id used for prereq 0 is root
    specialty int not null,# id to the specialty it belongs to
    title varchar(20) not null, # name of the skill
    description text not null, # what the skill does
    tiers int(5) not null default 1, # levels of advancement in skill, default 1, max 5
    prereq int default null, # used as parent id, looks better than parent
    icon varchar(128), # path or url to icon, shown in skill description view
    image varchar(128) not null, # path or url to image, image of the stat
    active int not null default 1, # if this skill is actve and needs to be added to the tree
    primary key(id) # auto_increment key has to be primary key
);

Bonuses:
use skilltree;

create table skillbonuses
(
    id int not null auto_increment,
    skill int not null, # id of the skill bonus belongs to
    stat int not null, # id of stat bonus applies to for this tier
    tier int(5) not null, # level of stat bonus applies to
    dependant int default 0, # dependant stat
    bonus int not null, # bonus amount as a percent
    primary key(id),
    foreign key(skill) references skills(id),
    foreign key(stat) references stats(id)
);

Dependants:
use skilltree;

create table skilldependants
(
    id int not null auto_increment,
    bonus int not null, # bonus that requires the check
    numequals int, # value to check if number
    txtequals varchar(38), # value check if stat is a string type
    primary key(id),
    foreign key(bonus) references skillbonuses(id)
);

A: Joins are not evil!
If your table is normalized, then you will find that many of your queries involve a JOIN, or multiple JOINs. They can frequently be the most effective way to keep your tables in good shape because you are not repeating data. When you repeat data you are at risk to have things get screwed up. The more data that is repeated, the more likely it will get screwed up. Complex joins offer no hit to the speed of your query, so the only potential downside is increased risk of carpal tunnel syndrome. On the contrary, the alternate possibility to smaller, nimbler tables is that you end up with a huge beast of a table that is repeating multiple values on each row, and that WILL be SLOW.
Can you normalize your way to fewer tables?
That being said, read the link I included and try to understand it a bit. Specifically, the point is that if you have any columns (other than primary keys), that show up in more than one table, you can normalize a bit more by dropping it from one of the tables. In that same vein, if you look at a couple of tables and realize you would NEVER call one without another, you can expect that merging them together is not going to cause you any serious problems.
However, it doesn't look, at a glance, like that is the case with you.
Other ways to cut coding
That being said, how can you limit the amount of these queries you write?
Utilize DRY principle. AKA Don't Repeat Yourself. If you find yourself hunting through your code to find a query to use at a later date, you are repeating yourself.
All queries should be in functions. That way when you want to call a query you are actually just calling a function. If your functions are well documented you will find that you have to write fewer and fewer queries.
Hope this helps.


text:
Q: Помощь с Semantic UI Доброго времени суток, подскажите пожалуйста почему может не работать выпадающий список Compact Dropdown  если сделать append всего блока.
То есть у меня есть блок в коде html:

Compact

A

B

C

который я добавил, есть кнопка "Add more" при нажатии на которую я с помощью append(); добавляю блок html
$(document).ready(function() {
    $("#add-more").click(function () {
        $(".choose-category-block").append('

Choose Category

Dresses

Jackets

Jeans

Shirts

');
    });
});

но первый выпадающий список, который добавлен в html откривается, а тот, который добавил с помощью append() не работает. В чём может быть проблема и какое возможное решение данного вопроса?

A: Нужно инициализировать компонент.
    $('.ui.dropdown').dropdown();

A: Вопрос закрыт, разобрался. Как и говорил Simonov Dmitro, нужно добавить инициализацию для добавленного элемента, так как он динамически добавлен с помощью append();:
$(document).ready(function($) {
    $("#add-category").on("click", function(){
        $(".choose-category-block").append('

Choose Category

Dresses

Jackets

Jeans

Shirts

');
        setTimeout(function() {
            $('.ui.dropdown').dropdown();
        }, 300);
    })
});


text:
Q: Require a new page in a wiki to use a template Let's say I want to make a wiki of addresses, using a Template:Address. How do I make it so that, if someone goes to a new page — e.g. myaddresswiki.com/John_Smith — to add their address, it automatically includes my Template:Address in the page?

A: See Manual:Creating pages with preloaded text at mediawiki.org.
If you're manually creating edit links for your users to add the new pages, you can just include a preload=SomePageName parameter in the URL.
Alternatively, you can use one of the extensions that automate parts of the process for you (typically either by generating the appropriate links and/or automatically selecting a preload template based on the page title), or even write your own using the EditFormPreloadText hook.

A: I just did it this way:
if( $("#wpTextbox1").val() == ""){
     $("#wpTextbox1").val("This content is generated from 'MediaWiki:Common.js'\rPlease use a template by typing into the Search field 'Template:'.  From there, your available templates will be visible from the auto-complete options.");
}

Of course, you could hard-code a template (or anything) into the val argument.


text:
Q: How to Convert English to Spanish using php We developed an App in Android and Iphone which support language in English.Now we plan to show the app content in Spanish also.What is the best approach to do this.
How we convert the English to Spanish using PHP to show data in Spanish also

A: Use language files for English and Spanish and whatever you need. and by the usage of those and an XML file you can implement this.
Please take a look here, this may help you How to Make Your Website Support for Multi Language with PHPMaker
8.0.3

A: Internationalization is what you are looking for. It is a fairly simple process(provided you are going to work with languages that are not encoding-specific). Data which changes with locale is isolated into seperate files which are locale-specific. Then when the locale of the user is identified, the specific locale file is loaded and the word from that locale is substituted in the placeholder. Wherever you are going to introduce this, I am sure Google can guide to an extensive tutorial.


text:
Q: createMany with realtion with prisma.io I have two models:
model Terminal {
    terminal_id   Int      @id @default(autoincrement())
    terminal_name String
    created_at    DateTime @default(now())
    updated_at    DateTime @updatedAt
    modcods       Modcod[]

    @@map("terminal")
}

model Modcod {
    modcod_id   Int      @id @default(autoincrement())
    name        String?
    created_at  DateTime @default(now())
    updated_at  DateTime @updatedAt
    terminal    Terminal @relation(fields: [terminal_id], references: [terminal_id], onDelete: Cascade, onUpdate: Cascade)
    terminal_id Int

    @@map("modcod")
}

Creating a single resource works just fine:
export async function createSingleModcod(modcod: Modcod, terminal_id: number) {
  const modcod = await prisma.modcod.create({
    data: {
      ...modcod,
      terminal_id, // this is the terminal_id coming from req.body
    },
  });
  await prisma.$disconnect();
  return modcod;
}

Creating many however does not:
export async function createManyModcods(modcods: Modcods[], terminal_id: number) {
  const modcods = await prisma.$transaction(
    modcods.map((modcod) =>
      prisma.modcod.create({
        data: {
          ...modcod,
          terminal_id, // this is the terminal_id coming from req.body
        },
      }),
    ),
  );
  await prisma.$disconnect();
  return modcods;
}

Is this a prisma limitation or am I missing anything?
I've tried the solution above using $transaction and the 'standard' createMany like so:
export async function createManyModcodsAlt(modcods: Modcods[], terminal_id: number) {
  const modcods = await prisma.modcod.createMany({
    data: modcods.map((modcod) => ({
      ...modcod,
      terminal_id,
    })),
  });
  await prisma.$disconnect();
  return modcods;
}

My expectation is that it should work just like creating a single resource


text:
Q: OpenGraph values I'm sorry, I have searched for a day and a half but I can't find the specific answer I'm looking for.
My Facebook Like button doesn't appear on IE, Chrome or Firefox.  I am using Javascript.

*

*I  have the required HTML addition.

*I need to put in the Meta Tag
meta property="og:tag name" content="tag value"
COULD I GET AN EXAMPLE FOR THE "TAG NAME" AND "TAG VALUE"?
I don't know what to fill in!

*I am supposed to have the Javascript SDK right after the body; however, I don't know what to put for an APP_ID as in:
 <script>
 window.fbAsyncInit = function() {
 FB.init({
 appId      : 'YOUR_APP_ID', // App ID
  //CAN I GET AN EXAMPLE OF YOUR_APP_ID, please?
 channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
  //is channel.html the page it's on?
 status     : true, // check login status
 cookie     : true, // enable cookies to allow the server to access the session
 xfbml      : true  // parse XFBML
 });
// Additional initialization code here
 };
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>

I am getting so frustrated!  Please help me!

A: The YOUR_APP_ID is the ID of your Facebook Application. If you haven't created a App, you can do so here.
However, you don't need to use an app to use the Like Button plugin. You should be able to use the Plugin just by copy-and-pasting the plugin code from the developer website. If that doesn't work, use the debug tool to see what's going wrong.

A: Well, I recommend you to read more carefully the documentation of the Facebook's JS SDK, but also the "Getting Started" and the "Core Concepts". There you will find a lot of very useful information.
I'll try to explain what the App_id is. When you want to do some more funcional applications, that interact with user information from facebook, you need to create a Facebook's app. To do that log into your account and go to https://developers.facebook.com/apps. There you need to tell your app's name, URL, and some other things. When you save you'll see an app_id, that is an unique number that identifies your app on Facebook. Is this number that you have to put in your script (surrounded by quotes, don't forget).
The channel file is a single line html file that you have to put in your server, at the same domain of your app. The content of this file is:
 <script src="//connect.facebook.net/en_US/all.js"></script>

Replace the "en_US" by your app locale.
You questioned about the meta tags of the OpenGraph. Well, when you click "like" for a URL, the Facebook-bot navigates to your page and reads the meta information. When it finds OpenGraph meta tags, the information posted at the user wall is more personalized. You'll have to spent a little time to understand more what kind of OpenGraph meta tags you will need, once every site has different information to share.


text:
Q: Java: InternetAddress I am storing my emails in database by using
InternetAddress.toUnicodeString().
It gives me such string: "John Doe" <doe@john.com>
The question: how can I parse that string in order to convert it back to InternetAddress?
Thank you

A: According to the javadoc, the InternetAddress.toUnicodeString() method is supposed to give you an RFC 822 compliant email address decoded as unicode characters.  But "John Doe" is not an RFC 822 compliant email address at all.  This points to the problem being with whatever is creating those InternetAddress objects in the first place.
Certainly, there is no way to "parse" the string "John Doe" and extract a valid email address.  The information is simply not there to be extracted.  Perhaps you could do a lookup in a local address book database.

UPDATE -
The way to turn "John Doe" <doe@john.com> into an InternetAddress is to use the InternetAddress(String) constructor (javadoc).  That will parse the input String automatically.

A: I would say, impossible. You should rather choose between storing a email address the full length in your database, or by storing an id of the email address (which requires a separate table for email addresses).
Just make sure that your InternetAddress object is valid. Try to call validate() on it to see if it is actually correct.

A: Ummm... perhaps by using the constructor that takes a String parameter? Please learn to use the Javadoc API - you'll find answers much faster than by asking here.

A: you can use new InternetAddress(emailAddress,personalName) method in your case.


text:
Q: Apache has just stopped working in XAMPP, new version says UAC issues Alright, so I've run into multiple issues with XAMPP.
First it started when I would try to run Apache and would receive the "Apache shutdown unexpectedly" error, so I did some troubleshooting and figured it would be best to just uninstall and reinstall a newer version since I was behind anyway.
So I go to install the new version and receive this:
http://i.imgur.com/3LUyL5j.png
Well, my UAC is turned off..so I can't possibly be having that issue. Tried to install anyway, but my XAMPP version number is still my PREVIOUS version of XAMPP even though I made sure to uninstall and reset before installing the newer version. Upon checking the logs I received "this file has not been created, would you like to create one?".
So I'm stuck here, anybody have a solution?

A: Ive had a similar problem- Installed XAMPP yesterday. Where you install your XAMPP...
->right click on the file "xampp"
->Properties
->Security
->Under 'Group or user names' click your user
->Then click on "To change permission, click Edit", and click the "Edit..."
->Click on you user again, and "Allow" yourself "Full Control"
->Click Apply
Let me know if this works


text:
Q: Is it possible to utilize a custom CSS properties with javascript? I was wondering if it was possible to access custom rules placed into a stylesheet. For instance, take:
p {
  line-height: 2em;
  -js-min-line-height: 1.4em;
}

I've tried traversing the stylesheet object and grabbing the CSS text but the browser, as it probably should do, does not return the text of properties it doesn't recognize:
for styleSheet in document.styleSheets
  for rule in styleSheet.cssRules
    console.log rule.cssText

Simply returns:
p { line-height: 1.4; }

A: It depends on how the CSS is derived. What it depends on is whether or not it is linked, composed, or hard coded. If it is hard coded, then just place an id on the style element, and use document.getElementById("styleId").innerHTML to get the text and then parse it by splitting the string at semi colons. If it is composed by javascript, then it should be easy to just add some extra content in there to retain the style. If it is linked, which I would say is most likely and the hardest case to handle, then I would suggest loading the css into javascript using $.AJAX(), read the text and parse it for what you want, and then use document.getElementsByName("head")[0].appendChild(varHoldingCss) to add the style to your page.


text:
Q: Placing OverFlow Menu On Left Side of ToolBar I have an overflow menu on my Toolbar, which I'm using to navigate between my activities.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".HomePage">

<item
    android:id="@+id/homeActionBar"
    android:title="Home"
    android:orderInCategory="100"
    app:showAsAction="never" />

<item
    android:id="@+id/allergiesActionBar"
    android:title="Allergies"
    android:orderInCategory="100"
    app:showAsAction="never" />

<item
    android:id="@+id/calendarActionBar"
    android:title="Calendar"
    android:orderInCategory="100"
    app:showAsAction="never" />

<item
    android:id="@+id/contactsActionBar"
    android:title="Contacts"
    android:orderInCategory="100"
    app:showAsAction="never" />

The overflow button with all of these options appears on the right hand side of my Toolbar. Does anybody know how to place it all the way to the left?
This is a related but secondary question. I don't have any fragments. They're all activities. I want to navigate between them on my toolbar. What's the best solution for this? Again, I created the overflow menu, which seems to be working fine. Is that typically the best route? I'm avoiding a navigation drawer due to my lack of fragments.
Thank you.

A: If you really want have an Overflow Menu on the left, you would need to create your own custom toolbar in xml than replace existing with your own version using a code like in this example:

here is what works for me like a dream: in the Activity I have this:
//hiding default app icon
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
//displaying custom ActionBar
View mActionBarView = getLayoutInflater().inflate(R.layout.my_action_bar, null);
actionBar.setCustomView(mActionBarView);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM) my_action_bar.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/turquoise">

    <ImageButton
        android:id="@+id/btn_slide"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:background="@null"
        android:scaleType="centerInside"
        android:src="@drawable/btn_slide"
        android:paddingRight="50dp"
        android:onClick="toggleMenu"
        android:paddingTop="4dp"/>
</RelativeLayout>

From Positioning menu items to the left of the ActionBar in Honeycomb

Note, that in Android apps on the left used to be a Navigation Drawer menu. If you would like to have it instead of Overflow Menu, please check this: Android Actionbar Left Menu
Hope it help


text:
Q: Php Mail going to recipients spam /Junk Folder I am working for my college website . I wrote a php script ,that sends email using php mail function. But the problem is ,all the emails that I send is going into the recipients spam /Junk Folder.
In order to resolve it :
I tried all the steps and answers for the similar issues in stackoverflow and serverfault website Like:
*Proper Header
*Accurate From Name,etc
But yet the problem is unresolved.
This is the php code for sending email:
<?php
$from_address="webmaster@".$_SERVER['SERVER_NAME'];
$from_name="webmaster";
$headers = "MIME-Version: 1.0\r\n"
  ."Content-Type: text/plain; charset=utf-8\r\n"
  ."Content-Transfer-Encoding: 8bit\r\n"
  ."From: =?UTF-8?B?". base64_encode($from_name) ."?= <$from_address>\r\n"
  ."X-Mailer: PHP/". phpversion();
$subject="Web Mail Testing";
$body="This is test Message";
$to="riteshkumargupta1990@gmail.com";
mail($to, $subject, $body, $headers, "-fwebmaster@{$_SERVER['SERVER_NAME']}");
echo "The Mail is  SuccessFully Sent to :".$to;
?>

I am also attaching the original email (that i received in my gmail account "riteshkumargupta1990@gmail.com")
Delivered-To: riteshkumargupta1990@gmail.com
Received: by 10.204.8.210 with SMTP id i18csp146000bki;
        Wed, 21 Nov 2012 20:58:12 -0800 (PST)
Received: by 10.68.219.164 with SMTP id pp4mr1119127pbc.72.1353560291776;
        Wed, 21 Nov 2012 20:58:11 -0800 (PST)
Return-Path: <webmaster@nitw.ac.in>
Received: from www.nitw.ac.in (www.nitw.ac.in. [218.248.13.200])
        by mx.google.com with ESMTPS id sh10si3456960pbb.293.2012.11.21.20.58.10
        (version=TLSv1/SSLv3 cipher=OTHER);
        Wed, 21 Nov 2012 20:58:11 -0800 (PST)
Received-SPF: pass (google.com: best guess record for domain of webmaster@nitw.ac.in designates 218.248.13.200 as permitted sender) client-ip=218.248.13.200;
Authentication-Results: mx.google.com; spf=pass (google.com: best guess record for domain of webmaster@nitw.ac.in designates 218.248.13.200 as permitted sender) smtp.mail=webmaster@nitw.ac.in
Received: from www.nitw.ac.in (localhost.localdomain [127.0.0.1])
    by www.nitw.ac.in (8.13.8/8.13.8) with ESMTP id qAM50M0h016190
    for <riteshkumargupta1990@gmail.com>; Thu, 22 Nov 2012 10:30:23 +0530
Received: (from nobody@localhost)
    by www.nitw.ac.in (8.13.8/8.13.8/Submit) id qAM50McG016189;
    Thu, 22 Nov 2012 10:30:22 +0530
Date: Thu, 22 Nov 2012 10:30:22 +0530
Message-Id: <201211220500.qAM50McG016189@www.nitw.ac.in>
X-Authentication-Warning: www.nitw.ac.in: nobody set sender to webmaster@nitw.ac.in using -f
To: riteshkumargupta1990@gmail.com
Subject: Web Mail Testing
X-PHP-Originating-Script: 0:mailer.php
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
From: =?UTF-8?B?d2VibWFzdGVy?= <webmaster@nitw.ac.in>
X-Mailer: PHP/5.3.5

This is test Message

Also while googling I found the uncommon reason for this sort of problem is server Blacklisting .
Then I use the following Tool to test it : http://www.mxtoolbox.com/SuperTool.aspx?action=mx%3anitw.ac.in#
I got shocked when the above tool test found my  server in the black-list. How  is this  true?Since the original mail that i attached above says ":Received-SPF: pass (google.com: best guess record for domain of webmaster@nitw.ac.in designates 218.248.13.200 as permitted sender)
Also if my server is blacklisted , then how can i find the reason for blacklist and how to resolve it?
UPD:
From Shadow Comment : Can "X-Authentication-Warning: www.nitw.ac.in: nobody set sender to webmaster@nitw.ac.in using -f" msg be the probable reason? If yes , How can I Fix it?
Thank You!

A: Setting up SMTP server is tricky and tedious task unless it is ur job do it day in and day out..,   Check if your server SSL certificate are signed properly with an authorized CA certificate., some times it could be the problem of a self signed certificates .,
Or you can also try out Gmail As your SMTP server which solves many problems .., Link


text:
Q: How to secure apiKey in here maps API With the old app_id and code_id setup we were able to use a whitelist in order to determine from which URLs request would be allowed using the credentials.
I cannot find any setting for this with the new apiKey. How are we supposed to secure this, as the key is appended to all request and thus visible to website-users.

A: You mentioned you can't secure the key to domains - however I see it here:

A: The best solution is to use a JavaScript key, where hosts protections are enabled. You can use the JavaScript keys to call the REST APIs. Our docs do not make this clear, but we've got a doc fix coming out to make it more obvious. But yes - just use the JavaScript key.

A: Recommend that you use Oauth 2.0
https://developer.here.com/documentation/authentication/dev_guide/topics/token.html


text:
Q: How do I fix the error 'No memory available to program now: unsafe to call malloc'? How do I debug and fix this error

No memory available to program now: unsafe to call malloc

Analyser doesn't show any cause.

A: Use instruments to check for leaks and memory loss due to retained but not leaked memory. The latter is unused memory that is still pointed to. Use Heapshot in the Allocations instrument on Instruments.
For HowTo use Heapshot to find memory creap, see: bbum blog
Basically there method is to run Instruments allocate tool, take a heapshot, run an intuition of your code and another heapshot repeating 3 or 4 times. This will indicate memory that is allocated and not released during the iterations.
To figure out the results disclose to see the individual allocations.
If you need to see where retains, releases and autoreleases occur for an object use instruments:
Run in instruments, in Allocations set "Record reference counts" on on (you have to stop recording to set the option). Cause the picker to run, stop recording, search for there ivar (datePickerView), drill down and you will be able to see where all retains, releases and autoreleases occurred.


text:
Q: Builder Pattern useful with Setter-methods? So I have a webproject with Hybris, Spring and so on.
I have some classes, which are autogenerated. Let's say I have one modelclass, which is autogenerated and inherits from another class some methods, to set fields.
When writing Unit-tests, is it useful to start using the Builder pattern? Because the thing is, I don't have a constructor, like Employee(int id, String name) and so on, I only have the inherited methods to set them (setId(int id) and so on).
So when I would write a Builder class for this model for example, I would have the methods .withId(int id) and .withName(String name) and the build()-method, where I would run the setter-methods.
so in the end in my test-class I would have:
EmployeeBuilder eb = new EmployeeBuilder();
Employee emp = eb.withId(123)
                 .withName("John")
                 .build();

But since I already have Setter-Methods I normally have:
Employee emp = new Employee();
emp.setId(123);
emp.setName("John");

So is it really worth the effort in this case? Or is there something I have not really understood?
Thanks!

A: Before I give an answer to your question I would like to explain the builder pattern.
The builder pattern is usually used when you have a lot of overloaded constructors (telescoping constructor anti-pattern). E.g.
public class Employee {

   public Employee(String firstName, String lastName){
       ...
   }

   public Employee(String firstName, String lastName, Sex sex){
       ...
   }

   public Employee(String firstName, String lastName, String salutation) {
       ...
   }
}

In this case client code must decide which constructor to invoke depending on the data it has. If it has a firstName and lastName it must invoke new Employee(firstName, lastName). If it only has a firstName it must invoke Employee(String firstName). So the client code might have a lot of if/then/else. E.g.
Employee employee = null;
if(firstName != null && lastName != null && sex != null){
    employee = new Employee(firstName, lastName, sex);
} else if(firstName != null && lastName != null && salutation != null){
    employee = new Employee(firstName, lastName, salutation );
} else {
  .....
}

The design of the Employee class in this example includes that firstName and lastName are mandatory attributtes of an Employee, because every constructor needs them. The attributes sex and saluation are optional. If the client code decides which constructor to invoke this also means that the decision process is duplicated accross client code. E.g. if a client knows the firstName, lastName, sex and salutation which constructor should it call? Either new Employee(firstName, lastName, sex) or new Employee(firstName, lastName, saluation)?
In order to encapsulate the constructor resolution you might want to use a builder pattern.
public class EmployeeBuilder {

      public EmployeeBuilder(String firstName, String lastName){

      }

      public void setSex(Sex sex){ ... }

      public void setSalutation(Salutation salutation){ ... }

      public Employee build(){
          if(salutation != null){
             return new Emplyoee(firstName, lastName, salutation);
          } else if(sex != null){
             return new Emplyoee(firstName, lastName, sex);
          } else {
             return new Emplyoee(firstName, lastName);
          }
      }
}

This makes the client-code much easier to read and the constructor invokation decision is encapsulated. E.g.
EmployeeBuidler employeeBuilder = new EmployeeBuilder(firstName, lastName);

Sex sex = ...;
String salutation = ...;

employeeBuilder.setSex(sex);
employeeBuilder.setSalutation(salutation);

Employee employee = employeeBuilder.build();

Back to your question

So is it really worth the effort in this case?

For your unit tests you might want to create Employee objects with some attributes and the others should be set to default values. In this case I think it is a good idea to use a builder pattern. I would name the builder then e.g. EmployeeDefaultValuesBuilder to make it clear.
You might also want to build Employees based on other employee objects (templates). In this case I would add another constructor to the EmployeeBuilder. E.g.
public EmployeeBuilder(Employee template){
  // initialize this builder with the values of the template
}

So it is worth the effort if you encapsulate construction logic or if it increases readability.

A: Builder pattern is useful for:

*

*Immutable classes, which is not the case here.

*When you need to build many of the same things with minor differences. Which is also not the case here.

*Writing a "Fluent" API.

*When you have a complex object which requires a complex build.

So is it really worth the effort in this case?

Given what you have posted, I'd say no.
Finally the effort involved is tiny when using the right APIs, such as Project Lombok or Google Auto. (Also if you are using a builder to hide a telescoping constructor anti-pattern I think you are abusing the pattern, but hey...)

A: Builder pattern is useful in two cases:

*

*resulting object is immutable(all fields are final) - builder is
better than  constructor with many arguments.

*you want to be sure that created object is valid and no inconsistent objects can be created - for example you can throw error from build() method if longitude field was set but latitude was not.

A: As you demonstrate in your code example, with the builder pattern you only save a couple time writing out your variable name emp, but also have to add a final build() call or similar.
In my book that certainly does not pay off the investment of creating additional builders.
But ...
Maybe you have fields that need to be filled, but that are really not relevant for what you want to test.
Or you want to create multiple instances that only differ in few properties.
Those can be build nicely in a builder, saving lots of lines of code, and what is more important, makes your tests much clearer.


text:
Q: Making ndarrays callable Suppose I have a set of orthonormal basis functions, represented as Python callables
class Basis(object):

    def __init__(self,i,j):
        self.i=i
        self.j=j

    def __call__(self,x,y):
        return f(self.i,self.j,x,y)

I'd like to store these in a numpy.array, such that basis_functions[i,j]=Basis(i,j)
I'd also like the array to be callable, so that basis_functions(x,y) returns an array containing basis_functions[i,j](x,y) for all i,j in range.
I've had a look at the documentation on subclassing ndarray, but haven't found it particularly helpful. Can anybody give me any pointers as to where to start?
ADDENDUM
I was hoping to use it something like this
class SytheticFunction(object):
    basis=callable_array([[Basis(i,j) for j in xrange(COLUMNS)]
                          for i in xrange(ROWS)])

    def __init__(self,weights):
        self.weights=weights

    def __call__(self,x,y):
        return (self.weights*SyntheticFunction.basis(x,y)).sum()


text:
Q: PrestaShop $this->context->smarty is null I'm making a PrestaShop 1.6 module and something weird is happening. In the configure page of this module I offer the user two forms. One to configure an automatic email and other to test the e-mail. My problem is that after submitting the second form the $this->context->smarty is null giving me this error:
Fatal error: Call to a member function assign() on null in /Users/andre/Projects/Web/xxx/modules/closecustomerthreademail/closecustomerthreademail.php on line 90

In line 90 I have: $this->context->smarty->assign('module_dir', $this->_path); which is inside of this function:
public function getContent()
{
    /**
     * If values have been submitted in the form, process.
     */
    if (((bool)Tools::isSubmit('submitClosecustomerthreademailModule')) == true) {
        $this->postProcess();
    }

    $this->context->smarty->assign('module_dir', $this->_path);
    $output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');

    return $output.$this->renderForm();
}

This is how I add two forms in the screen (renderForm method): return $helper->generateForm(array($this->getConfigForm(), $this->getTestForm()));
The postProcess. Sorry for pasting so much code, I'm trying to provide all the details I find relevant.
protected function postProcess()
{
    if(Tools::isSubmit('test_form')) {
        $this->sendTestEmailTo(Tools::getValue('CLOSECUSTOMERTHREADEMAIL_EMAIL_TO_TEST'));
    }
    elseif(Tools::isSubmit('config_form')) {

        $form_values = $this->getConfigFormValues('config_form');

        foreach (array_keys($form_values) as $key) {
            Configuration::updateValue($key, Tools::getValue($key));
        }
    }
}

The sendTestEmailTo just has an IF statement and then call this function:
public function sendEmail($to_email, $to_name = null){

    $id_lang = $this->context->language->id;
    $template_dir = _PS_MODULE_DIR_.$this->name.'/views/templates/email/';

    $vars = array(
        '{html}' => Configuration::get('CLOSECUSTOMERTHREADEMAIL_EMAIL_HTML_BODY'),
        '{text}' => Configuration::get('CLOSECUSTOMERTHREADEMAIL_EMAIL_TEXT_BODY')
    );

    require(_PS_CONFIG_DIR_.'config.inc.php');
    require_once(_PS_ROOT_DIR_.'/init.php');

    $send = Mail::Send(
        (int)$id_lang,
        'email',
        Configuration::get('CLOSECUSTOMERTHREADEMAIL_EMAIL_SUBJECT'),
        $vars,
        $to_email,
        $to_name,
        null,
        null,
        null,
        null,
        $template_dir,
        false,
        (int)$this->context->shop->id,
        null
    );

    return $send;
}

I'm failing to see what could be causing $this->context->smarty to be null. Would you have any tips to help me investigate?
EDIT
The construct method:
public function __construct()
{
    $this->name = 'closecustomerthreademail';
    $this->tab = 'others';
    $this->version = '1.0.0';
    $this->author = 'andre';
    $this->need_instance = 0;

    /**
     * Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
     */
    $this->bootstrap = true;

    parent::__construct();

    $this->displayName = $this->l('Close Customer Thread e-mail');
    $this->description = $this->l('Sends an e-mail whenever you close a customer thread');

    $this->confirmUninstall = $this->l('Are you sure you want to uninstall this module?');

    $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}

A: I'm glad that you've solved. But I guess that the problem is this:
require(_PS_CONFIG_DIR_.'config.inc.php');
require_once(_PS_ROOT_DIR_.'/init.php');

Remove those lines :), you shouldn't never include that files in a class method.

A: I couldn't figure out before the delivery so I had to do this to solve, a redirect:
protected function postProcess()
{
    if(Tools::isSubmit('test_form')) {
        $this->sendTestEmailTo(Tools::getValue('CLOSECUSTOMERTHREADEMAIL_EMAIL_TO_TEST'));
    }
    elseif(Tools::isSubmit('config_form')) {

        $form_values = $this->getConfigFormValues('config_form');

        foreach (array_keys($form_values) as $key) {
            Configuration::updateValue($key, Tools::getValue($key));
        }
    }

    $actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

    Tools::redirectAdmin($actual_link);
}


text:
Q: i have some issues to save my data into my database with my php code actually i had some text content to include into my database the format is text.
But i can save it in my database (in phpmyadmin)i'm using xammp .
Can you help me to find where is the problem with my code please ?
i had a first file name text2.text in to a folder name files he look like this :
title : a subject , content : lorem ipsum dolor , autor : John Doe
title : a subject1 , content : lorem ipsum dolor , autor : Izzy Doe
title : a subject2, content : lorem ipsum dolor , autor : Pat Doe
title : a subject3, content : lorem ipsum dolor , autor : Jimmy Doe
title : a subject4, content : lorem ipsum dolor , autor : Dave Doe

i create a database name "mydatabase"
and i create a table name "thetest "
here is my code :
<?php
$conn = new mysqli('localhost','root','','mydatabase');

$file= fopen("files/text2.text","r");

while (!feof($file)){
    $content = fgets($file);

    $carray = explode(",", $content);

    list($title,$content,$autor)= $carray;

  $sql=" INSERT INTO `thetest` (`id`, `title`, `content`, `autor`) VALUES ( '$title', '$content', '$autor')";

$conn-> query($sql);
   //echo "<pre>";
   //var_dump($carray);
}

fclose($file);
?>

the var_dump here helped me to see if the explode work well
i expected with this code that when i refresh my page all the data saved in my database but i had nothing save inside  .
I know that actually the database is not secure with this code i will work later on this but actually this database is a trainning tool to learn how to save data inside.
Thank you by advance

A: Firstly you need to convert file extension from .text to .csv, if you want to save it into database. try using this code`
$filename = $_FILES["email"]["tmp_name"];

     if($_FILES["email"]["size"] > 0)
     {
        $file = fopen($filename, "r");
        while (($getData = fgetcsv($file, 1000, ",")) !== FALSE){

     $sql = "INSERT into emails (emails,website)
             values ('".$getData[0]."','".$getData[1]."')";
               $result = mysqli_query($connect, $sql);
            if(!isset($result))
            {
                echo "please upload csv file";
            }
            else {
                  echo "File has been uploaded";
            }
         }

         fclose($file);
     }

`

A: i find out  where was the error in my code.
It was the format of the text2.text ,i change it in a text2.txt ,
and it was the sql request where i put id =>
instead of (id, title, content, autor) i put (title, content, autor).
those modification works and  saves the text data  in my database .
here is my new code :
<?php
$conn = new mysqli('localhost','root','','mydatabase');

$file= fopen("files/text2.txt","r");

while (!feof($file)){
    $content = fgets($file);

    $carray = explode(",", $content);

    list($title,$content,$autor)= $carray;

  $sql=" INSERT INTO `thetest` (`title`, `content`, `autor`) VALUES ( '$title', '$content', '$autor')";

$conn-> query($sql);
   //echo "<pre>";
   //var_dump($carray);
}

fclose($file);
?>

i hope that will help someone else have a nice day!


text:
Q: how to achieve CheckBox Checked and Unchecked event in MVC 3 I have manufacturer name with checkbox, when i checked manufacturer then by checked event i want to display all product from that manufacturer,...
how to achieve CheckBox Checked and Unchecked event in MVC 3

A:
how to achieve CheckBox Checked and Unchecked event in MVC 3

Suppose you have this checkbox:
<input type="checkbox" id="manufacturerCheckbox" />

You can capture it's "Checked and Unchecked event" by:
$("#manufacturerCheckbox").click(function () {
    alert($(this).is(':checked')
        ? 'checkbox is checked'
        : 'checkbox is unchecked');
});


text:
Q: printing an element of array (python) There are two lists/arrays and I want to assign one by one.
import Mybench
process = []
benchmarks = options.benchmark.split(',')
for bench_name in benchmarks:
   process.append(getattr(Mybench, bench_name))

Assume another list (cpus) is also created. Now I want to do this:
i = 0
for i, cpu in cpus:
   print "cpu", i, "assigned to ", process[i]
   cpu.workload = process[i]
   i = i+1

However in the output I see:
cpu 0 assigned to  <orphan LiveProcess>

LiveProcess() is returned from Mybench.
How can I fis that?

A: for i, cpu in enumerate(cpus):
   print "cpu", i, "assigned to ", process[i]
   cpu.workload = process[i]


text:
Q: Working with functions I am writing this method that takes in 3 parameters and then outputs the result in an ordered row. I got it to that point fine, but for some reason I get a duplicate number at end of each iteration. Such as:

Here is the entire code. Hope it helps:
#include <iostream>
//function prototype:
int payoff(int x, int y, int z);

//global variables:
int R1;
int R2;
int R3;
int total;

using namespace std;
int main(void) {
    cout << "R1\t R2\t R3\t\n" << endl;

    ////////////////////
    //first loop
    ////////////////////
    R1 = 1;
    R2 = 1;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    ////////////////////
    //second loop
    ////////////////////
    R1 = 1;
    R2 = 2;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    ////////////////////
    //third loop
    ////////////////////
    R1 = 1;
    R2 = 3;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    ////////////////////
    //fourth loop
    ////////////////////
    R1 = 2;
    R2 = 1;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    ////////////////////
    //fifth loop
    ////////////////////
    R1 = 2;
    R2 = 2;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    ////////////////////
    //sixth loop
    ////////////////////
    R1 = 2;
    R2 = 3;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    ////////////////////
    //seventh loop
    ////////////////////
    R1 = 3;
    R2 = 1;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    ////////////////////
    //eight loop
    ////////////////////
    R1 = 3;
    R2 = 2;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    ////////////////////
    //ninth loop
    ////////////////////
    R1 = 3;
    R2 = 3;
    R3 = 1;
    printf("%d", payoff(R1, R2, R3));
    printf("\n");

    system("PAUSE");
    return 0;
}
/////////////////////////////////////////////////////////
//FUNCTIONS:
/////////////////////////////////////////////////////////
int payoff(int R1, int R2, int R3) {
    do {
        //calculate payoff:
        total = R1;
        if (R2 < R1) {
            total = total + R2;
        } //end if
        else {
            if (R3 < R1) {
                total = total + R3;
            } //end if
            else {
                total = R1;
            } // end else
        } //end else

        if (R3 < R2) {
            total = total + (2 * R3);
        } //end if
        else {
            if (R3 < R1) {
                total = total + R3;
            } //end if
            else {
                total = R1;
            } //end else
        } //end else

        //display payoff:
        printf("%d\t %d\t %d\t payoff is %d\n", R1, R2, R3, total);

        R3++;
    } while (R3 < 4); //end do-while

    return total;
} //end function payoff

Can anyone help me figure out how to get rid of that pesky extra number? Thank you so much on advance!

A: The return code from payoff() is being printed in the printf statements which is not want you want. You just need to call payoff() without the printf.
printf("%d", payoff(R1, R2, R3)); calls payoff function, then outputs the value returned from the payoff() function.
So replace lines such as:
 printf("%d", payoff(R1, R2, R3));

with
 payoff(R1, R2, R3);

A: this is what happens when you insert 1,1,1 in your function:
printf(first loop with \n)
printf(second loop with \n)
printf(last loop with \n) //because R3 will be 4 and therefore hte while-loop will end.

then you will return the total to the printf-function in your main function and print the duplicate lines.
if you don't want those duplicate lines you should simple call your function and make it not return anything:
instead of this:
int payoff(int R1, int R2, int R3) {

do{
...
}while(r3<4);

return total;
}

change to this:
void payoff(int R1, int R2, int R3) {

do{
...
}while(r3<4);

//return total;
}

Then call the function not like you did:
printf("%d", payoff(R1, R2, R3));

But like this:
payoff(R1, R2, R3);

A: If you don't want to show that line then remove in each loop this line:
printf("%d", payoff(R1, R2, R3));

Change it to:
payoff(R1, R2, R3)

Because it is printing a number %d of the result of the function, also in payoff you're already printing the results, so you don't need it to return it to the main site.
Why don't use loops?


text:
Q: NullPointerException in Eclipse itself I started working on a project recently and after I imported it in Eclipse (the usual way, File -> Import -> Existing Projects into Workspace) it started giving me this strange error. The project has a little red icon, like it is not configure properly, that is really bugging me.
The error below happens also when I click on Project Facets. When I try to click OK it alerts me with the usual java-style NullPointerException. Otherwise, the project works just fine. I'm using Eclipse Kepler.

A: Examine the error log view,  select appropriate problem (probably the JPA error message) and open it.  See if there is a stack trace present.  this may point more directly to the issue at hand.  Suggest possibly reporting it to Eclipse foundation at the bugzilla site.
(edit: corrected view name.  thanks)


text:
Q: Color each data point I want to color each point in ListPlot using custom markers when there are only values of the points, i.e. the data is in the form {1,2,3,...}. There are many related questions (e.g. here and here), but the solutions are either to use data in the form {x,y}, convert it to the list of lists, and then effectively color each subplot separately
data1 = {{{1, 2}, Red}, {{2, 3}, Blue}};
ListPlot[
   List /@ data1[[;; , 1]],
   PlotMarkers ->
      Apply[Graphics[{#, Rectangle[]}, ImageSize -> 15] &, List /@ data1[[;; , 2]], {1}]
]

or to color each point using Style, in which case using custom markers doesn't work.
data2 = {Style[2, Red], Style[3, Blue]};
ListPlot[data2, PlotMarkers -> Graphics[{Rectangle[]}, ImageSize -> 15]]

Is there a solution when the data doesn't have the x coordinate?

A: I'm with swish. I think it's easy to add the x-coordinate.
data = {{2, Red}, {3, Blue}, {1, Green}};
Module[{pts, markers},
  pts = MapThread[{{#1, #2}} &, {Range @ Length[data], data[[All, 1]]}];
  markers =
    Graphics[{#, Rectangle[]}, ImageSize -> 15] & @@@ List /@ data[[All, 2]];
  ListPlot[pts, PlotMarkers -> markers]]

Update
If you want  to specify the plot range, then define a custom version of ListPlot. Like so:
myListPlot[data_, min_, max_] :=
  Module[{xcoords, pts, markers},
    xcoords = Subdivide[min, max, Length[data] - 1];
    pts = MapThread[{{#1, #2}} &, {xcoords, data[[All, 1]]}];
    markers =
      Graphics[{#, Rectangle[]}, ImageSize -> 15] & @@@ List /@ data[[All, 2]];
    ListPlot[pts, PlotMarkers -> markers]]

myListPlot[data, 10, 20]

plot


text:
Q: Websphere Application Server 8.5. Load roles by custom code on Federated repository I'm uses WAS with security realm Federated repository.
In federated repository configured repository with type LDAP:CUSTOM. It's worked fine and I can authenticate in my web application via LDAP.
But how can I load roles (authorization) for my web application from custom database/from static list by username? (not from LDAP)


text:
Q: How to launch a url in a text box on chrome? c# I am currently working on a school project using C# which is to develop a basic program of my choice.  Currently I'm faced with the problem of trying to implement a function where a URL is imputed into a textbox and a button would open that url in a web browser.
I've been searching for a solution to this problem but haven't found any luck as of yet so I would appreciate any help.

A: You have not provided enough information. Lets assume you have ASP.NET MVC app.
UI

View

Controller


text:
Q: external libraries in FreeFem ++ We are talking about FreeFem++ (based on C++).
I need to calculate the eigenvalues and eigenvectors of a matrix (stored in a bidimensional array) that it is created from a internal calculus, not created from bilinear form. Then I would to use an external function (then external library) that it can calucate a vector of eigenvalue and matrix that contains the eigenvector as a column.
In a FreeFem documentation there are examples that involves  I do not find technical support for this part.


text:
Q: ggplot2 in R: fill underneath a geom_smooth line I am trying to fill in a portion of a plot underneath a geom_smooth() line.
Example:

In the example the data fits on that curve. My data is not as smooth. I want to use geom_point() and a mix of geom_smooth() and geom_area() to fill in the area under the smoothed line while leaving the points above.
A picture of my data with a geom_smooth():

In other words, I want everything underneath that line to be filled in, like in Image 1.

A: Use predict with the type of smoothing being used. geom_smooth uses loess for n < 1000 and gam for n > 1000.
library(ggplot2)

ggplot(mpg, aes(displ, hwy)) +
    geom_point() +
    geom_smooth() +
    geom_ribbon(aes(ymin = 0,ymax = predict(loess(hwy ~ displ))),
                alpha = 0.3,fill = 'green')

Which gives:


text:
Q: How can i rapidly explore the classes of all columns in a dataframe? I want to rapidly explore the classes of columns in a dataframe, I made this function to print the columns names and arrange them by their class. I want it to tell me the numbers of the columns which aren't of class factor.
columnsclass<-function (x){
a<-vector()
b<-vector(mode="character")
c<-vector
c=0
for (i in 1:dim(x)[2]){
a[i]<-paste(class(x[,i]),names(x)[i],sep="--")
if (class(x[,i])!= "factor"){
c<-c+1
b[c]<<-i
}}
#1st print
print(sort(a))
#2nd print
print(paste("columns that aren't factors are number:",paste(b,collapse=","),collapse="  "))
}

However when i run it, it doesn't do the #2nd print though the code is already working.
> columnsclass(cars)
[1] "numeric--dist"  "numeric--speed"
[1] "columns that aren't factors are number: "
#it doesn't print the numbers of columns of class factor but if i run it separately ,it  runs
> print(paste("columns that aren't factors are   number:",paste(b,collapse=","),collapse="  "))
[1] "columns that aren't factors are number: 1,2"

A: Here's a function that takes into account Pierre's comments, but simplifies a's calculation as well:
columnsclass <- function(x){
  nm <- sapply(x, class)
  a <- paste(nm, names(nm), sep = "--")
  b <- which(!sapply(x, is.factor))
  # 1st print
  print(sort(a))
  # 2nd print
  print(paste("columns that aren't factors are number:",
    paste(b, collapse = ","), collapse = "  "))
}
> columnsclass(cars)
[1] "numeric--dist"  "numeric--speed"
[1] "columns that aren't factors are number: 1,2"

A: What about the str function?
library(datasets)
data(iris)
str(iris)


text:
Q: Question about calculus and real analysis Let $x_n = \frac{p_n}{q_n} $ be asequence of rational numbers where $p_n$ and $q_n$  are coprime. Suppose also that $\lim_{n \to \infty} x_n = x $. $(x_n \neq x)$ Can we conclude that, therefore,
$$ \lim_{n \to \infty} q_n  = \infty $$
???

A: We may assume $q_n>0$. Suppose that $q_n\le M$. If $x_m\ne x_n$ then
$$
\Bigl|\frac{p_m}{q_m}-\frac{p_n}{q_n}\Bigr|=\frac{|p_m\,q_n-p_n\,q_m|}{q_n\,q_m}\ge\frac{1}{M^2}.
$$
This implies that $\{x_n\}$ is no a Cauchy sequence, and hence does not converge.


text:
Q: OpenCV tutorial problems I am doing a few basic tutorial on OpenCV.
However on this: "https://docs.opencv.org/master/d4/d14/tutorial_windows_visual_studio_image_watch.html" tutorial I am running into problems.
Here is my code:
#include <opencv2/opencv.hpp>

using namespace cv;

int main(int argc, char** argv)
{
    char* imageName = argv[1];

    Mat image;
    image = imread(imageName, IMREAD_COLOR);

    if (argc != 2 || !image.data);
    {
        return -1;
    }

    Mat gray_image;
    cvtColor(image, gray_image, COLOR_BGR2GRAY);

    imwrite("C:\OpenCV-test-imgs", gray_image);

    namedWindow(imageName, WINDOW_AUTOSIZE);
    namedWindow("Gray image", WINDOW_AUTOSIZE);

    imshow(imageName, image);
    imshow("Gray image", gray_image);

    waitKey(0);

    return(0);
}

It is basically the same as in the tutorial.
I am expecting one or two windows to pop up showing me the two images of the cat.
except I'm getting the error :

The program '[14300] image-watch-demo.exe' has exited with code -1
  (0xffffffff).

What am I doing wrong here?
Should I make a folder containing an image?
And if so where should this folder be place and how should it be called.
I'm sorry if this is a dumb quest, I am a beginner to OpenCV and coding/visual studio in general.
Thanks in advance


text:
Q: Curl can't get a webpage properly I've been trying to grab one page via Curl but fail to do it properly as the page is returned badly encoded. Here's the page: http://www.movinsane.com/play13.php?vid=107628 Would you please tell me what how to do it with the help of PHP's Curl so that I can view it properly. Any help would be much appreciated. Thanks in advance!
$c = curl_init('http://www.movinsane.com/play13.php?vid=108561');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_ENCODING, "gzip");
$sourse = curl_exec($c);
curl_close($c);

echo $sourse;

A: This is not a curl related problem. It downloads the content properly. You have to include a <base href="http://www.movinsane.com/"/> before writing out the $sourse.
My opinion is that these type of actions are phishings.


text:
Q: median() coming back as NA for df of integers? Have a data frame of numerical data and using apply with median along columns. I'm getting NA for the median even though there are some non-zero entries in the columns. I did str(df) to ensure all of the df is integer and it is. What does it mean when R says the median is NA? Thanks.
v1  v2  v3.....
1   3   4
0   0   0
.   .   .

Also, I got a bunch warnings like this:
           "1: In mean.default(sort(x, partial = half + 0L:1L)[half +  ... :
           argument is not numeric or logical: returning NA"

A: My solution it is trivial but maybe there are some NAs you did not see. Try to use apply with the na.rm = FALSE in the last argument (the ellipsis).
Using the code provided by akrun.
set.seed(24)
df1 <- as.data.frame(matrix(sample(0:5, 10*5, replace=TRUE), ncol=5))
apply(df1, 2, median)

I add some NA
df1[ 3 , "V2" ] <- NA

and then use sapply (which is the same due to the fact that a data frame is a type of list )
sapply(df1, median, c(na.rm = TRUE))

edit:
consider that str(df1) return int even if there is an NA at row 3 column V2.


text:
Q: XAMPP FTP errors I have a windows 2012r2 server that I am trying to setup with Xampp. I can get everything but FTP wont allow me to upload. Ive tried forcing it to use active mode. Ive tried forcing the ports on the server and client side. Ive disabled firewalls but when I try to upload it tells me 500 syntax error and doesn't transfer. It also will drop down to passive mode. Internally it works and on the server it works but it doesn't go through the edge firewall we have in place. What ports do I need to open to get this working?

A: If you ask about the Ports FTP uses the Ports
21 for Login and
20 for Data Transfer
but the Passive Mode requires the Firewall to have a FTP Traffic Tracking Logic that would mark the Data Transfer Traffic as related.
But from your reported error 500 syntax error I would think that your FTP Client tries to use commands that the FTP Server in question does not support.


text:
Q: System.LimitException: Apex CPU time limit exceeded error in web service I have a webservice exposed in SFDC. SFDC will receive account records from external system. Based on the accounts received, its parent and child will be updated.
It works fine. However when 1000 or more records are sent, it fails with the below error
System.LimitException: Apex CPU time limit exceeded
Though my code is very large, i have followed the best practice. Also it worked perfectly fine for 750 records.
Is it a limitation or can something be done on SFDC side to overcome the error.

A: I'm surprised you're hitting this with 1000 records, are you 100% sure there's no conditions caused by the larger data set (dupes or similar) that's causing an infinite loop in the code?
If there are no such bugs and you simply are hitting the limit then the first option would be to ensure the sending system sends a manageable amount of records each time, staying within a comfortable limit. If that's not possible then you'll need to restructure your solution on the Salesforce side, perhaps insert the information into holding records in a custom object, and then use a batch job to pick those up and turn them into proper accounts. If the accounts are basic but it's a lot of processing afterwards that needs to be done then maybe that's the bit to separate out, it'll depend entirely on what your code is doing.
To sum it up, there's no way to bypass this limit and you have to work within it, it's all part of being on a multi-tenancy system, but to take 10 seconds to process 1000 records definitely suggests that there's an infinite (or massively nested/recursive) loop going on somewhere.


text:
Q: How to set env with laravel artisan to have two different database connections (local/remote)? I looking for setup a multi-environment project using Laravel3 but I dont understand the command to set the environment.
I see here: http://laravel.com/docs/artisan/commands
The command is:
php artisan foo --env=local

I already used artisan and bob with success, what I can't undertand the foo, I try to change to my project name but always the same output: "Sorry, I can't find that task."
If I try:    php artisan --env=local
That will return: "You forgot to provide the task name."
Anybody can help? Thanks for your time.
[edit] With the answers now I can understand better and improve my question:
I have a project with those folders created: http://d.pr/i/5nZS
With that in mind, I need to set my local env as development and production as production. So, I can do that with any variation of the command "php artisan --env=local" or I need to add on my public/.htaccess "SetEnv LARAVEL_ENV development"?
Thanks again.

A: "Foo" is whatever command you want to run. E.g. for migrations:
php artisan migrate --env=local

Another thing you can do is add your computers hostname to this array
For example, if my local computer name is 'Effinity.local' I could do
$environments = array(
    'local' => array('http://localhost*', 'Effinity.local'),
);

Then you do not need to specify the environment, just:
php artisan migrate

Hope that helps.

A: Here, how I solved my question:
First I didn't need the command php artisan migrate --env=local, I just need set on my virtualhost: SetEnv LARAVEL_ENV development.
Second, as William Cahill-Manley say, I need to work on application/paths.php, the $environments. I've used it before but the wrong way. In my case, I solve with that:
$environments = array(
    'development' => array('http://localhost/project*', '*project/*'),
    'production' => array('http://project.com', 'http://*.project.com')
);

My problem was because my code before was like that:
$environments = array(
    'development' => array('http://localhost/project*', '*project*'),
    'production' => array('http://project.com', 'http://*.project.com')
);

And because the second element of development array, in the production server always will be in development.
Thats because the url on development be http://project/ and on production be http://project.com/ or http://user.project.com/
See, the project will force in all envonriments be development by the asterisk/wildcard.

A: Foo is a task name , try to create this file in the task folder, there are some other task which is predefine for example migration etc.
<?php
    class foo_task {
    public function run(){
            echo 'this is foo';
        }
    }
?>

then when you run the command,it will run the code inside the run function.
php artisan foo --env=local

A: I'd recommend setting up a name-based virtual host for your web application first:
<VirtualHost *:80>
    ServerAdmin postmaster@localhost
    DocumentRoot "__PATH TO YOUR SERVER ROOT___/project/public/"
    ServerName project.dev
    ErrorLog "logs/project-error.log"
    CustomLog "logs/project-access.log" combined
</VirtualHost>

Then add project.dev to your hosts file /private/etc/hosts as follows:
127.0.0.1 project.dev

Don't forget to flush the DNS cache afterwards:
$ dscacheutil -flushcache

Then amend the $environments array found in [project root]/path.php (the applications/path.php file you mentioned does not exist) back to what it was. The original *.dev wildcard will pick up the .dev at the end of the url you provided.
$environments = array(

    'local' => array('http://localhost*', '*.dev'),

);

Then create a directory within applications/config/ called local, place within the new directory a file called application.php. The configuration given in this file will override the configuration set by the corresponding configuration files and settings/values given in the parent of the local directory you have created.


text:
Q: What C++ projects should I start? I'm a high school student, and I have a decent amount of programming experience (HTML, Javascript, PHP, Actionscript 3.0). I know C++, but unlike the other languages I know, I have never actually made any decent sized projects with it. I am puzzled at what kind of project I should start, as there are so many things you can do with C++.
I just want some experience making something - but right now I don't know what I want to do!
HELP ME!

A: Find some open source projects and offer your help. You get to see other's code and have a goal on what to develop.
Find something that interests you. That will keep your attention the longest.

A: Pick something you're either passionate in, or something that might help you at home.
If you do that, then you have a vested interest in it rather than it being just another application.
For me, I wrote a small system to keep track of my customers.  Now I know there are any number of applications that do that but I just wanted something small and custom so it really worked for me.
After that, when it was working, I then went back and refactored etc.

A: I see this question quite often. My reply is always the same. Programming is about scratching an itch. First find something that interests you and doesn't have a solution (or at least a good one). That's the itch.
Next sort out the best solution. It may be C++, .Net, Java or any one of a hundred other languages. The key is to pick the right tool for the job. If you try and push the square language in the round problem you will fail.
Programming is not about any one language. It's about finding the best solution to a problem and implementing it well using the right tools. This is what makes the difference between someone who knows a programming language, and someone who solve problems. The first are a dime a dozen, the second and worth their weight in gold.

A: Write a bitmap parser and viewer entirely from scratch, don't use any existing libraries. If you want an even bigger challenge, write a jpeg parser, that will require writing a huffman decompression algorithm and all sorts of other goodies.
I did this in java recently for a challenge, the program was rubbish but the amount of things I learnt made it worth while.

A: You could geek it up and create a complicated RPG (Maybe start with a simple form or console based game to get logic than maybe move on to directx or something).
I made an RPG myself but really never got to directx... yet.  It can be fun because the game can be about whatever you want, your imagination is the only limitation.  Figuring out the logic is a great way to stimulate your brain and learn new techniques in the process.

A: Try and find a copy of The OpenGL Programming Guide and have fun with some graphics programming.  Old editions can usually be had cheaply.
The examples are all in C, not C++, but its good to get some experience in C too.
Also, see if your school or community hosts programming contests.  One of my first large programs was a game for a junior-high level contest (though that was a long, long time ago).


text:
Q: How to use a saved (.h5) keras model with CasADi for MPC? I am new to CasADi. I have a saved Keras model in .h5 format that represents my system dynamics, and would like to use CasADi and develop a Model Predictive Control. Can you help on how to do this? is there any alternative useful library to use?
I could not find any useful resources online.


text:
Q: How to configure custom MediaType in Spring MVC? Using Spring MVC, I have controllers already working for both JSON and XML media formats.
In the content negotiation configuration, I would like to rely on Accept header only, and introduce a custom name media type, for example: "myXml"
My configuration:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
           .favorPathExtension(false)
           .favorParameter(false)
           .ignoreAcceptHeader(false)
           .useJaf(false)
           .mediaType(MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON)
           .mediaType(MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_XML)
           .mediaType("myXml", MediaType.APPLICATION_XML)
           .defaultContentType(MediaType.APPLICATION_JSON);
    }
}

My Controller:
@RequestMapping(value = "/manager/{id}",
        method = RequestMethod.GET,
        produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}
)
@ResponseBody public Manager managers(@PathVariable long id){
    return repo.getManagerById(id);
}

It works pretty well, Accept header: application/json produces JSON, application/xml produces XML. Anything else returns 406 Not Acceptable, even myXml.
I expected xml though...

A: With that configuration, you basically:

*

*ignored content negotiation using params or path extensions

*registered "json -> application/json" "xml -> application/xml" "myXml -> application/xml" as possible path extensions / params for negotiating to those media types. (see more about this here)

*told Spring MVC that whenever the HTTP client sends "Accept: */*" or no Accept header at all, the default ContentType should be "application/xml"

I don't think you intended to handle content negotiation like this.
You probably want to customize HttpMessageConverters (see here), like registering a Jaxb2RootElementHttpMessageConverter (if using JAXB) or a MappingJackson2XmlHttpMessageConverter (if using Jackson) and registering them with both "application/xml" and "myXml" media types.
Also, don't forget to add "myXml" in the "produces" part of the RequestMapping annotation - your controller method should declare it as a media type it can produce, otherwise it will will throw 406 again.
My advice
You should definitely use a media type like "application/vnd.foobar.v.1.0+xml" since:

*

*this is something relevant to http clients

*xml HttpMessageConverters in Spring are already registered to deal with "application/xml" and "application/*+xml".

In that case you can juste keep the defaultContentType part in your configuration (and probably set it to your custom media type) and throw away the rest.
In any case, you should still declare this custom media type in the produces section of your mapping annotations.


text: Q: How to work on Amazon Device Messaging with Unity? I'm developing an app that uses FCM for ios and android, but I need to use ADM for FireOS. Does anyone have a guide on using Amazon Device Messaging with their Unity Project?


text:
Q: Combinatorics: can someone verify my answer? I'm preparing for a test but I do not have the solutions available (as there are no solutions). It would be nice if someone could point out whether I solved the following exercise correctly.
Question: 11 people are going to dinner at a fancy restaurant. Every person is very hungry so everyone decides to take an entree, main dish and dessert. There is not much choice though: 2 choices for the entree, 3 for the main dish and 2 for the dessert. A waitress makes a list with all the dishes (in total 7) and how many times this dish is ordered. How many possible lists can the waitress make?
Solution
I believe this uses combinations with repitition:
The solution then would be:
$$\binom{12}{11} \binom{13}{11} \binom{12}{11} = 11232 $$
Could someone verify this solution please?
Thanks in advance :)

A: Your answer is correct. We can analyze the possibilities for each course independantly using stars and bars.
There are $\binom{12}{11}$ posssibilities for the entree, $\binom{13}{11}$ for the main dish and $\binom{12}{11}$ for the dessert.


text:
Q: Whose buttocks are these? In Charlie Stross' Overtime, Bob Howard finds himself stuck in the office at Christmas, having 'volunteered' as Night Duty Officer. He begins to settle in for a boring couple of nights, when he finds a strange photocopy:

One of the copiers has a print job stacked facedown in the output tray.
(...)
I flip the first sheet over to look for the header page, and do a double take. Buttocks! Pretty damned hairy ones, at that. So someone was enjoying the party.
The next page features more buttocks, and they're a lot less male, judging by the well-filled stockings and other identifying characteristics. I shake my head. I'm beginning to work out a response—I'm going to pin them on one of the staff notice boards, with an anonymous appeal for folks to wipe down the copier glass after each use—when I get to the third sheet.
Whoever sat on the copier lid that time didn't have buttocks, hairy or otherwise—or any other mammalian features for that matter. What I'm holding looks to be a photocopy of the business end of a giant cockroach.
Maybe I'm not alone after all. . . .

Now later on, a certain character is implied to be not quite human:

 Kringle crosses his arms affrontedly. At least, I think they're arms—they're skinny, and there are too many elbows, and now I notice them I realize he's got two pairs.

But was the copy his? If so, why? If not, whose was it?

A: It was Kringle. He came back in time (or forward in time, depending on your perspective) and created the photocopies in order to make Bob aware that he was in danger. Note the reference to (insectoid) double elbows earlier in the piece as well as this exchange:

The spectral shade in its ragged robe bobs its head—or whatever it has
in place of a head. "The Christmas incursion—" I glance at the cold
furnace again, then at my watch "—would have killed you. But without
Forecasting Ops to warn us about it, it'd happen anyway, wouldn't it?"
Three minutes. "So you had to maneuver someone into position to deal
with it even though you don't exist."
I remember sitting through a bizarre and interminable lecture at the
Christmas party. But who else remembers sitting through it? Andy
doesn't remember Kringle's talk. And I bet that aside from my own
memories, and a weirdly smudged photocopy—emergent outcome of some
distorted electron orbitals on a samarium-coated cylinder—there's no
evidence that the ghost of Christmases
rendered-fictional-by-temporal-paradox ever visited the Laundry on a
wet and miserable night.

Stross also (semi-)confirmed this theory in a recent tweet.

Answerguesser401: @cstross - I'm confused. In Overtime, who did the (photocopied) insectoid buttocks belong to?
Charlie Stross: @Answerguesser40 re read it. Hint: temporal paradoxes happen.
10:16 AM - 7 Feb 2015


text:
Q: 301 redirect index.html to / or /index.php Greetings,
I have just moved a website from IIS to Apache and am having a little trouble redirecting the index file without causing an infinite loop.
Both of these individually will cause a loop-
Redirect 301 /index.htm /index.php
Redirect 301 /index.htm http://www.foo.com/
Below is a copy of my current .htaccess.  Can someone help me?  I have a bunch of links pointed to http://www.foo.com/index.htm that I would like to 301 redirect to http://www.foo.com/
RewriteEngine On

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /

########## Begin - Joomla! core SEF Section
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|\.cfm|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section

Redirect 301 /a /administrator

A: Why are you doing this? Why not add index.php to your vhost/config as a valid index extension
DirectoryIndex index.html index.php

And then delete the HTML file>
or
DirectoryIndex index.php

A: I guess you have your directory index set to index.html, and it occurs before index.php. Then your http://www.foo.com/ is interpreted as http://www.foo.com/index.html, and it is redirected to http://www.foo.com/ - hence the loop.
Here you got some info about redirects the diffrent ways.

A: You would need to check the value of REQUEST_URI like this:
RewriteCond %{REQUEST_URI} ^/index.htm$     # If REQUEST_URI == "/index.htm"
RewriteRule (.*) / [R=301,L]                # Then 301 redirect to "/"

A: I agree with Kender's comment about the redirect loop. Possibly the way round that is to have
DirectoryIndex notindex.html
along with your redirects, then put the actual front page in notindex.html. I'm not clear what's wrong with people using /index.html if that page really exists?

A: I'm not allowed to add hyperlinks yet, as I'm a new user, so when I've typed "foo" just assume thats the entire URL...
To redirect foo/index.php to foo/ without the loop, use another rewrite rule:
RewriteRule index.php foo/ [R=301]

You might need to use /index.php depending on what your RewriteBase is set as (and how many directories you have an index.php in).


text:
Q: Diagonalise and concatenate every row of a matrix Given a matrix:
A = [1 2 3
     4 5 6
     7 8 9]

How to diagonalize each row of A and concatenate them simultaneously, so it yields the following?
1 0 0 4 0 0 7 0 0
0 2 0 0 5 0 0 8 0
0 0 3 0 0 6 0 0 9

A: You probably want to use the diag(v) function, and apply it to every row of A.
B = diag(A(1,:))
for i=2:size(A)
    B = [B,diag(A(i,:))]
end


text:
Q: Leader election kubernetes I have 2 application with 3 replica each deployed within the same namespace in same cluster. Both of these application can have singleton instance running at a time.
Can i use leader elector kubernetes in any way to have one leader for each deployment running at a time in same namespace ??
Tried leader elector but once deployed only one out of total 6 replicas for 2 deployment are coming up even when leader elector is implemented as sidecar in each deployment separately.