text:
Q: Matlab - Trying to use vectors with grid coordinates and value at each point for a color plot I'm trying to make a color plot in matlab using output data from another program. What I have are 3 vectors indicating the x-position, y-yposition (both in milliarcseconds, since this represents an image of the surroundings of a black hole), and value (which will be assigned a color) of every point in the desired image. I apparently can't use pcolor, because the values which indicate the color of each "pixel" are not in a matrix, and I don't know a way other than meshgrid to create a matrix out of the vectors, which didn't work due to the size of the vectors.
Thanks in advance for any help, I may not be able to reply immediately.

A: If we make no assumptions about the arrangement of the x,y coordinates (i.e. non-monotonic) and the sparsity of the data samples, the best way to get a nice image out of your vectors is to use TriScatteredInterp.  Here is an example:
% samplesToGrid.m
function [vi,xi,yi] = samplesToGrid(x,y,v)

F = TriScatteredInterp(x,y,v);
[yi,xi] = ndgrid(min(y(:)):max(y(:)), min(x(:)):max(x(:)));
vi = F(xi,yi);

Here's an example of taking 500 "pixel" samples on a 100x100 grid and building a full image:
% exampleSparsePeakSamples.m
x = randi(100,[500 1]); y = randi(100,[500 1]);
v = exp(-(x-50).^2/50) .* exp(-(y-50).^2/50) + 1e-2*randn(size(x));
vi = samplesToGrid(x,y,v);
imagesc(vi); axis image

Gordon's answer will work if the coordinates are integer-valued, but the image will be spare.

A: You can assign your values to a matrix based on the x and y coordinates and then use imagesc (or a similar function).
% Assuming the X and Y coords start at 1
max_x = max(Xcoords);
max_y = max(Ycoords);

data = nan(max_y, max_x); % Note the order of y and x
indexes = sub2ind(size(data), max_y, max_x);
data(indexes) = Values;

imagesc(data); % note that NaN values will be colored with the minimum colormap value


text:
Q: Setting attribute to NULL in Yii2 and save to database In Yii we had CDbExpression('NULL') what is the equivalent in Yii2? Need to set a database column back to null via a model in Yii2

A: If i remember correctly yii2 don't make a string conversion for null value  when you can try setting the value to NULL
$model->field = NULL;

A: You can set NULL value directly to model attribute:
$model->field=null;

or config default value in rules() method
[['field'],'default',null]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is setting my UINavigationBar's background image affecting the size of the navigation bar? I'm doing something like this:
UIImage *barBackgroundImage = [UIImage imageNamed:@"myImage.png"];
[[UINavigationBar appearance] setBackgroundImage:
                                    backgroundImage
                                   forBarMetrics:UIBarMetricsDefault];

And the resulting UINavigationBar is much larger than the standard navigation bar. I'm aware that my image size might be the problem. Is there any way to take care of this programmatically?

A: This is how I set the UINavigationController's navigationBar background image.
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setTintColor:LIGHTBROWN];

navbar.png is 320x44 and respectively 640x88 for navbar@2x.png.

A: Follow this link to make your code compatible with iOS4, 5 and 6: http://robert-varga.com/?p=735
You just have to make in Photoshop or other software a rectangular with the size of 320x44 or 640x88 (for retina display) and import it to your project


text:
Q: How to pass objects to methods in other classes in VB6 I have created two classes as interface / implementation classes, and wish to pass a particular example of one class to a method in the other. The definitions are as follows...
Class BigInt...
Option Explicit
Public Sub dothing(ByRef passed_object As MyInt)
End Sub

and an implementation BigImplementation...
Option Explicit
Implements BigInt

Public Sub BigInt_dothing(ByRef passed_obj As MyInt)
Dim i As Integer
i = passed_obj.getprop
End Sub

The class I am planning to pass is...
Option Explicit

Public Property Get getprop() As Integer
End Property

Public Property Let letprop(ByVal myval As Integer)
End Property

implemented as MyImplementation thus...
Option Explicit
Implements MyInt
Private myval As Integer

Public Property Get myint_getprop() As Integer
myint_getprop = myval
End Property

Public Property Let myint_letprop(ByVal passed_int As Integer)
myval = passed_int
End Property

I am then driving this with the following snippet of code:-
Private Sub Command_Click()
Dim myobj As MyInt
Set myobj = New MyImplementation
Dim mybigobj As BigInt
Set mybigobj = New BigImplementation

myobj.letprop = 1
Call mysub(myobj)
mybigobj.dothing (myobj)   ' Line with problem
End Sub

Private Sub mysub(ByVal passed_obj As MyInt)
Dim i As Integer
i = passed_obj.getprop
End Sub

When the execution reaches the line marked, I get run-time error 438 - Object doesn't support property or method. The call to the ordinary function mysub works perfectly. Does anyone know what I am doing wrong and what I need to do to fix this?

A: Use either
mybigobj.dothing myobj

or
Call mybigobj.dothing(myobj)

Putting extra parentheses around a reference evaluates its default property and passes it's value as actual argument.

A: mybigobj.dothing requires its parameter to be a MyInt
Public Sub BigInt_dothing(ByRef passed_obj As MyInt)
Dim i As Integer
i = passed_obj.getprop
End Sub

You're passing a MyImplementation
Set myobj = New MyImplementation

So possiblly something like (my vb is rusty)
mybigobj.dothing (myobj.myint_getprop())


text:
Q: Scheduling multiple batch classes from postinstall script of managed package I know we can schedule batch classes from post install scripts, but need to confirm this in my scenario.
I have to schedule two batch classes which will update the data of two objects and also insert attachments during upgrade of managed package. During update, multiple triggers will execute.
Post install script uses ghost user. Will this user be able to access the records and perform DML through dependent classes (with sharing). Also, I am using SoC pattern in dependent classes.


text:
Q: Missing attribute 'filename' in tag qualified by namespace 'urn:xmpp:http:upload:0' I am trying to transfer files between applications using ejabberd-18.06 and SMACK-4.2.0 as the android client.
mod_http_upload is configured in ejabberd and using HttpFileUploadManager from SMACK.
When i try to upload file, it is not uploading.
Getting below error from ejabbered log:

Missing attribute 'filename' in tag qualified by namespace 'urn:xmpp:http:upload:0'

But you can see the file name is there from detail debug log from ejabbered:
#iq{id = <<"1TNIF-33">>,type = get,lang = <<"en">>,
    from =
        #jid{
            user = <<"mamun">>,server = <<"localhost">>,
            resource = <<"130055862109590748621314">>,luser = <<"mamun">>,
            lserver = <<"localhost">>,
            lresource = <<"130055862109590748621314">>},
    to =
        #jid{
            user = <<>>,server = <<"upload.localhost">>,resource = <<>>,
            luser = <<>>,lserver = <<"upload.localhost">>,lresource = <<>>},
    sub_els =
        [#xmlel{
             name = <<"request">>,
             attrs = [{<<"xmlns">>,<<"urn:xmpp:http:upload:0">>}],
             children =
                 [#xmlel{
                      name = <<"filename">>,attrs = [],
                      children = [{xmlcdata,<<"img.jpg">>}]},
                  #xmlel{
                      name = <<"size">>,attrs = [],
                      children = [{xmlcdata,<<"19691">>}]},
                  #xmlel{
                      name = <<"content-type">>,attrs = [],
                      children =
                          [{xmlcdata,<<"application/octet-stream">>}]}]}],
    meta = #{ip => {192,168,1,5}}}
2018-08-15 21:52:17.204 [debug] <0.495.0>@ejabberd_router:do_route:352 route:
#iq{id = <<"1TNIF-33">>,type = error,lang = <<"en">>,
    from =
        #jid{
            user = <<>>,server = <<"upload.localhost">>,resource = <<>>,
            luser = <<>>,lserver = <<"upload.localhost">>,lresource = <<>>},
    to =
        #jid{
            user = <<"mamun">>,server = <<"localhost">>,
            resource = <<"130055862109590748621314">>,luser = <<"mamun">>,
            lserver = <<"localhost">>,
            lresource = <<"130055862109590748621314">>},
    sub_els =
        [#xmlel{
             name = <<"request">>,
             attrs = [{<<"xmlns">>,<<"urn:xmpp:http:upload:0">>}],
             children =
                 [#xmlel{
                      name = <<"filename">>,attrs = [],
                      children = [{xmlcdata,<<"img.jpg">>}]},
                  #xmlel{
                      name = <<"size">>,attrs = [],
                      children = [{xmlcdata,<<"19691">>}]},
                  #xmlel{
                      name = <<"content-type">>,attrs = [],
                      children =
                          [{xmlcdata,<<"application/octet-stream">>}]}]},
         #stanza_error{
             type = modify,code = 400,by = <<>>,reason = 'bad-request',
             text =
                 [#text{
                      lang = <<"en">>,
                      data =
                          <<"Missing attribute 'filename' in tag <request/> qualified by namespace 'urn:xmpp:http:upload:0'">>}],
             sub_els = []}],
    meta = #{ip => {192,168,1,5}}}

ejabberd configaretion:
mod_http_fileserver:
    docroot: "C:/ProgramData/ejabberd/upload"
    accesslog: "C:\\Program Files\\ejabberd-18.06\\logs\\access.log"

mod_http_upload:
   docroot: "C:/ProgramData/ejabberd/upload"
   put_url: "http://@HOST@:5443"
   custom_headers:
     "Access-Control-Allow-Origin": "*"
     "Access-Control-Allow-Methods": "GET, POST, PUT, OPTIONS"
     "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
mod_http_upload_quota:
   max_days: 30
......
-
 port: 5280
 ip: "0.0.0.0"
 ##ip: "::"
 module: ejabberd_http
 request_handlers:
   "/ws": ejabberd_http_ws
   "/bosh": mod_bosh
   "/oauth": ejabberd_oauth
   "/api": mod_http_api
   "/pub/archive": mod_http_fileserver
 web_admin: true
 captcha: false
-
 port: 5443
 ip: "0.0.0.0"
 module: ejabberd_http
 tls: true
 request_handlers:
   "": mod_http_upload

SMACK Code:
HttpFileUploadManager httpFileUploadManager=
  HttpFileUploadManager.getInstanceFor(activity.getXmppConnectionManager()
 .getConnection());
File file = new File("/mnt/sdcard/img.jpg");
try {
    Log.i("UPLOAD_SERVICE",
      httpFileUploadManager.isUploadServiceDiscovered()+"");
    Log.i("FILE_UPLOAD",httpFileUploadManager.uploadFile( file);
  } catch (InterruptedException e) {
        e.printStackTrace();
  } catch (XMPPException.XMPPErrorException e) {
        e.printStackTrace();
  } catch (SmackException e) {
        e.printStackTrace();
  } catch (IOException e) {
        e.printStackTrace();
  }


text:
Q: Alterar divs com a mesma classe

         33
         88
         55
         36
         79
         35

Preciso colocar o simbolo de porcentagem após o número

Tentei fazer desta forma mas ele altera todos os numeros para o primeiro valor

A: Tem que fazer o concat para cada um, a sugestão aqui é fazer com o each:

  $(document).ready(function(){
       var valor = $('.valor').each(function(){
         val = $(this).html()
          $(this).html(val + '%')
       })
    });

 33
 88
 55
 36
 79
 35

A: Algumas formas de fazer:
1 - Usando JQuery (exemplo funcionando)
$('.valor').append('%');

2 - Usando apenas CSS (exemplo funcionando)
.valor:after {
  content: "%";
}

Esta técnica utiliza o pseudo-elemento ::after do CSS2.
Confira a compatibilidade com os diferentes navegadores.
3 - Usando apenas Javascript (exemplo funcionando)
var valores = document.getElementsByClassName('valor');

for (var i=0; valores[i]; i++) {
  valores[i].innerHTML += '%';
}

Esta opção não precisa do JQuery, e é compatível também com alguns navegadores antigos.

A: Tens que fazer esse processo para cada elemento (obj) que tem atribuída a classe referida. Podes aceder aos dados do objecto com o wrapper JQuery $(this).

Não testei mas acredito que será algo nestas linhas.

A:

A: Você deve iterar sobre todos os itens. Pode fazer isso utilizando a função  each. Você também pode acessar o elemento diretamente, como no código abaixo, ao invés de usar a função html().

$('.valor').each(function(){
    this.innerHTML+='%';
});


text:
Q: CSS LESSphp variable with CSS code block I would like to add multiple style declaration using lessphp. I have provide the $context array with the lessphp setVariables method.
$context['font'] = 'color: #ffffff; font-family: verdana;';

Then I would like to use it in the less file with the variable name, like this:
.selector{
  @font;
}

This doesn't work, what should be the appropriate way of handle this?

A: There are at least two issues with what you are trying to do based on both LESSphp and LESS syntax:

*

*The array from php needs to be pairs of variable names and values, not property names and values.

*LESS does not allow dynamic setting of property names.

So I believe a solution for you is something like this:
PHP
$context = array(
   "fontColor" => "#ffffff",
   "fontFamily" => "verdana"
);

$less->setVariables($context);

LESS
The above code should generate in the compiled LESS file the equivalent of this:
@fontColor: #ffffff;
@fontFamily: verdana;

Which then you use like this:
.selector {
   color: @fontColor;
   font-family: @fontFamily;
}


text:
Q: Android message notification dialog on top of other activities How do I get an Android message notification dialog on top of other activities?
I am searching for a solution to this problem and still not yet got the solution. Right now, I am developing a social networking app in which I need to show a notification message dialog whenever the user gets some message from another and to achieve that I have used the broadcast receiver and it is working fine.
The problem is how to show the notification dialog on top of another application.

A: Yes, it is possible. The Main.xml layout has one edit text and button. The Messagebox layout has one button. Here you can change message layout to whatever you want.
File MyScheduledReceiver.java:
public class MyScheduledReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        Intent scheduledIntent = new Intent(context, MessageBox.class);
        scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(scheduledIntent);
    }
}

Main Activity:
public class AndroidMessageBoxActivity extends Activity implements OnClickListener
{
    private EditText time;
    private Button btn;
    private AlarmManager alarm;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        time = (EditText) findViewById(R.id.editText1);
        btn = (Button) findViewById(R.id.button1);
        alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        int x = Integer.parseInt(time.getText().toString());

        Intent intent = new Intent(this, MyScheduledReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);

        alarm.set(AlarmManager.RTC_WAKEUP,
                  System.currentTimeMillis() + (x * 1000),
                  pendingIntent);
        Toast.makeText(this,
                       "Alarm set in " + x + " seconds",
                       Toast.LENGTH_LONG).show();
    }
}

MessageBox:
public class MessageBox extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.messagebox);

        Button btn = (Button) findViewById(R.id.Ok);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
    }
}

And add these two lines in the Android manifest XML file:
<receiver android:name="MyScheduledReceiver"></receiver>

<activity android:name="MessageBox" android:theme="@style/Theme.Transparent"></activity>

Filestyle.xml:
<resources>
    <style name="Theme.Transparent" parent="android:Theme">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>
</resources>

A: As others have said in their responses, launching an Activity from the background in order to get the user's attention is discouraged. However, some situations call for this; examples in Android itself include clock alarms, incoming calls, and low battery alerts.
In Gingerbread the fullScreenIntent field was added to Notification objects; this is a standard and convenient way to post a Notification that also launches an Activity to really get the user's attention. As of Gingerbread, the platform components I listed above (alarms, etc.) all use this technique to show their alerts. This is the recommended way to do what you're asking.

A: As stated in the documentation on Status bar notifications:

A background service should never launch an activity on its own in order to receive user interaction.

Therefore, I strongly advice you against doing that, but you should use a status bar notification instead.


text:
Q: Why are some functions available without having to load their parent package? Functions such as GraphDistanceMatrix[] or AdjacencyMatrix[] are available without invoking
Needs["GraphUtilities`"]

.
Why isn't the whole package available when Mathematica starts? Are the functions different after having loaded GraphUtilities?

A: If you look at their Contexts, you'll see that all of them are in the System` context and not the GraphUtilities` context.
Context /@ {GraphDistanceMatrix, CharacteristicPolynomial, AdjacencyMatrix}
Out[1]= {"System`", "System`", "System`"}

Some packages are preloaded when the kernel starts — System` is one of them, whereas GraphUtilities` is not. You can see all packages that are pre-loaded with $Packages
$Packages
Out[2]= {"ResourceLocator`", "DocumentationSearch`", "GetFEKernelInit`",
    "JLink`", "PacletManager`", "WebServices`", "System`", "Global`"}


text:
Q: php search through mysql fields for string match I have an input box where multiple words can be entered and searched for in my table.
supposing the user enters 'people places things' as their search criteria, these should get submitted to my php function which searches through my 'nouns' table and the 'description' and 'title' fields for possible matches.  The function should then sort the results in descending order by number of matches found.
what I've got so far (missing a lot, and possibly not even the correct method):
$lcSearchVal = "people places things";
$lcSearchVal = explode( ' ', $lcSearchVal );

foreach( $lcSearchVal as $lcSearchWord ){
   $qry_suggest = mysql_query( 'SELECT * FROM nouns
                            WHERE Active
                            AND ( ' . strpos($lcSearchWord, "description") > 0 . '
                               OR ' . strpos($lcSearchWord, "title") > 0 . ' ) '
                            );
}

I'm not sure what to do or where to go from here though....please help!

A: The query you are using will not work - you're using PHP functions to do the comparison to a plain string and appending the result of that comparison in your query.  All the DB will see is this:
SELECT * FROM nouns WHERE Active AND (-1 OR 0)
...because the php strpos function returns the numeric position of the found string (or -1 if not found.  You need to use comparison functions within the database itself, therefore, you aren't after php functions at all, rather you want mySQL comparison functions.
For reference, here is a list of them: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html
Here is a sample that , very simply, searches for matches.  You can improve this code quite a bit, but this should give you an idea:
$lcSearchVal = "people places things";
$lcSearchVal = explode( ' ', $lcSearchVal );

$sql = 'SELECT * FROM nouns WHERE Active=1 AND (';

$parts = array();
foreach( $lcSearchVal as $lcSearchWord ){
    $parts[] = '`description` LIKE "%'.$lcSearchWord.'%"';
    $parts[] = '`title` LIKE "%'.$lcSearchWord.'%"';
}

$sql .= implode(' OR ', $parts).')';
print $sql;

Mess around with it: http://codepad.org/fcNH5qyu
Also note, your WHERE Active clause is not valid - you have to give it a comparison.  I've assumed in my sample that Active field is a numeric 1 or 0.

A: You can't mix PHP functions with SQL like that. Your query is going to look something like:
... WHERE Active AND (1 or 0) ...

I'm guessing you'd want someting like this:
$lcSearchWord = mysql_real_escape_string($lcSearchWord);

... WHERE Active=1 AND (description LIKE '%$lcSearchWord$%' OR title LIKE '%$lcSearchWord$%') ...


text:
Q: Is it ok to pass a Flow from one composable to another? I have a view model which exposes a flow of events. I have that viewModel injected in a top level composable but I want to send the events to another composable (inside the top level composable).
Something like this:
@Composable
fun MainScreen(viewModel: MyViewModel) {
    SomeComponent(viewModel.events)
    // Other Stuff
}

@Composable
fun SomeComponent(events: Flow<MyEvent>) { // MyEvent is a sealed class
    LaunchedEffect(Unit) {
        events.collect {
            // Process the events
        }
    }
    // Other stuff
}

The reason I am collecting the flow in SomeComponent and not MainScreen is because I need access to some internal state of SomeComponent (it's a ScaffoldState actually) for processing the events.
I wrote this code in my app and everything seems to be working but I am not sure if this is a good thing to do.
My question is:
Are there any drawbacks in this approach that I missed? What can possibly go wrong here?

A: Passing a flow as parameter is fine. There is nothing special about a flow. It's just another data source like anything else. If you didn't pass it in, you would have to come up with some other way of accessing it and that would probably result in breaking the uni-directional flow pattern that Composables should adhere to.


text:
Q: Update a value before to request into API I'm working in a project where I have to modify a value certain number of times before I make a request to an API. The problem is that when I'm using hooks to update the value, when I'm trying to update the value, as useState is asynchronous, the update of the value stays in a past value. However the value get modified after doing the request.
How can I make that the value updated before my request?
Here is the code:
useEffect(() => {                                  // I'm using a useEffect hook to verify that my variable is updated. But that update is done late.
    console.log(valorTotal);
}, [valorTotal]);

const agregarPlato = async () => {
    if(validarCamposPlato()){
        try{
            let valorParcial = 0;
            let platoExist = await encontrarPlato(config, rvPlato);
            if(platoExist === true){
                setAgregadoMin(true);
                platoCodigo = await obtenerCodigoPlato(config, rvPlato);
                platosRegVent.push({codigoPlato: platoCodigo, cantidad: rvCantidad});
                let costoPlato = await obtenerValorPlato(config, rvPlato);
                valorParcial = valorTotal;
                setValorTotal(valorParcial += (costoPlato * parseInt(rvCantidad)));      // Here is where I'm changing the value of my variable.
                setRvPlato('');
                setRvCantidad('');
            }
            else{
                toast.error('The object wasn't found.');
                setRvPlato('');
            }
        }
        catch(error){
            toast.error('An unexpected error has ocurred');
            props.handleSubmit();
        }
    }
}
const finalizarRegVent = async () => {
    console.log(agregadoMin);
    if(validarCampos()){
        try{
            if(rvPlato !== '' || rvCantidad !== ''){
                agregarPlato();                                 // Here I'm calling the function above
            }
            if(agregadoMin === true){
                rvCodigo = await crearRegistroVenta(config, valorTotal, fechaActual, regVentMesa);         // Here I'm doing the request to save the value
                platosRegVent.forEach( (plato : any) => {
                    crearRegVentPlato(config, rvCodigo, platosRegVent.codigoPlato, platosRegVent.cantidad);
                });
                valorFinal = true;

            }
            else{
                toast.error('You have to add an object before doing this option.');
            }
        }
        catch(error){
            toast.error('An unexpected error had happened.');
            props.handleSubmit();
        }
    }
}

Thank you for your help.

A: Please try to use await in front of the calling function.
if(rvPlato !== '' || rvCantidad !== ''){
    await agregarPlato();
}

And write below code inside of hook event.
useEffect(() => {
    if(agregadoMin === true){
        rvCodigo = await crearRegistroVenta(config, valorTotal, fechaActual, regVentMesa);
        ...
    } else {
        toast.error('You have to add an object before doing this option.');
    }
}, [agregadoMin])

Then if agregadoMin is changed, hook will monitor changes and execute accordingly
Hope this helps you to understand.


text:
Q: is a value in a given list of values using javascript? How to find out if a given value is among some values? Similar to the IN operator in SQL or what you might expect from sets.  Let's suppose set is {male,female,xyz}. I want to find if male is in the set.

A: The in operator does exist in JavaScript. But it checks whether a property exists on an object.
You can use an object hash or an array:
var values = {male: true, female: true, xyz: true}
var valueToSearch = 'female';

valueToSearch in values; //true

var values = ['male', 'female', 'xyz']

values.indexOf(valueToSearch) !== -1 // true

EDIT:
Using a RegExp:
if(pattern.test(search)) {
   //search found
}

A: I think what you need is indexOf. Check this example to understand how to use it:
Determine whether an array contains a value

A: If you mean in an array you can use indexOf
var find = 'male';
var haystack = ['female', 'male', 'xyz'];

alert((haystack.indexOf(find) >= 0));

A: Object
var objNames = {
    "Michigan": "MI",
    "New York": "NY",
    "Coffee": "yes, absolutely"
};

Array
var arrNames = [
    "Michigan", "New York", "Coffee"
]

Function
function isIn(term, list) {
    var i, len;
    var listType = Object.prototype.toString.call(list);

    if (listType === '[object Array]') {
            for (i = 0, len = list.length; i < len; i++) {
                if (term === listType[i]) { return true; }
            }
            return false;
    }

    if (listType === '[object Object]') {
        return !!list[term]; // bang-bang is used to typecast into a boolean
    }

    // What did you sent to me?!
    return false;
}

Usage
var michiganExists = isIn('Michigan', objNames); // true

Note
I didn't use indexOf because the op didn't mention browser support, and indexOf doesn't work with all versions of Internet Explorer (gross!)


text:
Q: How can I log every printed output while printing inside an (external) function I am not so familiar with logger; please allow me to ask.
Basically I want to log everything I print. The problem is that the print lines are inside functions declared in external files. For example, my main.py file is like
from do_run import do_run
import logging
if __name__ == "__main__":

    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logger = logging.getLogger()
    logger.addHandler(logging.FileHandler('test.log', 'a'))
    global print
    print = logger.info
    do_run()

And I have printing lines in the do_run() function defined in a separate python file do_run.py:
def do_run():

    print('blah')

The problem is that 'blah' is not printed in the 'test.log' file, whlie I want it to be printed in it.
Is there a simple way to fix it?

A: Kind of hack-y but you can use patch from unittest.mock in order to have it log to the file as well as print.
from src.do_run import do_run
import logging
from unittest.mock import patch

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logger = logging.getLogger()
    logger.addHandler(logging.FileHandler('test.log', 'a'))
    with patch("src.do_run.print", logger.info):
        do_run()

When I run the above code I get a test.log file with the contents of blah in it.


text:
Q: Reuse of Python object created by enumerate I have a list of lists that I am searching through to find the indices of duplicates.
listA = [[1,2,3],[3,4,5],[6,7,8],[1,2,3]]
listA_set = [[1,2,3],[3,4,5],[6,7,8]]
enum_listA = enumerate(listA)
listA_indices = []
for i in listA_set:
    listA_indices([j[0] for j in enum_listA if j[1] == i])

The intended outcome is:
listA_indices = [[0,3],[1],[2]]

But instead I am getting:
listA_indices = [[0,3],[],[]]

If I include the enumerate within the in-line for loop (see example below), I receive the correct answer but see a significant reduction in speed. How can I perform this task without losing the enumerate information stored in enum_listA?
for i in listA_set:
    listA_indices([j[0] for j in enumerate(listA) if j[1] == i])

A: enumerate returns an iterator which can only be iterated once. So once it is exhausted, which is the case after you iterate it in the list comprehension of the first for loop iteration, it will not yield any more items.
If you want to keep the information, you will have to actually store that data in memory, for example as a list:
enum_listA = list(enumerate(listA))

Note that this effectively duplicates the information in the list and adds the indexes, so this is wasting a lot of extra memory and might not end up being more efficient than recreating the enumerate object over and over.
The performance difference you are seeing however comes from the fact that after the first loop iteration, the enumerator is empty, so the list comprehension no longer runs for subsequent iterations.

A: use a dict and a set and your code will run a lot more efficiently:
from collections import defaultdict

st = set(map(tuple, listA_set))
d = defaultdict(list)

for i, ele in enumerate(map(tuple,listA)):
    if ele in st:
        d[ele].append(i)

print(list(d.items()))

print(list(d.values()))

Output:
[((3, 4, 5), [1]), ((6, 7, 8), [2]), ((1, 2, 3), [0, 3])]
[[1], [2], [0, 3]]

If you want to maintain the order first seen:
from collections import  OrderedDict
d = OrderedDict()

for i, ele in enumerate(map(tuple, listA)):
    if ele in st:
        d.setdefault(ele, []).append(i)

print(list(d.items()))

print(list(d.values()))

output:
[((1, 2, 3), [0, 3]), ((3, 4, 5), [1]), ((6, 7, 8), [2])]
[[0, 3], [1], [2]]

Whatever way you use enumerate, your complexity is still quadratic, this will be considerably faster than your own approach.
Some timings on a random data set:
In [27]: from random import randint

In [28]: listA_set = [[randint(1,20) for _ in range(10)] for _ in range(2000)]

In [29]: listA = [[randint(1,20) for _ in range(10)] for _ in range(3000)]

In [30]: %%timeit
listA_indices = []
for i in listA_set:
    listA_indices.append([j[0] for j in enumerate(listA) if j[1] == i])
   ....:
1 loops, best of 3: 696 ms per loop

In [31]: %%timeit
st = set(map(tuple, listA_set))
from collections import  OrderedDict
d = OrderedDict()
for i, ele in enumerate(map(tuple,listA)):
    if ele in st:
        d.setdefault(ele, []).append(i)
   ....:
1000 loops, best of 3: 1.49 ms per loop

~400  times faster.

A: The reason you are seeing a significant reduction in speed (by your terminology) is that your second, correct version is actually computing the values you are looking for.
Because enumerate produces a generator, once you consume its values, you cannot produce them again. The second version you have presented is the correct way of using enumerate.
Side not, I'm not sure how your code is working at all. You are calling a list, a non-callable object
listA_indices([...])

Maybe, you meant to do
listA_indices += [...]


text:
Q: The ideal gas equation in higher dimensions Basically I wanted to know whether or not the ideal gas equation, $PV=NkT$ would hold in higher dimensions? If so, how would you go about proving this?
I can't see any reason as to why it shouldn't hold, all that changes would be that the volume element would be raised to the $d$th power, $V^d$, where $d$ being the number of dimensions, right?

A: I stumbled upon this and, because I had to deal with this recently, can share my solution:
Let's start with a microcanonical ensemble in $D$ dimensions.
$$
S = k \log \Omega
$$
with $S$ being the entropy, $\Omega$ the statistical weight, $k$ the Boltzmann constant.
$$
\Omega = \lim_{\Delta E \rightarrow 0} \frac{1}{\Delta E}
\int_{E \leq H \leq E+\Delta E} d\Gamma
$$
with Hamiltonian
$$
H = \sum_{n=1}^{N} \frac{\vec p_n^2}{2m}
$$
and
$$
d\Gamma = \frac{1}{N!} \prod_{n=1}^N \frac{d^Dp_n\,d^D\!q_n}{(2\pi\hbar)^D}
$$
results in
$$
\begin{align}
\Omega &= \frac{1}{N!\,(2\pi\hbar)^{DN}}
  \lim_{\Delta E \rightarrow 0} \frac{1}{\Delta E}
  \int_{E \leq H \leq E+\Delta E}
  \prod_{n=1}^N d^Dp_n\,d^D\!q_n \\
&= \frac{1}{N!\,(2\pi\hbar)^{DN}}
  \lim_{\Delta E \rightarrow 0} \frac{1}{\Delta E}
  \int_{E \leq H \leq E+\Delta E}
  \prod_{n=1}^N (d^Dp_n) \cdot V^N \\
&= \frac{1}{N!\,(2\pi\hbar)^{DN}}
  S_{DN}(\sqrt{2mE}) \cdot V^N \propto V^N\\
\end{align}
$$
I used the independence of $p$ and $q$ to split the integral and used that the resulting integral is the surface of a $DN$-dimensional hypersphere with radius $\sqrt{2mE}$: $S_{DN}(\sqrt{2mE})$. For this calculation it is sufficient to realize that $\Omega \propto V^N$ (see following).
$$
\begin{align}
&&dE &= TdS-PdV = 0 \\
\Leftrightarrow&&\frac{P}{T} &= \frac{dS}{dV}
  = \frac{\partial S}{\partial \Omega} \frac{d\Omega}{dV} \\
&&&=\frac{k}{\Omega} \frac{d\Omega}{dV} \\
&&&=\frac{kN}{V} \\
\Leftrightarrow&&PV&=NkT
\end{align}
$$
So the dimension does not matter.


text:
Q: limit posts to wall on fb app I have an fb app connected with my website. it will trigger a post to fb user's wall when he completes a search on my site. Is there anyway to have a limit on the number of posts to the wall? say 1 post per day or 3 posts per week?

A: Take a look at the Graph API documentation. Basically, Facebook will send you a Graph object for each of the users that log in. You can just keep a table in your DB that maps users to a counter for how many posts you've made to their wall, which you always check before posting to make sure it's not over the limit. When the time period is up, you can just reset the counter.
Here is some example code that will show how to access the Graph object: http://www.devshed.com/c/a/PHP/Facebook-PHP-API-Applications-Working-with-User-Data/


text:
Q: JSP page not rendering properly when served from WAR I have a web project on Eclipse using Tomcat.  My web.xml declares a welcome file
<welcome-file-list>
    <welcome-file>/WEB-INF/pages/testPage.jsp</welcome-file>
</welcome-file-list>

Simple stuff,  when I run the server locally through eclipse and I browse to it through my browser it shows me my testPage.jsp and the buttons,  javascript works fine.
Now .  when I export the same app unchanged to a WAR and then deploy this on a seperate server and browse to this through the same browser the testPage.jsp displays as a plain text file,  ie it is not rendered properly, see below  I just see plain HTML text. Why does my browser not render the buttons correctly if the page is served from a WAR running on a standalone tomcat but works fine when served from Tomcat running within my Eclipse?
    <%@ page contentType="text/html; charset=UTF-8"%>

                    <textarea id="annotationLookupInput"  style="margin-left:5px;width:300px;height:80px;" ></textarea>
                        <input type="submit" name="submit" onclick="annotationLookup()" value="Lookup Annotation ID">

                    <textarea id="annotationLookupResult" style="margin-left:5px;width:300px;height:80px;" ></textarea>

                    <textarea id="annotationSaveIDInput"  style="margin-left:5px;width:80px;height:40px;" ></textarea>
                    <textarea id="annotationSaveValueInput"  style="margin-left:5px;width:100px;height:40px;" ></textarea>
                        <input type="submit" name="submit" onclick="annotationSave()" value="Save/Update Annotation">

                    <textarea id="annotationSaveResult" style="margin-left:5px;width:300px;height:80px;" ></textarea>

A: If I recall correctly the JSPs should be placed directly inside the project folder and not inside WEB-INF.
You can try that and change the web.xml
<welcome-file-list>
    <welcome-file>testPage.jsp</welcome-file>
</welcome-file-list>


text:
Q: how do I programically create a page in WordPress if it doesn't exist already? how do I programically create a page in WordPress if it doesn't exist already?

A:
I want to write a plugin and to put some html controls in a page which will automatically create when user install the plug in

Based on that comment, you want to hook a function to your plugin's activation hook, which inserts a WordPress post object into the database;
function my_plugin_activate()
{
    wp_insert_post(array(
        'post_type' => 'page',
        'post_title' => 'Page Title',
        'post_content' => 'Page Content',
        'post_name' => 'page-slug',
    ));
}
register_activation_hook(__FILE__, 'my_plugin_activate');

A: How will you identify that page? Assuming you have a specific title, use something like
if( get_page_by_title('my_title') === false ) // page doesn't exist
{
    // insert the page using wp_insert_post
}

If you need help with wp_insert_post, please comment.

A: You can implement a function that intercepts the template_redirect action/filter, and inside that function include the theme's header and footer, while creating your own content to put into the body of the page. See the API link (above) for an example.
Here's a tutorial on the web.


text:
Q: Flask sustainability for the future I built a SaaS web application for commercial purpose using Flask as server side framework.
Since a while I'm having worries about Flask and Flask extensions sustainability for the future.
Quoting, among the other on this subject, this Packt article Open Source Software: Are maintainers the only ones responsible for software sustainability?:
The majority of open-source software that the world depends on is built by volunteers. When a business chooses to use open-source software this volunteer labor is essentially an unpaid vendor with no contractual obligations.
But - unlike the open source volunteers - I do have contractual obligations towards my clients.
So I tried to measure someway the project health by looking at Github numbers and comparing it to other projects, or trying to know how large is the users base for Flask and various extensions (mainly Flask-Sqlalchemy, Flask-Assets, Flask-Login, Flask-Socketio, Flask-WTF, Flask-Mail), , but it's not easy to get a picture. How many active maintainers are there? What is the chance that the project in the near future would lack financial and personnel resources and should quit, and how fast would  this quitting happen?
So I'd like to know if it's generally considered a good practice to include open source frameworks (I mean the ones not supported by big companies) in commercial server-side software for what it concerns future sustainability, and what other people facing with this problem are doing.
Is sometimes porting everything to Java the only safe way to go? (This question is based on the evidence that actually enterprise development is Java. But I also notice that today on Github spring-framework has 429 contributors while flask has got 562. On the other hand spring has 20.141 commits while flask has 3.799).

A: You can have a look at the Stack Overflow Developer Survey:
Developer Survey
In my expirience, an Open Source framework as big as Flask never died in the past.
With respect to the article, you provided: not only Open Source projects, even big companies can get something wrong. They often do. Thinking about WannaCry ransomware attack which caused a lot of damage on Windows Systems. And Windows is not an Open Source project.
It is a good thing, to do risk evaluation as you did. In my expirience, you are save using Flask for a commercial project.


text:
Q: How to copy text from tooltip in Html/JS I have an image on a page. On hovering to the image, you see a tool tip with some details. Say, for example - Name : xyz, Account id : abc1234, Technical id : 0000
User wants to copy some text from this tooltip like the account id abc1234. How can this be achieved in JS?
I am asking this from code perspective so that the end user can use this functionality. I am not looking for any hacks/tricks to copy the text from browser.

A: With CSS.
You can set a hover style in css, and set a hover class, with absolute positioning (top, left, right, bottom) and create a div:after and set the content with attr.
That means you need to write the values into attributes on the image.
.tooltip:hover:after
{
    border: 1px solid #fc0;
    padding: 3px 6px;
    background: #fffea1;
    content: attr(data-title);
    position: absolute;
    top: 0px;
    left: 0px;
    # right: 0px;
    # bottom: 0px;
    width: 100px;
    height: 100px;
}

To concatenate two or more string values in CSS, separate them with whitespace:
.tooltip:hover:after
{
    content: attr(class) ' ' attr(data-size);
}

Note that the whitespace between the attr() functions and the quotes is not the same as the whitespace within the quotes. The latter is an actual string containing a space character, which will separate the two attribute values in the output. The whitespace between the three parts is the operator that joins them together.
Unfortunately, most browsers do not support using :after or :before on img tags, so you need to change your img to a div with background-image:

Another unfortunate circumstance is, that you can't copy from pseudo-elements...
So, if you want to do it in JavaScript, the mouse events are mouseover/mouseout or mouseenter/mouseleave. Something along the lines of:
function attachHoverHandler()
{
  var fragment = document.createDocumentFragment();
  var text = document.createTextNode('Before - ');
  var div = document.createElement("div")
  div.appendChild(text);

  fragment.appendChild(div);

  Array.prototype.forEach.call(document.getElementsByTagName('img'), function (img) {
      console.log("adding", img);
      // img.insertBefore(fragment.cloneNode(), img.parentElement.firstChild);
      img.addEventListener("mouseenter", function(event){
        /* here goes your code */
        img.parentElement.insertBefore(fragment.cloneNode(true), img);
        console.log("mouseenter", event);
      });

      img.addEventListener("mouseleave", function(event){
        /* here goes your code */
        img.parentElement.removeChild(img.previousSibling);
        console.log("mouseleave", event);
      });
  });
}

function autorun()
{
  console.clear();
  attachHoverHandler();
}

   // event listener
   if (document.addEventListener) document.addEventListener("DOMContentLoaded", autorun, false);
   else if (document.attachEvent) document.attachEvent("onreadystatechange", autorun);
   else window.onload = autorun;


text:
Q: Live bootable pen drive with both Windows and Ubuntu I use both Macs and PCs. I have a pen drive that is in exFAT format and it is 64GB.I am planning on making a bootable live Ubuntu pen drive.Will I be able to boot into Ubuntu in both of the Windows PC and Mac with the same pen drive?(Please note that I can currently use the pen drive in both OSes as it is in exFAT format, that is if it has anything to do with it)

A: You should be able to. But there are two important factors.
a. You have to make sure that your Windows computer is running Windows 8 or higher. If you are using Windows 7, you can't have a bootable USB that also boots on Mac. (Mac and versions of Windows higher that 8 use UEFI, whilst Windows 7 and lower use BIOS)
b. Also you have to make sure that both computers can boot from a USB.


text:
Q: PDF scraping using textract module I have a Node.js app that have to do some web scraping of online pdf.
This is a piece of code:
var textract = require('textract');
const util = require('util');

var methods = {};

var urls = [
    {year: '2016', link: 'http://www.url2016.pdf'},
    {year: '2015', link: 'http://www.url2015.pdf'}
];
var result = [];

const textractFromUrl = util.promisify(textract.fromUrl);

methods.download = function(req, res) {
    return extractText();
}

async function extractText() {
    try {
        var config = {
            preserveLineBreaks: true
        };
        for(let url of urls) {
            let text = await textractFromUrl(url.link, config);
            switch(url.year) {
                case '2015':
                    await extractTextType1(url, text);
                    break;

                case '2016':
                    await extractTextType2(url, text);
                    break;

                default:
                    console.log('Error: no switch case');
            }
        }
    }
    catch(err) {
        console.log('catch block');
        console.log(err);
    }
}

As you can see, I use textrack package to scrape pdf.
When I run this app, I get:
catch block
{ Error: Error for type: [[ application/pdf ]], file: [[ C:\Users\myUserName\AppData\Local\Temp\96710848773.pdf ]], extractor for type exists, but failed to initialize. Message: INFO: 'pdftotext' does not appear to be installed, so textract will be unable to extract PDFs.
    at extract (C:\Users\myUserName\projectPath\node_modules\textract\lib\extract.js:147:15)
    at Timeout._onTimeout (C:\Users\myUserName\projectPath\node_modules\textract\lib\extract.js:155:7)
    at ontimeout (timers.js:466:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:267:5) typeNotFound: true }

In the npm textract module page, is written that PDF extraction requires pdftotext be installed, link.
So I go to http://www.foolabs.com/xpdf/download.html and I downloaded and istalled Download XpdfReader: Windows 64-bit.
I try again to run the app using node app.js (app.js is the main file of my app) but I get the same error so I download Download the Xpdf tools: Windows 64-bit.
It's a zip file, I extract that file and then I try to install pdftotext.exe but when I double click on pdftotext.exe, anything happens.
I also try to install that using Administrator privileges. Nothing.
I'm using Windows 10, 64 bit.
What I have to do?

EDIT 1
As recommended, I copied the pdftotext.exe file to C:\Windows\System32. Then I ran my program again and I have this problem:
catch block
TypeError: Cannot read property 'split' of undefined
    at extractTextType4 (C:\myUserName\projectPath\file.js:301:28)
    at extractText (C:\myUserName\projectPath\file.js:78:12)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:182:7)

Do I have to change the environment variables?

EDIT 2
My C:\myUserName\projectPath\file.js is this:
var textract = require('textract');
const util = require('util');
var utilFunc = require('../helpers/utilFunc.js'); // my lib
var postgreSQLlib = require('../middlewares/postgreSQLlib.js'); // my lib

// object of methods
var methods = {};

// object of pdf links
var urls = [
    {year: '2014', link: 'http://www.salute.gov.it/imgs/C_17_tavole_20_allegati_iitemAllegati_0_fileAllegati_itemFile_2_file.pdf'},
    {year: '2013', link: 'http://www.salute.gov.it/imgs/C_17_tavole_20_allegati_iitemAllegati_0_fileAllegati_itemFile_1_file.pdf'},
    {year: '2012', link: 'http://www.salute.gov.it/imgs/C_17_tavole_20_allegati_iitemAllegati_5_fileAllegati_itemFile_0_file.pdf'}
];
var result = [];

const textractFromUrl = util.promisify(textract.fromUrl);

/**
 * Do web scraping and save info on DB.
 */
methods.download = function(req, res) {
    return extractText();
}

/**
 * Switch between different type of pdf file.
 */
async function extractText() {
    try {
        var config = {
            preserveLineBreaks: true
        };
        for(let url of urls) {
            let text = await textractFromUrl(url.link, config);
            switch(url.year) {
                case '2012':
                    await extractTextType1(url, text);
                    break;

                case '2013':
                    await extractTextType2(url, text);
                    break;

                case '2014':
                    await extractTextType3(url, text);
                    break;

                default:
                    console.log('Error: no switch case');
            }
        }
    }
    catch(err) {
        console.log('catch block');
        console.log(err);
    }
}

/**
 * Save data on DB.
 */
function saveOnObject(vaccines, regions, map, url) {
    vaccines = map.shift(); // remove and return the first element
    regions = map.shift(); // remove and return the first element

    let promises = [];
    for(var i = 0; i <= 21; i++) {
        var line = map[i];
        line.forEach(async function(value, index) {

            // make the values uniform
            var vac = utilFunc.makeUniform(vaccines[index], 'vaccine');
            var reg = utilFunc.makeUniform(regions[i], 'region');
            var perc = utilFunc.makeUniform(value, 'value');

            // create json object
            var obj = utilFunc.createJsonObjectCov(parseFloat(url.year), 'Italy', vac, reg, perc);
            covDataItAll.push(obj);
        });
    }
    return Promise.all(promises);
}

/**
 * Extract text to pdf 2000-2012.
 */
function extractTextType1(url, text) {
    var matrix = [];
    var map = [];
    var vaccines = [];
    var regionsTemp = [];
    var regions = [];
    var regionLength = [1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];

    // text to matrix
    var textArray = text.split('\n');
    for(var i = 0; i < 23; i++) {
        matrix[i] = textArray[i].split(' ');
    }

    // create vaccines array
    matrix[0].shift();
    vaccines = matrix[0];
    map[0] = vaccines;

    // create regionsTemp and values arrays
    for(var i = 0; i < regionLength.length; i++) { // i index for regionLength
        var j = i + 1; // index for matrix
        var indexToRemove = 0;
        var numberToRemove = regionLength[i];
        var region = matrix[j].splice(indexToRemove, numberToRemove);
        regionsTemp.push(region);
        map[j+1] = matrix[j];
    }

    // create regions array (merge some elements)
    for(var i = 0; i < regionsTemp.length; i++) {
        var region = '';
        if(regionLength[i] > 1) {
            region = regionsTemp[i].join(' ');
        }
        else {
            region = regionsTemp[i].join('');
        }
        regions.push(region);
    }
    map[1] = regions;

    // remove \r char from map
    for(var i = 0; i < map.length; i++) {
        for(var j = 0; j < map[i].length; j++) {
            map[i][j] = map[i][j].replace(/\r/g, '');
        }
    }

    return saveOnObject(vaccines, regions, map, url);
}

/**
 * Extract text to pdf 2013.
 */
function extractTextType2(url, text) {
    var matrix = [];
    var map = [];
    var vaccines = [];
    var regions = [];

    // text to matrix
    var textArray = text.split('\n');
    for(var i = 0; i < 36; i++) {
        matrix[i] = textArray[i].split(' ');
    }

    // create vaccines array
    vaccines.push(matrix[0][1].replace(/\(a\)/g, '').replace(/\(b\)/g, '').replace(/\(c\)/g, '').replace(/\r/g, ''));
    for(var i = 1; i < 10; i++) {
        vaccines.push(matrix[i][0].replace(/\(a\)/g, '').replace(/\(b\)/g, '').replace(/\(c\)/g, '').replace(/\r/g, ''));
    }
    var meningo = ''.concat(matrix[10][0], matrix[11]).replace(/\(a\)/g, '').replace(/\(b\)/g, '').replace(/\(c\)/g, '').replace(/\r/g, '');
    vaccines.push(meningo);
    var pneumo = ''.concat(matrix[12][0], ' ', matrix[13]).replace(/\(a\)/g, '').replace(/\(b\)/g, '').replace(/\(c\)/g, '').replace(/\r/g, '');
    vaccines.push(pneumo);
    map[0] = vaccines;

    // create regions array
    for(var i = 14; i < matrix.length; i++) {
        regions.push(matrix[i][0]);
    }
    map[1] = regions;

    // create values array
    for(var i = 14; i < matrix.length; i++) {
        matrix[i].shift();
        map.push(matrix[i]);
    }

    // remove \r char from map
    for(var i = 0; i < map.length; i++) {
        for(var j = 0; j < map[i].length; j++) {
            map[i][j] = map[i][j].replace(/\r/g, '');
        }
    }

    return saveOnObject(vaccines, regions, map, url);
}

/**
 * Extract text to pdf 2014.
 */
function extractTextType3(url, text) {
    var matrix = [];
    var map = [];
    var vaccines = [];
    var regionsTemp = [];
    var regions = [];
    var regionLength = [1, 2, 1, 3, 3, 1, 3, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]; // array that contains the length of the regions (I need to correctly split the arrays)

    // text to matrix
    var textArray = text.split('\n');

    for(var i = 0; i < 36; i++) {
        matrix[i] = textArray[i].split(' ');
    }

    // create vaccines array
    vaccines.push(matrix[0][2].replace(/\(a\)/g, '').replace(/\(b\)/g, '').replace(/\(c\)/g, '').replace(/\r/g, ''));
    for(var i = 1; i < 10; i++) {
        vaccines.push(matrix[i][0].replace(/\(a\)/g, '').replace(/\(b\)/g, '').replace(/\(c\)/g, '').replace(/\r/g, ''));
    }
    var meningo = ''.concat(matrix[10][0], ' ', matrix[10][1], ' ', matrix[11]).replace(/\(a\)/g, '').replace(/\(b\)/g, '').replace(/\(c\)/g, '').replace(/\r/g, '');
    vaccines.push(meningo);
    var pneumo = ''.concat(matrix[12][0], ' ', matrix[13]).replace(/\(a\)/g, '').replace(/\(b\)/g, '').replace(/\(c\)/g, '').replace(/\r/g, '');
    vaccines.push(pneumo);
    map[0] = vaccines;

    // create regionsTemp and values arrays
    for(var i = 0; i < regionLength.length; i++) { // i index for regionLength
        var j = i + 14; // index for matrix
        var indexToRemove = 0;
        var numberToRemove = regionLength[i];
        var region = matrix[j].splice(indexToRemove, numberToRemove);
        regionsTemp.push(region);
        map[i+2] = matrix[j];
    }

    // create regions array (merge some elements)
    for(var i = 0; i < regionsTemp.length; i++) {
        var region = '';
        if(regionLength[i] > 1) {
            region = regionsTemp[i].join(' ');
        }
        else {
            region = regionsTemp[i].join('');
        }
        regions.push(region);
    }
    map[1] = regions;

    // remove \r char from map
    for(var i = 0; i < map.length; i++) {
        for(var j = 0; j < map[i].length; j++) {
            map[i][j] = map[i][j].replace(/\r/g, '');
        }
    }

    return saveOnObject(vaccines, regions, map, url);
}

// exports methods
module.exports = methods;

A: Copy the the file to pdftotext.exe to either c:\windows or c:\windows\system32.
Basically any folder which is added to your PATH. Then it should work
You can see in the source code
https://github.com/dbashford/textract/blob/078b3654b2f4e4f11a179714bd827a556fc1f64f/lib/extractors/pdf.js#L24
The code assumes pdftotext to be in path


text:
Q: Zend Framework 2 - Multiple sub domains cause problems I am writing an application in Zend Framework 2 which is going to run from a few different subdomain, and I want to have a different module for each sub domain, to keep things tidy.
My problem is when I add more than 1 sub domain to the routing, it loses one of the sub domains.
eg: This setup works
testbed.localhost (module/Application)
a.testbed.localhost (module/A)
If I add an extra one it will the route all requests for a to the Application Index Controller
eg
testbed.localhost (module/Application), a.testbed.localhost (module/A), b.testbed.localhost (module/B)
This is the module.config.php for module/A
    'router' => array(
    'routes' => array(
        'ads' => array(
            'type'    => 'Hostname',
            'options' => array(
                 'route'    => 'a.testbed.localhost',
                'constraints' => array(
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id'     => '[0-9]+',
                ),
                'defaults' => array(
                    '__NAMESPACE__' => 'A\Controller',
                    'controller' => 'A\Controller\A',
                    'action'     => 'index',
                ),
            ),

And this is the route in module.config.php in module/B
    'router' => array(
    'routes' => array(
        'ads' => array(
            'type'    => 'Hostname',
            'options' => array(
                 'route'    => 'b.testbed.localhost',
                'constraints' => array(
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id'     => '[0-9]+',
                ),
                'defaults' => array(
                    '__NAMESPACE__' => 'B\Controller',
                    'controller' => 'B\Controller\B',
                    'action'     => 'index',
                ),
            ),

Now the namespaces are correct in both the module.config.php files, what I have noticed is the sub domain a.testbed.localhost will work if I remove the reference to it from config/application.config.php
    <?php
    return array(
        'modules' => array(
         'Application',
         'A',
         'B', <--- A doesn't work if B is here
      ),

And if I swap A & B around in the modules array above, then B will get forwarded to the Application Module and A will work. So it seems to have problems with more than 1 sub domain. Has anyone got any ideas / come across the same thing?

A: This happens because your route names are the same. I would try a-ads and b-ads for route names and that should resolve your situation.
In the end the configuration is getting merged together. So it's like an array, when the last array is merged it overwrites anything before it.


text:
Q: How to create a scheduler task in Window Task Scheduler using Java? I want to create a task under Window Task Scheduler using my java code.
OS I am using is win7 64bit.
After creating the task I have to edit the scheduled time weekly or biweekly.
Is there any window scheduler API to use in java code or command to use under command prompt?

A: Launch the command line utility schtasks.
To create the task.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TestWinScheduler {

public static void main(String args[]) throws IOException, InterruptedException {
  // schtasks /create /tn "HowToTask" /tr c:\temp\test.cmd /sc once /st 00:00:00 /sd 2022/01/01 /ru username /rp password

  List<String> commands = new ArrayList<String>();

  commands.add("schtasks.exe");
  commands.add("/CREATE");
  commands.add("/TN");
  commands.add("\"HowToTask\"");
  commands.add("/TR");
  commands.add("\"c:/temp/test.cmd\"");
  commands.add("/SC");
  commands.add("once");
  commands.add("/ST");
  commands.add("00:00:00");
  commands.add("/SD");
  commands.add("2022/10/10");
  commands.add("/RU");
  commands.add("username");
  commands.add("/RP");
  commands.add("password");

  ProcessBuilder builder = new ProcessBuilder(commands);
  Process p = builder.start();
  p.waitFor();
  System.out.println(p.exitValue()); // 0 : OK
                                     // 1 : Error
  }
}

To execute a task :
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TestWinScheduler {

public static void main(String args[]) throws IOException, InterruptedException {
  // schtasks /run /tn "HowToTask"

  List<String> commands = new ArrayList<String>();

  commands.add("schtasks.exe");
  commands.add("/RUN");
  commands.add("/TN");
  commands.add("\"HowtoTask\"");

  ProcessBuilder builder = new ProcessBuilder(commands);
  Process p = builder.start();
  p.waitFor();
  System.out.println(p.exitValue()); // 0 : OK
                                     // 1 : Error
  }
}

Ref

A: Windows have already a task scheduler that you can invoke from command line: Schtasks.exe
SCHTASKS /parameter [arguments]
Description:
    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system.
Parameter List:
/Create         Creates a new scheduled task.
/Delete         Deletes the scheduled task(s).
/Query          Displays all scheduled tasks.
/Change         Changes the properties of scheduled task.
/Run            Runs the scheduled task on demand.
/End            Stops the currently running scheduled task.
/ShowSid        Shows the security identifier corresponding to a scheduled t
ask name.
/?              Displays this help message.

A: Try this one http://yajsw.sourceforge.net/. Using "YAJSW" (Yet Another Java Service Wrapper) you can register your java service as a windows service.


text:
Q: Creating an efficient tiled background in sprite kit What I have created in my SpriteKit project is a large two-dimensionally tiled background made up of about 160 sprite nodes. But to me, this seems extremely inefficient.
Would putting these nodes under a single parent make them more efficient? I would assume not and in that case is their a way to combine the textures themselves into a single node at run time?
I would simply use an image editor to tile these images but the size of said background will change between devices, and due to other factors within my project.

A: What you can do, in your loading phase,  create the 160 sprite nodes needed to make your background under 1 parent node, then call let texture = scene.view.textureFromNode(parentNode), and use this texture for your BG sprite.  When the loading phase ends,  the 160 sprites should get destroyed


text:
Q: Euler's totient function maximum value for a range For the euler's totient function, we have a number $n<10^{18}$
we have to find the value of $i$ between $2$ and $n$ (both inclusive) such that the value of $\phi(i)/i$ is maximum.
I have have observed that this value will be equal to the largest prime number less than or equal to n. Now since $n$ is upto $10^{18}$, what will be the most efficient way to do this?

A: Hint:
$\phi(p)=p-1$, so now you have to look for largest prime before $10^{18}$


text:
Q: Header/footer unable to overwrite when plotting I created a excel vba script, mostly by using the record button and manually adding the preset headers and footers.
The problem that's occuring is that it seems to be unable to overwrite existing headers and footers. The code works fine if the header/footers are manually deleted at first before plotting using the macro (included below) little bit anoying and have not really got a clue how to solve it, are there any functions available to just delete all the existing printsettings before executing this script?
Application.PrintCommunication = False
    Application.Dialogs(xlDialogPrinterSetup).Show
    With ActiveSheet.PageSetup
        ActiveWindow.View = xlPageBreakPreview
    ActiveSheet.PageSetup.PrintArea = "$A:$N"
        .PrintTitleRows = "$1:$1"
        .PrintTitleColumns = ""
    End With

    Application.PrintCommunication = True
    ActiveSheet.PageSetup.PrintArea = ""
    Application.PrintCommunication = False
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = "Project X"
        .RightHeader = ""
        .LeftFooter = Sheets("instellingen").Cells(20, 2).Value
        .CenterFooter = ActiveSheet.Name & Chr(10) & Format(Sheets("instellingen").Cells(22, 2).Value, "dd-MM-yyyy")
        .RightFooter = "Pagina &P van de &N"
        .LeftMargin = Application.InchesToPoints(0.7)
        .RightMargin = Application.InchesToPoints(0.7)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .HeaderMargin = Application.InchesToPoints(0.3)
        .FooterMargin = Application.InchesToPoints(0.3)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 600
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperA4
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = False
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = True
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
    Application.PrintCommunication = True
    ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
        IgnorePrintAreas:=False
End Sub

A: Solved by changing both lines containing
Application.PrintCommunication = False

to
Application.PrintCommunication = True

Source:
Excel headers/footers won't change via VBA unless blank


text:
Q: Trouble using ant length condition on a string I'm trying to deal with a string that has a long error message instead of a short value when something goes wrong. My ant script contains the following code:

<!-- build.svnversion is invalid if it's longer than 15 characters -->
<length property="build.svnversion.length" string="${build.svnversion}" />
<echo message="build.svnversion.length: ${build.svnversion.length}"/>

<condition property="build.svnversion" value="N/A" else="${build.svnversion}">
    <length string="${build.svnversion}" when="gt" length="15" />
</condition>
<echo message="build.svnversion: ${build.svnversion}" />

This produces the following output:
[echo] build.svnversion.length: 148
[echo] build.svnversion: svn: The path '.' appears to be part of a Subversion 1.7 or greater
[echo] working copy.  Please upgrade your Subversion client to use this
[echo] working copy.

Why isn't build.svnversion getting set to N/A since its length is clearly greater than 15?

A: Are you attempting to reset the property build.svnversion?
Once a property is set, it cannot be unset or changed1.
In your <condition/> task, you'll have to use another property name.
<!-- build.svnversion is invalid if it's longer than 15 characters -->
<length property="build.svnversion.length"
    string="${build.svnversion}" />

<echo message="build.svnversion.length: ${build.svnversion.length}"/>

<condition property="real.build.svnversion"
    value="N/A"
    else="${build.svnversion}">
    <length string="${real.build.svnversion}"
        when="gt" length="15" />
</condition>
<echo message="real.build.svnversion: ${real.build.svnversion}" />

1.. You can use Ant-Contrib's <var/> task to change a property's value or to completely unset it, but that's considered bad form.


text: Q: Missing list of Algorithm in the content The command in my tex \listofalgorithms is detected as unrecognized command. In the generated pdf file. The page of Algorithm is presented, while in the content, this page is skipped. So what can I do to make the list of algorithme appear in the content list. Thank you.


text:
Q: Linking to online help for my web app I am using Electron for my web app but I want to create online documentation for the app rather than embedding the documentation within the app. The issue I have to deal with is the app's version number. As I release minor or major upgrades to the app, the documentation needs to reflect those changes. However, the person who is using app version 2.0 would see documentation that contains all the 1.0 stuff plus anything new that has been added in 2.0.
There are a number of ways of dealing with this. I could just have a link in the app to a url where each url is specific to a version. The downside to this is that I have to copy all the documentation from the 1.0 page to the 2.0 page and maintaining that could be a hassle.
Another approach is to just use one url but pass the version number in a query string and then hide/show those parts of the documentation that are relevant to their version.
If you've had to deal with this issue, what approach have you taken?


text:
Q: Laravel transactions don't rollback on exception in MySQL with InnoDB engine I have this transaction, and all my MySQL tables are using InnoDB engine:
\DB::beginTransaction();
try{
    User::create([
        'name' => 'test',
        'status' => 1
    ]);
    array_push($test_array, ['test']);
    \DB::commit();

} catch(\Exception $e){
    \DB::rollBack();
}

If I dump() the exception, it says:

array_push() expects parameter 1 to be array, null given

because $test_array is null. However, the transaction doesn't rollback, and the user is still created. I don't know what I'm doing wrong.
I get the same result while doing this too :
\DB::transaction(function () {

    User::create([
        'name' => 'test',
        'status' => 1
    ]);
    array_push($test_array, ['test']);
});


text:
Q: How can I use group, inner join and sum? I have two Tables: Products & Sales.
Products
id- productname  -  grp

11    bmwblue       bmw
12    bmwwhite      bmw
13    audiblack     audi
14    audiwhite     audi

Sales
 id   productid  amount

 1      11        2
 2      12        1
 x      13        5
 x      14        3

How can I show;
audi 8, bmw 3 ?

A: SELECT grp,
       sum(amount) AS total_grp_amount
FROM products AS p
JOIN sales AS s ON p.id = s.product_id
GROUP BY grp

I guess you are looking for this.


text:
Q: groovy - duplicate name for field and property I am trying to understand the below point in the codehaus page under 'Properties and field rules' section.

*

*You can declare a property and a field of the same name, the property will use that field then.

Does that mean we could have two variables one private and other public and the private uses the public field? Please see below sample program I tried for my understanding.
class Car {
    private def brake
    def brake // when does this get used? if I declare public, it gives compilation error

    protected void setBrake() {
        this.brake = brake
    }

    static def main(args) {
        Car c = new Car()
        c.setBrake 'abc'
        println c.brake
    }
}

A: This is what it means.
class Car {
    private def brake

    // Same name property will add getter/setter for the above field
    def brake

    static def main(args) {
        Car c = new Car()
        c.setBrake 'abc' // Use setter
        println c.getBrake() // Use getter
    }
}

Try above sample commenting out the property, you should see groovy.lang.MissingMethodException for setBrake(), because it gets added by the property.
The verbiage in the page says that if you have a field (may be private) and a property ( def brake) then the property will add the accessor methods for that field instead of creating a new private field.


text:
Q: In Nest 1.7.1 Delete or DeleteByQuery nothing works In Nest 1.7.1 Delete or DeleteByQuery nothing works for me.
I am trying to delete below documents:
Article article1 = new Article()
            {
                Id = 1111,
                Title = "Title - Test Elastic Search",
                Summary = "Summary - Test Elastic Search",
                Body = "Body - Test Elastic Search",
                ArticleDate = _dateToday,
                Author = new Author() { Id = 100, Name = "Mikey" },
            };

Article article2 = new Article()
            {
                Id = 2222,
                Title = "Title - Test Elastic Search",
                Summary = "Summary - Test Elastic Search",
                Body = "Body - Test Elastic Search",
                ArticleDate = _dateToday,
                Author = new Author() { Id = 100, Name = "Mikey" },
                Published = true
            };

I was expecting below queries would delete single document and all documents in an index but no query is deleting.
_elasticClient.Delete(article).Found;
_elasticClient.DeleteByQuery<Article>(q => q.Query(t => t.Term(m => m.OnField(f => f.Id).Value(articleId))))
                                      .Found;

_elasticClient.DeleteByQuery<Article>(q => q.MatchAll()).IsValid;

Please correct me if i am doing anything wrong.

A: Here's a working example
void Main()
{
    var settings = new ConnectionSettings(new Uri("http://localhost:9200"), "articles");
    var client = new ElasticClient(settings);

    if (client.IndexExists("articles").Exists)
    {
        client.DeleteIndex("articles");
    }

    client.CreateIndex("articles", c => c
        .AddMapping<Article>(m => m
            .MapFromAttributes()
        )
    );

    var today = DateTime.Now.Date;

    var article1 = CreateArticle(1111, today);
    var article2 = CreateArticle(2222, today);
    var article3 = CreateArticle(3333, today);
    var article4 = CreateArticle(4444, today);

    var bulkRequest = new BulkDescriptor();
    bulkRequest.Index<Article>(i => i.Document(article1));
    bulkRequest.Index<Article>(i => i.Document(article2));
    bulkRequest.Index<Article>(i => i.Document(article3));
    bulkRequest.Index<Article>(i => i.Document(article4));
    bulkRequest.Refresh();

    client.Bulk(bulkRequest);

    var searchResponse = client.Search<Article>(q => q.MatchAll());

    Console.WriteLine("Documents from search: {0}. Expect 4", searchResponse.Documents.Count());

    client.Delete(article1, d => d.Refresh());

    searchResponse = client.Search<Article>(q => q.MatchAll());
    Console.WriteLine("Documents from search {0}. Expect 3", searchResponse.Documents.Count());

    client.Delete(article2, d => d.Refresh());

    searchResponse = client.Search<Article>(q => q.MatchAll());
    Console.WriteLine("Documents from search {0}. Expect 2", searchResponse.Documents.Count());

    client.DeleteByQuery<Article>(q => q.MatchAll());

    searchResponse = client.Search<Article>(q => q.MatchAll());
    Console.WriteLine("Documents from search {0}. Expect 0", searchResponse.Documents.Count());

}

private Article CreateArticle(int id, DateTime articleDate)
{
    return  new Article()
    {
        Id = id,
        Title = "Title - Test Elastic Search",
        Summary = "Summary - Test Elastic Search",
        Body = "Body - Test Elastic Search",
        ArticleDate = articleDate,
        Author = new Author() { Id = 100, Name = "Mikey" },
        Published = true
    };
}

public class Article
{
    public int Id { get; set;}
    public string Title{ get; set;}
    public string Summary { get; set;}
    public string Body { get; set;}
    public DateTime ArticleDate { get; set; }
    public Author Author { get; set; }
    public bool Published { get; set;}
}

public class Author
{
    public int Id { get; set; }
    public string Name { get; set;}
}

results in
Documents from search: 4. Expect 4
Documents from search 3. Expect 3
Documents from search 2. Expect 2
Documents from search 0. Expect 0

as expected.
Something to bear in mind is that Elasticsearch is eventually consistent meaning that a document that is indexed does not appear in search results until after a refresh interval (by default, 1 second); Likewise, with a delete query, a document marked for deletion will appear in search results until the refresh interval has elapsed.
A GET request on a given document with a given id will however return the document before the refresh interval.
If you need documents to be searchable (or to not show in search results after deletion), you can refresh the index after an operation as I did with the bulk and delete calls above, using .Refresh(). You might be tempted to call refresh after every operation, however I would recommend using it only when you really need to as it adds overhead to the cluster and called all the time would likely degrade performance.

A: I got it working finally.
The delete request which is sent via NEST in fiddler is DELETE /articlestest/article/_query and the query which worked in plugin is this DELETE /articlestest/articles/_query ( the document type name was misspelled in the code).That's the reason ,query was not deleting the documents via NEST.And the bad thing is ,it doesn't even complain about the non-existent document type :( It took me a while to found that issue.


text:
Q: Read N lines until EOF in Python 3 Hi tried several solutions found on SO but I am missing some info.
I want to read 4 lines at once until I hit EOF. I know how to do it in other languages, but what is the best approach in Python 3?
This is what I have, lines is always the first 4 lines and the code stops afterwards (I know, because the comprehension only gives me the first 4 elements of all_lines. I could use some kind of counter and break and so on, but that seems rather cheap to me.
if os.path.isfile(myfile):
    with open(myfile, 'r') as fo:
        all_lines = fo.readlines()
        for lines in all_lines[:4]:
            print(lines)

I want to handle 4 lines at once until I hit EOF. The file I am working with is rather short, maybe about 100 lines MAX

A: If you want to iterate the lines in chunks of 4, you can do something like this:
if os.path.isfile(myfile):
    with open(myfile, 'r') as fo:
        all_lines = fo.readlines()
        for i in range(0, len(all_lines), 4):
            print(all_lines[i:i+4])

A: Instead of reading in the whole file and then looping over the lines four at a time, you can simply read them in four at a time. Consider
def fun(myfile):
    if not os.path.isfile(myfile):
        return
    with open(myfile, 'r') as fo:
        while True:
            for line in (fo.readline() for _ in range(4)):
                if not line:
                    return
                print(line)

Here, a generator expression is used to read four lines, which is embedded in an "infinite" loop, which stop when line is falsy (the empty str ''), which only happens when we have reached EOF.


text:
Q: How do I get the X and Y position of a div relative to the div it is appended to and not the viewport in JavaScript? I need to find the X and Y position of a div within another div, and not relative to the viewport like getboundingclient() returns. Is there a way to do this?
Position Relative to the Parent Div

A: Yes, it's just a matter of math.
When you have X and Y from both elements, your element you want to know the coordinates for and its wrapping container, then you only have to subtract the element - container coordinates.
Note: This also works if the element is not an immediate children of the container.
See the example below, where blue is the wrapping container and red is the element you want to know the coordinates from inside the blue container.

const container = document.querySelector('.container');
const element = document.querySelector('.element');

// get the domrect for your targeted container
const containerDomrect = container.getBoundingClientRect();

// get the domrect for you relement you wanna have the x/y coordinates
const elementDomrect = element.getBoundingClientRect();

// then simply subtract the x/y values of the container from the element
const xCoord = elementDomrect.x - containerDomrect.x;
const yCoord = elementDomrect.y - containerDomrect.y;

console.log('X coordinate: ' + xCoord);
console.log('Y coordinate: ' + yCoord);
.container {
  width: 100px;
  height: 100px;
  position: relative;
  background: blue;
}

.element {
  width: 50px;
  height: 50px;
  position: absolute;
  right: 0;
  bottom: 0;
  background: red;
}


text:
Q: How to create a font file from a base64 encoded font string in java I have a base64 encoded font String
String font_data="font/truetype;charset=utf-8;base64,AAEAAAAMAIAAAwBAT1MvMmaobcEAAAFIAAAAVmNtYXCo5nJcAAACgAAAAVJnYXNw//8AAwAAKHQAAAAIZ2x5Zt1rdPEAAARIAAAULGhlYWTx2l1e   ...........  AFwAXQAAAAAAAf//AAI=";

Now I want to create a .ttf  font file using java;
How to do this?
Thanks in advance..

A: Just decode the base64 part and save it in a file (I'm assuming that part is really a True Type font).
If you're using Java 7:
String fontData = "font/truetype;charset=utf-8;base64,QUJDREU= ... ";

fontData = fontData.substring(fontData.indexOf("base64,") + 7);

File ttFile = new File("/path/to/your/file.ttf");
try (FileOutputStream output = new FileOutputStream(ttFile)) {
    byte[] binary = javax.xml.bind.DatatypeConverter.parseBase64Binary(fontData);
    output.write(binary);
} catch (IOException e) {
    e.printStackTrace();
}

If you're using Java 6:
String fontData = "font/truetype;charset=utf-8;base64,QUJDREU= ... ";

fontData = fontData.substring(fontData.indexOf("base64,") + 7);

File ttFile = new File("/path/to/your/file.ttf");
try {
    FileOutputStream output = null;
    try {
        output = new FileOutputStream(ttFile);
        byte[] binary = javax.xml.bind.DatatypeConverter.parseBase64Binary(fontData);
        output.write(binary);
    } finally {
        if(output != null) {
            output.close();
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

If you're using an older version, download and add to your classpath Apache Commons Codec, and try this:
String fontData = "font/truetype;charset=utf-8;base64,QUJDREU= ... ";

fontData = fontData.substring(fontData.indexOf("base64,") + 7);

File ttFile = new File("/path/to/your/file.ttf");
FileOutputStream output = null;
try {
    try {
        output = new FileOutputStream(ttFile);
        byte[] binary = new org.apache.commons.codec.binary.Base64().decode(fontData);
        output.write(binary);
    } finally {
        if(output != null) {
            output.close();
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}


text:
Q: SAXParseException creating an Enum in XSD I'm having trouble constructing my first XSD file. I'm trying to generate Java POJO's bases on my XSD with jaxb2-maven-plugin.
To start, I've followed the example that I've seen this tutorial
This is my xsd file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">

   <xs:element name = "Tshirt">
        <xs:complexType>
            <xs:sequence>
                <xs:element name = "Color" type = "clothesColorType" />
                <xs:element name = "Size" type = "clothesSizeType" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:simpleType name="clothesSizeType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="S" />
            <xs:enumeration value="M" />
            <xs:enumeration value="L" />
            <xs:enumeration value="XL" />
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="clothesColorType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="Black" />
            <xs:enumeration value="White" />
            <xs:enumeration value="Green" />
            <xs:enumeration value="Blue" />
        </xs:restriction>
    </xs:simpleType>
</xs:schema>

When my plugin try to parse the file, I get the error
org.xml.sax.SAXParseException; systemId: file:/ruta/src/main/resources/wsdl-definition/Assurance.xsd; lineNumber: 47; columnNumber: 72; src-resolve: No se puede resolver el nombre 'clothesColorType' para un componente 'type definition'.

I have been googling for hours but I have not found the response. Any Ideas?
Thank you in advance.

A: The schema is valid (Saxon accepts it, so it must be...)
The problem is therefore either with your schema processor, or with the way you are invoking it.
I note that your schema does not have 47 lines, therefore I suspect the file you are actually using differs from the one shown.


text:
Q: Memory allocated when accessing CoreData to-many relationship not released? I'm building a news app where you have a series of images representing the actual articles. When you tap one of them, it opens up the main article page, which has a scroll view on the bottom containing related articles.
I found a strange (possibly CoreData related) problem regarding said bottom scroller. When I open the article page, I fetch the related articles, allocate a series of articleViewControllers and add their views to the scroll view. When I switch from the article page, I remove all the views from the scroller and release the articleViewControllers. Upon using Instruments and a couple of heapshots (one before tapping an article and another when switching back to the main page), I found that a substantial amount of memory remains allocated (see images)

When viewing the non-object tab, I discover that most of the allocations happen at the following line of code, in the viewDidLoad method of the above mentioned articleViewController:
    NSSet *tempSet = [[NSSet alloc] initWithSet:tempArticle.thumb];
    //tempArticle.thumb is the actual problem here
    [tempSet release]

tempArticle is an instance of the Article class, a subclass of NSManagedObject.
If I comment out these two lines of code, everything works fine, so I'm guessing it's a consequence of faulty CoreData usage.
Any help is appreciated. Thanks!

A: Core Data handles its own memory management. It may keep objects in memory or purge them at its own whim.
It's recommended that you not store large BLOBs (such as images) in NSManagedObjects. Instead,  store the images to disk, with its filepath reference in an NSManagedObject.


text:
Q: Updating Inno Setup progress bar from Dephi DLL I need your help, please. I'm trying to call function from DLL written in Delphi 10 Seattle from Inno Setup (ANSI). But I do not understand what is the problem. If I make application in Delphi and call this function from DLL, it works perfectly! See code listing:
Delphi DLL:
function Process(Pb: TProgressBar): Integer; stdcall;
var
  I: integer;
begin
  for I := 0 to 1000 do
  begin
    Pb.Position := I;
    Pb.Update;
    Sleep(10);
  end;
end;

Exports
  Process;

Inno Setup (ANSI):
function Count(Progr: TNewProgressBar): integer; external 'Process@files:CallC.dll stdcall delayload';

procedure NewButton1Click(Sender: TObject);
begin
   Count(NewProgressBar1);
end;

After call I get Access Violation. But, comment in dpr file i read, ShareMem write first line, but zero effect.
Show me how to correctly update progress bar in Inno Setup from Delphi DLL, please.

A: You cannot call object methods this way. You may be lucky to get this working, if you use exactly the same version of Delphi as the one Inno Setup is built with, as your tests with Delphi application shows. But it is still wrong and unreliable, do not do it. As you use a different Delphi version, the layout of the progress bar class in memory is different, hence the "Access violation".

For this particular task, you can easily do with just a handle to the progress bar:
function Process(Handle: THandle): Integer;
var
 I: Integer;
begin
  SendMessage(Handle, PBM_SETRANGE, 0, 1000 shl 16);
  for I := 0 to 1000 do
  begin
    SendMessage(Handle, PBM_SETPOS, I, 0);
    UpdateWindow(Handle);
    Sleep(10);
  end;
end;

In Inno Setup, call the function like:
function Count(Handle: THandle): integer;
  external 'Process@files:CallC.dll stdcall delayload';

procedure NewButton1Click(Sender: TObject);
begin
  Count(NewProgressBar1.Handle);
end;

For more advanced tasks, you need to use a callback.
See

*

*Using callback to display filenames from external decompression dll (Inno Setup)

*Call C# DLL from Inno Setup with callback


text:
Q: NHibernate WHERE Subquery Equals/GreaterThan/LessThan I am wanting to know how to restrict the results in the outer query based on the value of a subquery in NHibernate.
The sql would look something like:
SELECT
    p.*
FROM
    ParentTable p
WHERE
    (SELECT COUNT(c.Id) FROM ChildTable c WHERE c.ParentId = p.Id) > n

I've got as far as:
Parent parentAlias = null;
Child childAlias = null;
var query = Session.QueryOver(() => parentAlias);
var subquery = Session.QueryOver(() => childAlias).Where(childAlias.Parent.Id == parentAlias.Id);
query.WithSubquery...

But can't seem to get much further - unless I'm missing something obvious?

A: I worked it out. Here is a pseudo example:
outerQuery.WithSubquery.WhereValue(int).Lt(subquery);

Will execute as in SQL as
SELECT
  *
FROM
  OuterTable
WHERE 1 < (SELECT COUNT(*) FROM InnerTable WHERE ...)

A: Parent parentAlias = null;
var subquery = QueryOver.Of<Child>().Where(child.Parent.Id == parentAlias.Id);
var query = session.QueryOver(() => parentAlias)
    .WithSubquery.WhereExists(subquery)
    .List();


text:
Q: How can I choose which GPU to use from grub using vgaswitcheroo? I have a notebook with switchable AMD/Intel Graphics. I use, successfully, vgaswitcheroo to choose the active GPU and disable the unused one by a script in rc.local.
However, I would like to be able to choose the active GPU at startup, ideally by a different grub entry for each GPU. Is there a way of doing this?


text:
Q: "Authorization code is already claimed" error I've previously has no issues with re-granting OAuth permissions as you didn't need to revoke access in order to re-grant access.
What could be causing "Authorization code is already claimed"?
I know this error sounds obvious but I can't find documentation on this error and I believe that this shouldn't occur unless the endpoint isn't generating a new Authorization code. I wonder if there needs to be certain amount of time that needs to pass before re-granting access can occur, though I've never ran into this issue when implementing Square Up into my project.

A: That message implies that the authorization code returned from the Authorize endpoint was already used by the ObtainToken endpoint. If you need a new authorization code, you'll need to have the merchant/customer go through the Authorization flow again so that a new authorization code is generated.
With that said, you mention "re-granting" access. To re-grant someone access (who already has access), you shouldn't need to go through the authorization flow (meaning you don't need to use an authorization code). You just need to go through the RenewToken endpoint which only requires your client_id and the access_token you want to renew. If they no longer have access (their access was revoked or expired), then you'll need to go through the entire Authorization flow again.

A: I had this same issue - In my code, I was checking the CURL_EXEC for errors, and then running CURL_EXEC again, thus causing the issue. I just eliminated the error check.
if(!curl_exec($curl)){
        return 'Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl);
}

$ch = curl_exec ($curl);


text:
Q: Basic JavaScript keeps returning false Hey so I'm creating a basic chrome plugin. I have done no java script until now and have only used java before. For some reason whenever I run this function it always returns false. I have added an alert in the if check and it appears.

function alarmExists() {
    var exists = false;

    chrome.alarms.getAll(function(alarms) {
            for(i = 0; i < alarms.length; i++) {
                if(alarms[i].name == "MyAlarm") {
                    alert("True");// This is called
                    exists = true;
                    break;
                }
            }
    });
    return exists;
}

A: chrome.alarms.getAll is an asynchronous function and takes a callback as an argument. It will execute the callback once it has finished executing which, in your case, happens after you return the value from alarmExists. You should include the logic inside the callback or use a pattern such as Promises.


text:
Q: How to split each item in an string-array xml list and add it to a new arraylist? My activity has a listview that prints out every item from the string array, but what I am trying to do is only show the first part of the string and the second part is needed for the next activity. When the activity loads it shows part1|part2. I can't get it working for the first load of the activity, but for the OnItemClickListener it works to split the string and send part2 to another activity.
<string-array name="test">
    <item>Dummy1|test1 test2 test3</item>
    <item>Dummy2|test4</item>
    <item>Dummy3|test5</item>
</string-array>

I am using a delimiter " | " to split the string.
String title, sub_category, part1, part2;
Bundle bundle;
String[] sub_category_list, seperated;
ListView listView;
Object sub_cat_name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.subcategory_layout);

    bundle = getIntent().getExtras();
    title = bundle.getString("selected_category");

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitleTextColor(Color.WHITE);
    getSupportActionBar().setTitle(title);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    sub_category_list = getResources().getStringArray(R.array.test);

    (Print out only the first part of each item.
    I need a function here that splits each strings)

    listView = (ListView) findViewById(R.id.sub_category_list);

    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.list_single, R.id.txt, sub_category_list);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            sub_cat_name = listView.getItemAtPosition(position);
            seperated = sub_cat_name.toString().split("\\|");
            part1 = seperated[0];
            part2 = seperated[1];
            sub_category = sub_cat_name.toString();

            Toast.makeText(SubCategory.this, "You clicked at : " + (part2) + (position), Toast.LENGTH_SHORT).show();
        }
    });
}

I have tried using a for loop to add all the first parts to a new ArrayList.
public ArrayList<String> newList;

    sub_category_list = getResources().getStringArray(R.array.popular);
    for (String i : sub_category_list){
        String[] split1 = i.split("\\|");
        String abc = split1[0];
        String def = split1[1];
        newList.add(abc);
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,  R.layout.list_single, R.id.txt, newList);
    listView.setAdapter(adapter);

A: Try something like this:
Map<String,String> partsMap = new HashMap<>();

private ArrayList<String> getFisrtPartString() {
    ArrayList<String> firstPartStringsList = new ArrayList<>();
    ArrayList<String> list = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.test)));

    String firstPart;
    String secondPart;

    for(String stringInStringArray : new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.test)))) {
        firstPart = stringInStringArray.split("|")[0];
        secondPart = stringInStringArray.split("|")[1];
        partsMap.put(firstPart, secondPart);
    }
    firstPartStringsList.addAll(partsMap.keySet());
    return firstPartStringsList;
}

It will initialize a map that get the first part of the String as key and the second part as value, and return a list (so you can use it for your ListView/RecyclerView adapter) of "first part of the strings".
Regarding the second phase, which needs the second part of the string, it's up to you to use the map's values (that contains at this stage the second part of the strings) and to deliver it to whoever need it.