text:
Q: How can i add item in redux with nested data structure like this? I am adding new items to choice array I want to push new items dynamically to choice array which is nested deeply so that then i can render react native TextInput component dynamically using the map function. Can anyone please help me out. Please find the datastructure and reducer design along with other code below.
Use case is like this:
UI:
 Question:     _________
 Choice:       _________    Add more choices
 Right Choice: _________    Dropdown which gets data from choice array

 Next                  Add New Question

On pressing add new question, new object from dynamicMCQGenerationDataFormat[0] is added and then using the map function i than render two questions each having question, choice, right choice properties. I hope this is enough for people to understand.
(On clicking add more choices will be rendered using map function. I have to not only push new items in choice array but later i have to even change the content inside them.)
I have a datastructure dynamicMCQGenerationDataFormat:
[
  {
    "question": "What",
    "choice": ["choice"],
    "rightChoice": ""
  }
]

Reducer:
import {
  EXAM_UPDATE,
  REFRESH_EXAM,
  INSERT_NEW_QUESTION,
  INSERT_NEW_CHOICE,
  UPDATE_QUESTION
} from '../actions/types';
import dynamicMCQGenerationDataFormat from '../assets/MCQGenerationFormat/dynamicMCQGeneration.json';

const INITIAL_STATE = {
  description: "",
  level: "",
  status: "",
  mcq: dynamicMCQGenerationDataFormat
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case EXAM_UPDATE:
      return { ...state, [action.payload.prop]: action.payload.value }
    case INSERT_NEW_QUESTION:
      console.log(action.payload);
      return { ...state, mcq: [ ...state.mcq, action.payload] }
    case UPDATE_QUESTION:
      return {
        ...state, mcq: state.mcq.map((mcq, i) => i === action.payload.idx ? {...mcq, question: action.payload.value} : mcq)
      }
    case INSERT_NEW_CHOICE:
      return { ...state, mcq: [...state.mcq, choice: [...state.mcq.choice]] }
    case REFRESH_EXAM:
      return { INITIAL_STATE }
    default:
      console.log('Enroll Guard Form Reducer');
      return state;
  }
};

ActionCreator:
import { Actions } from 'react-native-router-flux';
import {
  EXAM_UPDATE,
  EXAMS_FETCH_SUCCESS,
  INSERT_NEW_QUESTION,
  UPDATE_QUESTION,
  INSERT_NEW_CHOICE
} from './types';
import firebase from 'firebase';
import { Alert } from 'react-native';

export const examUpdate = ({ prop, value }) => {
  return {
    type: EXAM_UPDATE,
    payload: { prop, value }
  };
};

export const insertNewQuestion = (value) => {
  return {
    type: INSERT_NEW_QUESTION,
    payload: value
  };
};

export const insertNewChoice = (value) => {
  return {
    type: INSERT_NEW_CHOICE,
    payload: value
  };
};

export const questionUpdate = ({ idx, value }) => {
  return {
    type: UPDATE_QUESTION,
    payload: { idx, value }
  };
}

Calling the action creator from one of my react native component:
pushNewQuestion() {
    this.props.insertNewQuestion(dynamicMCQGenerationDataFormat[0]);
}

Here dynamicMCQGenerationDataFormat is again the same:
[
  {
    "question": "What",
    "choice": ["choice"],
    "rightChoice": ""
  }
]

A: Okay. I solved it. For those who face the same problem while updating something deeply nested and cannot denormalize data please refer this.
case INSERT_NEW_CHOICE:
  return {
    ...state, mcq: state.mcq.map((mcq, i) => i === action.payload.idx ? {...mcq, choice: [ ...mcq.choice, action.payload.value]} : mcq)
  }

case UPDATE_CHOICE:
  return {
    ...state, mcq: state.mcq.map((mcq, i) => i === action.payload.idx ? {...mcq, choice: [ ...mcq.choice.map((choice, i) => i === action.payload.sIdx ? action.payload.value : choice ) ] } : mcq)
  }


text:
Q: Criar auto complete em input? Quero fazer um efeito de autocomplete em um input, como um prompt, exemplo, tenho os seguintes comandos em um array php:
ADD
SUB
SHOW
MUL

Quero fazer com que ao ele começar digitar, por exemplo digitar "A", exibir uma espécie de placeholder completando o comando, assim: ADD, porém não adicionando o "DD" já no input, apenas como "placeholder", e se o usuário apertar a tecla TAB por exemplo aí sim ele adiciona o "DD" ao input.
A minha maior dificuldade está a fazer esse efeito de placeholder no input não tenho a minima ideia de como fazer. Creio que o resto eu consigo fazer soziho, mas o ponto de partida (efeito de autocomplete) não tenho ideia de como fazer, podem dar uma luz?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to automate github branch deployment using Jenkins In my org, currently we are deploying the branches manually.
the steps are

*

*tsh login "my auth details"

*tsh ssh myusername@server

*sudo su

*run_command

this gives me a list of options like, branch , env etc. then the deployments starts. I was told this can be automated using jenkins. But I am not sure how and where to start.
Can anybody help in pointing out the resources from where I can learn about this and implement ?


text:
Q: Configure Multiple Static IPs through NAT on OpenWRT with Nginx Aplogies if this has been asked before, I did a thourough search and didn't find anything quite like it, so I'm hoping someone can either point me in the right direction or lend a hand with the configuration. Here's what I'm working with:
I have 5 static IPs from ISP, coming in to my own router running OpenWRT(its an R6300v2), and I need the router to not only run Nginx, but NAT those 5 IPs via a single trunk line to a Cisco 2690G L2/L3 switch, which then branches out to about two dozen VMs running on four physical hosts.
Now, before getting too crazy technical, I guess my first question is thus: am I better off using a VM to run as firewall/router/nginx server instead of the router? I do have another physical host sitting in standyby if thats the way I should go.
Otherwise, my second question is: how do I combine the nginx and NAT routing so that the traffic comes in on a single WAN port, and out to the switch on a single LAN port? I have a grasp of the basics, and can get things running individually, VLANs, NAT, trunking(somewhat), but the Nginx and combining everything into one config is throwing me for loops.
Again, my apologies if this has been asked/done before, I may not have worded my search properly, and sincerest apologies if this is an entirely greenie question. However, any and all help that can or may be provided would be greatly appreciated.
If it helps, I am the sole tech working this network, I've been building it literally from the ground up, so I have unrestricted access to the machines, the physical plant, all the addressing information, literally everything, so if there are any changes that should be made, or any more info I should provide, please, let me know, I'm happy to oblige.
Thank you very, very much,
Tay


text:
Q: IBM Worklight 6.0.0.1 - Error during hourly process for push notifications We're getting an error in WebSphere's SystemOut log approximately every hour on our Worklight Server.
It seems to be trying to validate push notification configuration.  We currently have working notifications, using Apple push notifications only. Errors are:

com.notnoop.apns.internal.ApnsFeedbackConnection getInactiveDevices
  Failed to retreive invalid devices ava.lang.RuntimeException:
  javax.net.ssl.SSLHandshakeException

Our notifications are working, but, what is this hourly process? I don't see anything in the docs regarding a batch process that's run by Worklight Server.
Our setup: Worklight Server 6.0.0.20130909-1459, WAS 8.0.0.6, JDK 1.6.

A: Worklight uses notnoop open source library to push notification to APNS. This is a known harmless bug in notnoop.
https://github.com/notnoop/java-apns/issues/29

A: I believe this check is part of the way APNS's feedback service works.
From: Provider Communication with Apple Push Notification Service
Section: General Provider Requirements

Connect regularly with the feedback service and fetch the current list
  of those devices that have repeatedly reported failed-delivery
  attempts. Then stop sending notifications to the devices associated
  with those applications. See "The Feedback Service" for more
  information.

As for what it means, it looks to me like your exception quote is cut. Is that all of it?


text:
Q: ActionScript is like JavaScript? I have a book, Essential ActionScript 3 (O'Reilly), to learn about using that language. It mentions that ActionScript 3 is an implementation of ECMAScript, just like Javascript. I find this strange, because there are many differences. In Javascript, as far as I know, you cannot give variables a type (var marvin : Robot) or create "traditional" classes and interfaces. This is, however, possible in ActionScript.
What's up?

A: The current implementations of Javascript in browser follows Ecmascript 3 specification. Actionscript implements Ecmascript 3 but in addition, some of the elements in Ecmascript 4 draft specification (at that time). ES4 features Classes, classical inheritance, packages and other features you see in AS3.
ES4 is now abandoned but here is a link to the specs PDF.

A: ActionScript 1 (Flash Player 5 and 6) is very close to JavaScript.

A: Wikipedia's page about ECMAScript states (quoting) :

ECMAScript is a scripting language,
  standardized by Ecma International in
  the ECMA-262 specification and ISO/IEC
  16262. The language is widely used on the web, especially in the form of its
  three best-known dialects,
  JavaScript, ActionScript,
  and JScript.

So I'm guessing that those three languages sort-of are "children" of ECMAScript, and that each of those choose to implement (or not) some specific features -- while all keeping the same root.

The page about ActionScript kind of confirms that, stating (quoting, emphasis mine) :

ActionScript is a scripting language
  based on ECMAScript.

I suppose this "based on" is the important part.

Also, there might be a difference depending on the version of ECMAScript that is used, I'd say -- especially considering people are talking about ECMAScript 5, and that, for instance, Javascript is based on ECMAScript 3 :

As of 2009, the latest version of the
  language is JavaScript 1.8.1. It is a
  superset of ECMAScript (ECMA-262)
  Edition 3.

A: ECMAScript is just a standard for a scripting language. Javascript and Actionscript are both implementations of that standard. Each implementation may or may not strictly follow that standard, and both are free to add to and subtract from it.


text:
Q: Objective-C: Loading animation on UIWebView I'm trying to use UIImageView as an animation when my UIWebView is loading, and remove that view when it's finished loading. However, I'm unable to make it start/stop animating when webview starts and stops loading. Code snippets:
@synthesize webView; //UIWebView
@synthesize loadView; //UIImageView

- (void)viewDidLoad {
    // ...

    loadView = [[UIImageView alloc] initWithFrame:[self.view bounds]];
    [loadView setAnimationImages:[NSArray arrayWithObjects:
                                    [UIImage imageNamed:@"image1.png"],
                                    [UIImage imageNamed:@"image2.png"],
                                    [UIImage imageNamed:@"image3.png"],
                                    nil]];
    [loadView setTag:1];
    [loadView setAnimationDuration:1.0f];
    [loadView setAnimationRepeatCount:0];
    [self.view addSubview:loadView];

    [webView loadRequest:request]; //request is defined somewhere else
}

- (void)webViewDidStartLoad:(UIWebView *)curWebView {
    [loadView startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)curWebView {
    [loadView removeFromSuperview];
}

- (void)webView:(UIWebView *)curWebView didFailLoadWithError:(NSError *)error {
    [loadView stopAnimating];
    // ... Code to show reload button
}

If I call [loadView startAnimating] in viewDidLoad, it animates, but [loadView stopAnimating] in webView:didFailLoadWithError still wouldn't work. Otherwise, laodView only shows a blank white screen.

A: Try writing a local webpage with the spinner in it (animated gif?), loading that and setting it running, then while it's animating, load your remote page in the back.

A: Set the UIWebViewDelegate protocol in interface. Have you set delegate of UIWebView in XiB file.


text:
Q: Autofac - DataContext not being disposed at end of lifetime scope I have a command-line program which is importing data into my system. Because it's inserting data into many tables, I require change tracking. To try and prevent the job from slowing down over time, I have used Autofac (my dependency injection framework) to create an inner lifetime scope from which I resolve dependencies. At the end of each batch, I recreate the lifetime scope and get new instances of my dependencies. The problem is that when I do this, my DataContext which the UnitOfWork depends on is not being refreshed each time, leading to a situation where the job slows down and eventually terminates before completing.
I can see this when debugging by setting the 'Make Object ID' on my DbContext, e.g.

After each batch, the object ID remains $2, demonstrating that the DataContext instance is not getting a new instance. Why is it not getting a new instance?
My code looks something like this:
foreach (var batch in data.Batch(10))
{
    using (var scope = LifetimeScope.BeginLifetimeScope(b =>
    {
        b.RegisterType<UnitOfWork>.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
        b.RegisterType<MyService1>.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
        b.RegisterType<MyService2>.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
        b.RegisterGeneric(typeof(EntityBaseRepository<>)).As(typeof(IEntityBaseRepository<>)).InstancePerLifetimeScope();
    }))
    {
        UnitOfWork = scope.Resolve<IUnitOfWork>();
        MyService1 = scope.Resolve<IMyService1>();
        MyService2 = scope.Resolve<IMyService2>();
        Thing1Repository = scope.Resolve<IEntityBaseRepository<Thing1Repository>>();
        Thing2Repository = scope.Resolve<IEntityBaseRepository<Thing2Repository>>();

        foreach (var row in batch)
        {
            try
            {
                ParseRow(row);
            }
            catch (Exception e)
            {
                JobLogger.Error(e, "Failed to parse row. Exception: " + e.Message);
                throw;
            }

        }
    }
}

It was my understanding that when I get a new instance of my dependencies, the child dependencies will get new instances as well? Why is the original DataContext still hanging about?
My UnitOfWork looks like this:
public class UnitOfWork : Disposable, IUnitOfWork
{
    private readonly IDbFactory _dbFactory;
    private DataContext _dbContext;

    public UnitOfWork(IDbFactory dbFactory)
    {
        _dbFactory = dbFactory;
    }

    public DataContext DbContext => _dbContext ?? (_dbContext = _dbFactory.Initialise());

    public void Commit()
    {
        DbContext.Commit();
    }
}

My DbFactory is responsible for creating a new instance of my DataContext:
public class DbFactory : Disposable, IDbFactory
{
    DataContext _dbContext;

    public DbFactory()
    {
        _dbContext = new DataContext();
    }

    public DataContext Initialise()
    {
        return _dbContext ?? (_dbContext = new DataContext());
    }

    protected override void DisposeCore()
    {
        _dbContext?.Dispose();
    }
}

My services are registered by scanning the assembly when the program first starts by calling this method:
AutofacConfig.InitialiseJobRunner();

Inside this method, I register my types like this:
builder.RegisterType<DataContext>().AsSelf().InstancePerMatchingLifetimeScope(lifetimeScope);
builder.RegisterGenericInstance(typeof(EntityBaseRepository<>), typeof(IEntityBaseRepository<>), lifetimeScope);
builder.RegisterAssemblyInterfaces(Assembly.Load(Data), lifetimeScope);

RegisterAssemblyInterfaces is implemented as:
public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle>
        RegisterAssemblyInterfaces(this ContainerBuilder builder, Assembly assembly, object lifetimeScope)
{
    return builder.RegisterAssemblyTypes(assembly)
        .AsImplementedInterfaces()
        .InstancePerMatchingLifetimeScope(lifetimeScope);
}

A: As you register assembly interfaces like below
public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle>
    RegisterAssemblyInterfaces(this ContainerBuilder builder, Assembly assembly, object lifetimeScope)
{
    return builder.RegisterAssemblyTypes(assembly)
        .AsImplementedInterfaces()
        .InstancePerMatchingLifetimeScope(lifetimeScope);
}

my guess is that your DbFactory is also registered this way. In such case (according to: https://autofac.readthedocs.io/en/latest/lifetime/instance-scope.html#instance-per-matching-lifetime-scope ) you will get the same instance of your factory as your child scope is not named. Try to add
b.RegisterType<DbFactory>.AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();

in your loop or change DbFactory to always return new context in Initialise method instead returning the same if it's already instantiated.


text:
Q: API call handling in offline mode (React Native) Is there a way to handle an API call which was sent while being online but all of a sudden after that call is made you lost network and got in offline mode meaning that the request has been sent to the server but you won't be able to see the response due to being in offline mode.
Also, being in offline mode if I make an API call (putting it in offline queue) to update some field of a particular record and before getting back online some other user (in online mode) made an update call for that particular record then how can such a case in offline mode be handled which requires synchronization ?
Do libraries like redux-offline and react-native-offline handle such scenarios ?


text:
Q: Echoing a  and obtaining the id of it Currently, when displaying all posts made by users I do the following:
while($info=mysql_fetch_array($data)) {
echo "
";
   echo $info['subject'];
   echo $info['post-item'];
echo "
";

}

But, however, I now need to treat each element fetched as an actual post rather than just an outputted div for obtaining the post_id of each post to be able to actually enable a user to interact with different posts e.g. to 'like' a post.
I had tried hyperlinking the like  href to ?id=$thispost which worked for liking however had problems such as a user altering the url, or even if I would like to also add the commenting functionality, I would need a different method!

A: As for different tasks, you would pass different querystrings:
like this
comment
share this

In page.php, you would then...
if (isset($_GET['do'] && isset($_GET['id'])) {
    $do = $_GET['do'];
    $id = $_GET['id'];
} else exit("blabla");

switch ($do) {

    case 'like':
        // do sth
        break;

    case 'comment':
        // do sth
        break;

    // etc.

} // switch

Of course, passing the values by URL open the gate to manipulation.
So either store $do and $id in $_SESSION or in $_POST.
Example for $_POST:
$h = "";
while ($info = mysql_fetch_array($data)) {

    $h .=  '
';
    $h .= '<form method="post" action="page.php">';
    $h .= "{$info['subject']}
{$info['post-item']}";
    $h .= "<input type=\"hidden\" name=\"id\" value=\"{$info['id']}\" />';
    $h .= '<input type="submit" name="do" value="like" />';
    $h .= '</form>
';

}
echo $h;

Comments:
1. don't use mysql_*, but mysqli_* or PDO -> makes your code future-proof and more secure
2. this code creates a form around every post, with a hidden field containing the id (from db) of that post...
3. and a button that will send the id invisible for the user to page.php.
4. in page.php, you read $_POST, as in my above exaple with $_GET:
if (isset($_POST['id'])) {
    $do = $_POST['do'];
    $id = $_POST['id'];
} else exit("blabla");

// etc.


text:
Q: How can I improve academic English? I'm a PhD student in Mathematics. I love learning and studying mathematical things. Everytime I read interesting article about my PhD topic. Usually I write academic papers to send an indexed journal. But, I got so many regretful responses from the reviewers about writing mistakes. In this context, How can I write fluent academic paper? Is there any web site to help me about this topic?
Sorry my bad english.
Sincerely.

A: All professional academics get other people to read their papers for typos and silly mistakes before submitting them. I wouldn't even think about sending an academic paper to a journal, or submitting work at university before getting a friend or colleague of mine to proof-read it for typos such as spelling errors or grammatical slips. This is part of what doing work in academia involves. Get someone to read your paper before you submit it. Learn from their corrections. (Good luck!)


text:
Q: Apache Mod_Rewrite Htaccess for Dynamic URL I have this link
www.example.com/1/title
which goes to
www.example.com/post.php?author=1&title=title
because of this rule
RewriteRule ^post/([0-9]+)/([\w-_:]+)/?$ post.php?author=$1&title=$2 [L,QSA,NC]

Fine, but now how do make it such that if somebody types in www.example.com/post.php?author=1&title=title to redirect to www.example.com/1/title
I have spent literally hours online researching this but the information is vague (at least for me) and not working.
2 things stump me so far:

*

*Writing the pretty url into dynamic and then dynamic into pretty -
Doesn't that create a loop?

*I also wanted to go the route of a 301 redirect but I could not find
any workable code that take variables from the first link to put into
the redirect. In my head a 301 would be the right choice, but I see a
lot of people (examples) doing it through RewriteRule.

I understand that (groups) can later be accessed by using $1 and $2... but when trying the reverse I cannot make it work. Eg:
RewriteRule ^post.php?author=([0-9]+)&title=([\w-_:]+)$ post/$1/$2

But like I said nothing works. I've been beating my head on sites like http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html but I cannot fully understand (or apply) what I'm reading there. Can you please let me know what I'm doing wrong or how I should approach this problem?
Many thanks for any help you can give me

A: You need a new rule like this:
RewriteCond %{THE_REQUEST} \s/+post\.php\?author=([^&]*)&title=([^\s&]+) [NC]
RewriteRule ^ post/%1/%2? [R=302,L]

RewriteRule ^post/([0-9]+)/([\w-_:]+)/?$ post.php?author=$1&title=$2 [L,QSA,NC]


text:
Q: BLE Scan on android 8.0 I've developed an app that do ble scan for nearby devices (multiple kinds of beacons around).
I am scanning using the BluetoothLeScanner with CALLBACK_TYPE_ALL_MATCHES and an empty ScanFilter array (since I want to get callbacks for all nearby devices).
My app was working just fine on my OnePlus 5 device Android 7.x (and few other devices) - until I have upgraded to android 8.0 OTA on my device.
I am not sure if it is Android 8.0 issue or OnePlus Oxygen bug but I face to following situation:
Around me there are many kinds of beacons, some advertise standard ibeacon/eddystone packets and others advertise custom packets.
I receive callbacks (onScanResult) only for the standard ibeacon/eddystone packets and not for the custom ones.
Before upgrading I got the callbacks for all kind of packets - standard and non-standard.
Was something changed in the underline filter of received ble packets in android 8.0?
Is it a bug in latest Oxygen OS version?
Should I add some kind of flag to get non standard packets?
Any idea will be much appreciated.
Thanks.

A: After investigating the packets sent by each beacon, I have figured out that one of the custom beacons sent a packet with wrong data length byte.
That caused the packet to be filtered out by OS 8 (Android OR Oxygen) - did not matter to older versions.
Now i'll have to talk to the firmware company for a fix...


text:
Q: symfony2 utf8 issue with translation in the controller In my symfony 2 application, I am translating a string in a controller, from a yaml file, and sending it via ajax.
Then in my ajax function, I am parsing the response with JSON
The issue I have is the string that is being output by the translator is not in UTF8. Why? It is in the right format when I call the filter | trans in my templates.
Also, accentuated letters written in my controller are correctly sent in UTF8, it really seems to come from the translating component.
The workaround I found is to encode in UTF8 after it is translated in my controller, send it via ajax, then decode UTF8 in javascript. But it's not super clean plus I can get "this is not a URI" errors.
How can I have the translator output a UTF8 string in my controller ?
My yaml:
rights:
    is_boss: Tout éditer, voir, supprimer

My controller:
    $message= strtolower($translator->trans('rights.is_boss', array(), 'backend_pages'));

    $response = array(
        'message' => utf8_encode($message)
    );

    return new JsonResponse($this->get('serializer')->serialize($response, 'json'));

My view:
        $.ajax({
            type        : 'POST',
            url         : '{{ path('manage_rights', {'associate' : associate.id }) }}',
            data: {right: right, parameter: parameter, value: value},
            dataType: 'json'
        }).done(function(response){
            response = JSON.parse(response);
            var message = decodeURIComponent(escape(response.message));
            //do stuff
        })

The error I get if I don't encode in UTF 8 is the following:

Your data could not be encoded because it contains invalid UTF8
  characters. 500 Internal Server Error - RuntimeException
  in
  vendor\jms\serializer\src\JMS\Serializer\JsonSerializationVisitor.php
  at line 36   -

Precision:
//This does not output a proper UTF8 string. I get an error if I try to serialize it in JSON
$message= strtolower($translator->trans('rights.is_boss', array(), 'backend_pages'));

//In my twig, this does output a correct string with accentuated chars without weird symbols
<label>{{ ('rights.is_boss') | trans }}</label>


text:
Q: body and html not scaling outside of viewport when Zooming in Safari / Chrome We've coded a site, everything works great until you start using the zoom function of Safari/Chrome.
It seems some elements zoom correctly (see the search in attached screenshot) making a horizontal scrollbar, but html and head don't scale more than 100% of the viewport so when you scroll right making it look pretty bad…
I've tried width: 100% !important and many other things but nothing seems to affect it, any ideas would be most appreciated!

A: Fix seems to be putting a min-width on the body that's the same as the containers width, not ideal but seems to do the trick…!


text:
Q: List Every Network Printer With ListBox Powershell I'm new to Powershell and I would like to write a script to make it easier for end users to add a network printer to their system.
I want to list all the network printer in the listbox, but instead of listing all printer names, I get this:

Here's my code
#window
$window = New-Object System.Windows.Forms.Form
$window.Text = 'Select a Printer'
$window.Size = New-Object System.Drawing.Size(500, 400)
$window.StartPosition = 'CenterScreen'

#Button
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(340,130)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$window.AcceptButton = $okButton

 $cancelButton = New-Object System.Windows.Forms.Button
 $cancelButton.Location = New-Object System.Drawing.Point(340,240)
 $cancelButton.Size = New-Object System.Drawing.Size(75,23)
 $cancelButton.Text = 'Cancel'
 $cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
 $window.CancelButton = $cancelButton

 $label = New-Object System.Windows.Forms.Label
 $label.Location = New-Object System.Drawing.Point(10,20)
 $label.Size = New-Object System.Drawing.Size(280,20)
 $label.Text = 'Please select a printer'

 $listBox = New-Object System.Windows.Forms.ListBox
 $listBox.Location = New-Object System.Drawing.Point(10,60)
 $listBox.Size = New-Object System.Drawing.Size(260,20)
 $listBox.Height= 280

 $listBox.Items.Add((Get-Printer -ComputerName srvpr01| select $_.Name))

 $window.Controls.Add($listBox)
 $window.controls.Add($label)
 $window.Controls.Add($cancelButton)
 $window.Controls.Add($okButton)
 $result = $window.ShowDialog()

 if ($result -eq [System.Windows.Forms.DialogResult]::OK)
  {
     $x = $listBox.SelectedItem
     $x
  }

You know any way I can list the printer names instead of this Object?
I appreciate every type of help and feedback!

A: You need to use a loop to add the items to the listbox.
Change this line
$listBox.Items.Add((Get-Printer -ComputerName srvpr01| select $_.Name))

to this:
Get-Printer -ComputerName srvpr01 | ForEach-Object { $listBox.Items.Add($_.Name) }


text:
Q: When a page switches programmatically in Ionic Framework it breaks that page? In my Ionic Framework v3 app I a programmatically sending data to another page and when I try to get back to that page immediately it shows a broken version of the home page.
The page before switching:

After Switching (when I try to return to that page):

The done button is what switches the page with this code:
done() {
    this.navCtrl.push(HomePage, {
        drinkOption: drinkOption,
        drinkValue: amountOfDrink
    });

    this.navCtrl.parent.select(0);
}

Then the home page receives it with this code:
if (navParams.get('drinkOption') && navParams.get('drinkValue')) {
    this.drinkOption = navParams.get('drinkOption');
    this.amountOfDrink = navParams.get('drinkValue');

    saveDrink(this.drinkOption, this.amountOfDrink);
}

Ionic Info:
cli packages: (/Users/user/.config/yarn/global/node_modules)

@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : 8.0.0
Gulp CLI              : CLI version 3.9.1 Local version 3.9.1

local packages:

@ionic/app-scripts : 3.1.9
Cordova Platforms  : ios 4.5.4
Ionic Framework    : ionic-angular 3.9.1-201711081842

System:

ios-deploy : 1.9.2
ios-sim    : 6.1.2
Node       : v8.9.4
npm        : 5.6.0
OS         : macOS High Sierra
Xcode      : Xcode 9.3 Build version 9E145

Environment Variables:

ANDROID_HOME : not set

Misc:

backend : pro

Thanks in advance...


text:
Q: integrable function in Lebesgue sense How we prove that $\displaystyle{f : x \mapsto \frac{x}{e^{x}-1}}$
is Lebesgue integrable in $\mathbb{R}_{+}$?

A: Use Taylor series to see that $e^x-1 \geq x$ and $e^x-1 \geq x^3/6$, for $x \geq 0$. So
$$0 \leq \frac{x}{e^x-1} \leq \frac{x}{\max \{ x,x^3/6 \}} = \min \left \{ 1,\frac{6}{x^2} \right \}.$$
Can you work from here?
Another approach, which actually gives a way to calculate the integral:
$$\frac{x}{e^x-1}=\frac{x e^{-x}}{1-e^{-x}}=x e^{-x} \sum_{n=0}^\infty e^{-nx}.$$
Hence
$$\int_0^\infty \frac{x}{e^x-1} dx = \int_0^\infty x e^{-x} \sum_{n=0}^\infty e^{-nx} dx.$$
Then you can interchange summation and integration using monotone convergence. This leaves you to compute
$$\sum_{n=0}^\infty \int_0^\infty x e^{-(n+1)x} dx.$$
Using integration by parts, you get
$$\sum_{n=1}^\infty \frac{1}{n^2}.$$
One shows that this series converges in calc II; using Fourier series methods one can show that the value is $\frac{\pi^2}{6}$.

A: Here is another dominating function which does not use Taylor series. Consider $e^x/2$. At $x=\ln(2)$, $e^x/2=e^x-1$. This is the only point where these two functions are equal. At $x=\ln(4)$, $e^x/2<e^x-1$, so by continuity, we know that $e^x/2<e^x-1$ for all $x>ln(2)$. Thus, $$\int_{\ln(2)}^\infty\frac{x}{e^x-1}dx\leq\int_{\ln(2)}^\infty2xe^{-x}dx=1+\ln(2).$$
Now we just have to show that
$$\int_0^{\ln(2)}\frac{x}{e^x-1}dx<\infty.$$
We know that the integrand is continuous on $(0,\ln(2)]$. If we we can show
$$\lim_{x\to 0}\frac{x}{e^x-1}<\infty,$$
then the integrand is bounded on a set of finite measure. Calculating the limit is simple if we use L'Hopital's rule:
$$\lim_{x\to 0}\frac{x}{e^x-1}=\lim_{x\to 0}\frac{1}{e^x}=0.$$
Thus,
$$\int_0^{\ln(2)}\frac{x}{e^x-1}dx<\infty,$$
so
$$\int_0^{\infty}\frac{x}{e^x-1}dx=\int_0^{\ln(2)}\frac{x}{e^x-1}dx+\int_{\ln(2)}^\infty2xe^{-x}dx=<\infty.$$
If you are curious, the actual value of the integral is $\pi^2/6$.


text:
Q: customize Grape API response I am using  Grape GEM in my rails app, How can I customize  response
if record not found or request params are in valid
@video = Video.where(id: permitted_params[:id]).first!
for example there is no record for any id

A: You can do like this:
@video = Video.where(id: permitted_params[:id]).first!
if @video
   #your code
else
  error!({:error_message => "Record Could not found"}, 422)
end


text:
Q: Python package "dpath" segments.py giving infinite recursion on a simple "isinstance" call Attempting to use swagger codegen to auto-generate some a client library for a project I'm doing for work. Apparently swagger doesn't natively have a python version but they link to a community supported swagger-py codegen. Installed this with pip, tried running on my projects OpenAPI repo and I'm getting the error "RecursionError: maximum recursion depth exceeded in instancecheck"
Here's the stack trace:
Traceback (most recent call last):
  File "/home/user/.local/bin/swagger_py_codegen", line 8, in <module>
    sys.exit(generate())
  File "/home/user/.local/lib/python3.8/site-packages/click/core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "/home/user/.local/lib/python3.8/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/home/user/.local/lib/python3.8/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/user/.local/lib/python3.8/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/home/user/.local/lib/python3.8/site-packages/swagger_py_codegen/command.py", line 200, in generate
    for code in generator.generate():
  File "/home/user/.local/lib/python3.8/site-packages/swagger_py_codegen/base.py", line 44, in generate
    for code in g:
  File "/home/user/.local/lib/python3.8/site-packages/swagger_py_codegen/base.py", line 47, in generate
    for code in self._process():
  File "/home/user/.local/lib/python3.8/site-packages/swagger_py_codegen/jsonschema.py", line 110, in _process
    yield Schema(build_data(self.swagger))
  File "/home/user/.local/lib/python3.8/site-packages/swagger_py_codegen/jsonschema.py", line 51, in build_data
    for path, _ in swagger.search(['paths', '*']):
  File "/home/user/.local/lib/python3.8/site-packages/swagger_py_codegen/parser.py", line 118, in search
    for p, d in dpath.util.search(
  File "/home/user/.local/lib/python3.8/site-packages/dpath/util.py", line 222, in yielder
    for segments, found in dpath.segments.walk(obj):
  File "/home/user/.local/lib/python3.8/site-packages/dpath/segments.py", line 73, in walk
    for found in walk(v, location + (k,)):
  File "/home/user/.local/lib/python3.8/site-packages/dpath/segments.py", line 73, in walk
    for found in walk(v, location + (k,)):
  File "/home/user/.local/lib/python3.8/site-packages/dpath/segments.py", line 73, in walk
    for found in walk(v, location + (k,)):
  [Previous line repeated 981 more times]
  File "/home/user/.local/lib/python3.8/site-packages/dpath/segments.py", line 58, in walk
    if not leaf(obj):
  File "/home/user/.local/lib/python3.8/site-packages/dpath/segments.py", line 33, in leaf
    return isinstance(thing, leaves)
RecursionError: maximum recursion depth exceeded in __instancecheck__

If it were simply this community python implementation of swagger codegen, I'd understand, but its happening in isInstance.
It looks as though it gets to dpath site package (not familiar with this, maybe swagger_py_codegen added it), it gets to segments, and then there's a function that checks if something is a leaf.
Here's the relevant section from segments.py:
def leaf(thing):
    '''
    Return True if thing is a leaf, otherwise False.

    leaf(thing) -> bool
    '''
    leaves = (bytes, str, int, float, bool, type(None))

    return isinstance(thing, leaves)

I'm pretty sure isinstance is just part of the standard library, so its not as if I can tweak that. But looking at this leaf(thing) method from dpath, I can't see what could be causing the error.
What I've tried so far:
I tried editing segments.py to increase the max recursion count to 10,000. This just leads to running forever. I left it alone for 5 minutes and it still never completed.
So its SOME sort of infinite recursive loop, but assuming isinstance is correct, I cannot for the life of me figure out what is causing the issue from that simple leaf(thing) call


text:
Q: jquery replace html tag before loading page I want to replace a HTML tag with another, when loading a page, without showing original tag. For example I have a tag with class named header.

Original Tag

and I want to replace with another tag without showing original tag,
for example :

New Tag

I use of this code:

I'm new.

But, at first show the original tag and then remove it, and show new tag.

A: With orgHeader.replaceWith($("#new-header").html()); you're replacing the original element with the HTML content of #new-header.
But what you want to do is to replace it with #new-header itself so you should use $().outerHTML() instead
Like this
orgHeader.replaceWith($("#new-header").outerHTML());

A:

 $(document).ready(function() {
var h2 = document.getElementsByClassName('header')[0]
var div =  document.createElement('div')
div.classList.add('new-header');
div.innerHTML = 'New Tag';
h2.parentNode.insertBefore(div , h2);
h2.parentNode.removeChild(h2);
});

Original Tag

A: As mentioned, you cannot execute JavaScript/jQuery before the page loads. The best you can do is reduce load time so that it is faster than the User can perceive.

$(function() {
  var origHeader = $(".header");
  var newHeader = $("
", {
    class: "new-header"
  }).html("New Header");
  origHeader.replaceWith(newHeader);
});

Original Tag


text:
Q: Comparar 2 arrays y devolver array de lo que se repite JAVASCRIPT Que estoy haciendo mal?
Podrían explicarme?
No quiero usar foreach, filter o includes, lo quiero hacer con ciclos anidados.
El 18 rindo algo parecido, ayuda por favor!
    function actividadesEnComun(persona1, persona2) {
    // La funcion llamada 'actividadesEnComun' recibe como argumento dos arrays de actividades (strings) llamados 'persona1' y 'persona2'
      // y debe devolver un array de strings con las actividades en comun ( aquellas que se repiten ) entre cada array.
      // ej: persona1 = ['leer', 'comer', 'pasear', 'dormir', 'jugar']
      //     persona2 = ['comer', 'dormir', 'futbol']
      // actividadesEnComun(persona1, persona2) => ['comer', 'dormir']
      // Tip: podes usar ciclos for anidados.
      // Tu código aca:

            persona1 = ['Parkour', 'Gimnasia', 'Natacion'];
            persona2 = ['Parkour', 'Paracaidas', 'Remo'];

            let coincidencias = [];

            for(i=0; i < persona1.length; i++){
            for(j=0; j < persona2.length; j++){
            if (persona2[j] === persona1[i]){
          coincidencias.push(persona2[j]);
        }
      }
    }
          return console.log(coincidencias);
    }

A: Acabo de copiar y pegar tu código y funciona tal cual quieres. Devuelve por consola el array con las coincidencias entre persona1 y persona2.
Lo único que faltaría sería invocar la función para que se ejecute.


text:
Q: Why is Aptana Studio 3 hiding Javascript parameters(?) Here is some of the map code as Aptana displays it in the editor:
<area href="#" alt="" shape="rect" coords="18, 6, 104, 26" onMouseover="        (event,       [1])" onMouseout="             ()">
<area href="#" alt="" shape="rect" coords="18, 40, 101, 60" onMouseover="        (event,        [0])" onMouseout="             ()">`

onMouseover, event, & onMouseout are all blanked out. They are only visible if I select that code. Is there a setting somewhere that will change this? I couldn't find one. Thanks.


text:
Q: Typed in wrong repo remote name [New to git]
In the midst of making my first repo,  I misspelled my username in the directory.
git remote add origin [website/wrong username/repo name.git]
I tried doing git rm origin, and also deleting the branch, but that didn't work either.
What other things can I do? I've actually tried

A: You can change it with (git remote):
git remote set-url origin ....

But if you already 'remote rm' that remote, then a simple git remote add is enough.
git rm, on the other end, has nothing to do with remote, as commented by hvd.
Deleting a local branch wouldn't have any influence on the remotes (that you can see with git remote -v)


text:
Q: What is the probability mass function of the sum of two independent geometric random variables with different success probabilities? I've already seen this answer but I need the PMF of the sum of two geometric random variables with different success probabilities (uncommonly) defined as (see here):

By contrast, the following form of the geometric distribution is used for modeling the number of failures until the first success

In other words, defined Y such a random variable, its PMF is:

Here the question is the same as mine but the answer is for the other definition of the geometric random variable


text:
Q: Is there a difference between these queries I'm pretty sure these two queries are equivalent, but I could be wrong.
class Sample(models.Model):
    file = models.FileField(blank=True, null=True)

OK are these queries the same
 Sample.objects.exclude(~Q(file=''))
 Sample.objects.exclude(file__isnull=False)

A: That's a completely unnecessary use of the Q object. That is really only for one you want to add multiple conditions, especially if you are joining them with OR. And I can't see any reason to use exclude and ~ in the same condition.
However, the queries are not the same: the first excludes objects where the file attribute is not the empty string, whereas the second excludes objects where file is null; these are not necessarily the same.
Note that the second query could be expressed even more concisely:
Sample.objects.exclude(file=None)


text:
Q: Android Google Maps average polyline paths I'm making an android app that maps my path through plotting polylines using the google map API. If I have several of these paths, it just looks like a bunch of paths plotted on top of each other. Is there a way, through the Google Maps API to "average" these paths out? I was starting to head down a complicated path of computing the headings (geography util) and using those headings to get nearby polylines with similar headings and then averaging out the lats and lons to draw a polyline that was the average of all of the similar polylines. Before I do that I was wondering if anyone knew of a better way and/or if I should be using polygons instead of polylines? Here's a visual of what I am trying to do (sorry I used paint):

A: I don't know of a function in the googlemap api which would do what you want but I would do it kinda like below. I know that there are of course better ways of doing this but it is a simple way and you don't need the whole heading and bearing calculations.
You have to use the GoogleMap.getProjection().getProjection().toScreenLocation(LatLng)
on every visible LatLng Point.
List<List<Point>> PointList;
boolean close = false;
int distance = 10;

for(Point actual : PointList.get(0)) {
    for(Point check : PointList.get(1)) {
         if(check.x < actual.x + distance && check.x > actual.x - distance
            && check.y < actual.y + distance && check.y > actual.y - distance) {
              close = true;
         } else {
              close = false;
              break;
         }
    }
    if(!close) {
        break;
    }
}
if(close) {
    PointList.remove(1);
    //draw a polyline with thicker stroke and the points from PointList.get(0)
}

This checks if every point in pointlist1 is within a square of a point from pointlist2 independent where the Polyline startet or which directions they went.
If your Points are to close together think about a path simplification algorithm like the Ramer–Douglas–Peucker algorithm.

A: Based on my understanding, you want to merge multi-polylines into one polyline, you may use  'Encoded Polyline Algorithm Format'. Polyline encoding is a lossy compression algorithm that allows you to store a series of coordinates as a single string. Point coordinates are encoded using signed values. If you only have a few static points, you may also wish to use the interactive polyline encoding  utility.


text:
Q: object not set to an instance of an object using lambda expression I using lambda expression with where condition to get a count against a addresscollection.
Some of the addresscollection objects have null values to it. For some reason i am getting object not set to an instance of an object. when i dig into the exception, i found return type as {Name = "Boolean" FullName = "System.Boolean"} and return parameter {Boolean}. ANy ideas on how to handle this exception.
Here is my lambda expression that i was using:
var codes = (addresscollection.Where(n => n.Code.Contains("A") || n.Code.Contains("S") || n.Code.Contains("Q"))).Count()

A: either the collection is null or one of the codes is null.
var codes = addresscollection == null ? 0 :
            addresscollection.Count(n => n.Code != null && (
                                         n.Code.Contains("A") ||
                                         n.Code.Contains("S") ||
                                         n.Code.Contains("Q")));

A: If this is the line throwing your exception, then either addressCollection itself is null, or it contains a null element, or one of the elements contains a null in the Code property.


text:
Q: Opening a Hyperion SQR Reporting I have received some files with SQR extension. When I open it with Hyperion SQR Reporting tool, it shows only a script. How can we view the report layout using this script and how can we run this report. I'm not able to get a proper help doc on designing and executing a SQR report. Can anyone help?

A: From the command line you can run on Windows:
sqrw filename username/password@servername -KEEP

On Linux:
sqr filename username/password@servername -KEEP

Some more information here


text:
Q: Bootstrap - Scrollspy scrolling skipping second to last section I am having an issue with Bootstrap ScrollSpy in regards to the scrolling position of a selected element. The issue occurs at the bottom of the page, where I have two relatively short sections of content. When I either directly select the Projects section or scroll to it, the Education section will be highlighted instead of the Projects section. How would I offset/fix the scrolling position to select the correct section? I previously attempted to fix this by moving the anchor up into the previous section but only had limited success. The only other option I currently see is to restructure my content. Before I do that I would like to see if there are any other solutions, since I am encountering this exact issue on a second project.
The issue can be viewed here: http://beta.joshuabock.com/resume.html
Each of the sections is structured in the same way:

Projects

Project Title

Bullet Point

Bullet Point

Thanks in advance.

A: Ok I made it work. First of all

you have the same id for your nav and your ul. Remove it from your ul.
Second try putting
padding-top:30px;

To every one of your sections (just add a class, just to give them some space between).
Last and most important remove
data-offset="0"

from your body tag. The default value is 10 and with the 30px of padding it will give it some space, so when you select a section it takes you to a space that belongs to the section that you selected. Maybe another value would be better, just play with it, until you have what you want. But overall this is what is causing your problems.
HTML
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Joshua Bock's Portfolio</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="keywords" content="Joshua Bock, Portfolio, Web Design, Front End Developer, Web Developer">
        <meta name="description" content="Joshua Bock's Portfolio websites">
        <link rel="icon"
            type="image/png"
            href="public/img/favicon.png">

        <link href="public/css/main.css" rel="stylesheet">
        <link href="public/css/media-queries.css" rel="stylesheet">

        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="public/ico/apple-touch-icon-144-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="114x114" href="public/ico/apple-touch-icon-114-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="public/ico/apple-touch-icon-72-precomposed.png">
        <link rel="apple-touch-icon-precomposed" href="public/ico/apple-touch-icon-57-precomposed.png">

Joshua Bock

                        Website Designer & Web Developer

Home

Mobile Apps

Websites

Game Jam's

3d Work

Resume

Resume

Skillsets

Professional Experience

Projects

Education

Skillsets

Professional Skills

3d Modeling & Texturing

World Builder

Graphic Design

Web Design & Development

Customer Service

Help Desk/Technology Support

Programming

Web Technologies

HTML5

CSS3

Javascript

Actionscript 3.0

Jquery

Jquery UI

Twitter Bootstrap

Yahoo YUI

Zend Framework

Software Proficiency

Adobe Photoshop CS6

Adobe Flash CS6

Adobe Dreamweaver CS6

Adobe Illustrator CS6

Adobe After Effects CS6

Adobe InDesign CS6

Autodesk 3d Studio Max 2012

Autodesk Maya 2012

Pixologic Zbrush 4

Unreal Editor 3

Valve Source SDK

Unity

Zend Studio 9

Professional Experience

Software Developer III (April 2013 - Present), Northrop Grumman, CJMTK

As a Software Developer I am developing a new public facing website.

Software Developer III (December 2012 - Present), Northrop Grumman, under contract to the Defense Systems Group

As a Software Developer I am working on creating a uniformed look and feel for various widgets to be used by the U.S. Army.

Developing a uniformed style for various widgets

Developing a widget using the MVC model, HTML5, Bootstrap, Jquery, Dojo, Ozone Common Framework, and ArcGIS

Designing and Developing various HTML5 wireframes based off current widgets

Front-End Developer (November 2012 - December 2012), Northrop Grumman, Internal Research and Development

As a Front-End Developer I worked on creating wireframes and style guides. These wireframes were built using Adobe Proto, Twitter Bootstrap, and Jquery.

Designed & Developed layout wireframes

Developed page layouts

Designed various Logo compositions

Multimedia Designer III (September 2011-November 2012), Northrop Grumman, under contract to the Intelligence Community

As a Multimedia Designer I worked on classified projects, using Zend Studio 9, Adobe Photoshop, Adobe Illustrator, and Adobe After Effects to design websites that are cross-browser compatible and comply with the usability, accessibility standards set by the World Wide Web Consortium. These websites where built using frameworks such as, Yahoo YUI 2.0, Joomla, WordPress, and Zend Frameworks.

Provided design considerations and inputs during initial products requirements meetings.

Provided multiple design options highlighting elements that meet customers' goals.

Efficiently transferred product requirements into a working viewable product.

Successfully deployed multiple product releases days ahead of scheduled release.

Established working rapport with customers to develop their product vision.

Posed relevant questions driving towards solutions to design problems during product development.

Created and maintained descriptive documentation for hours spent on tasks.

Provided regular milestone samples of products, highlighting design issues.

Graphics Artist (February 2011- April 2011), DUA Computer Resources, under contract to Lockheed-Martin within the   Intelligence Community

As a member of a six-person Office of Corporate Communications graphics team working on both classified and unclassified projects, I used Adobe InDesign to design media products such as posters, brochures, retirement ceremony programs, event advertisements for plasma displays, web images, newsletters, logos, and publications. I consulted with clients throughout the Intelligence Community on their project requirements and design ideas. I worked on 42 projects. Significant projects included:

Designed three graphics for the celebration of the Army's birthday, creating a unified design for posters, web graphics, and plasma displays.

Designed a new event logo for a Support Team Conference to be used to advertise the event.

Designed a new Seal/Logo for the Office of the Inspector General.

Designed a poster collage to be given to members of the Deployment team.

CSR/ ITO Svc Delivery Rep III - NMCI Field Services - Help Desk (2009- February 2011), PSI Pax, Inc under contract to HP Enterprise Services/ HP Enterprise Services on the Navy Marine Corps Intranet (NMCI) contact– Dahlgren, VA

Provided exceptional technical support for the computer NMCI customer, resolving tickets within the required NMCI timeframe of 14 days. Followed up with customers to make sure the issues were fully resolved.

Commended for giving exceptional customer service.

Improved workflow to increase my productivity and took on additional tasks to improve my skills.

Placed orders for replacement parts and installed the parts.

Successfully completed the HP and Dell Workstation and Laptop certifications.

Graphic Specialist II ( October 2007- June 2009), Logistic Services International, under contract to L-3 Communications – D.P. Associates Inc. working for the U.S. Marine Corps on interactive courseware for KC-130J maintenance personnel – Havelock, NC

Synthesized highly complex and diverse information from subject matter experts into graphics to be used in lessons.

Received Quality Assurance Award recognition for producing high-quality graphics and an outstanding work ethic.

Collaborated with other team members to design effective workflows and procedures to decrease production time and decrease the amount of rework.

Helped other team members with graphic issues.

System Administrator/ Cage – Student Equipment Checkout Facility (September 2004- June 2007) Savannah College of Art & Design, Federal Work Study Program – Savannah, GA

Checked out/in equipment for student use for student projects.

Ensured equipment was in working order and responded to customer trouble tickets.

Information Technology Specialist (2002 to December 2006), College of Southern Maryland – La Plata & Leonardtown, MD

Set up AV equipment for classes and presentations. Set up a distance learning connection. Responded to customer tickets.

Created standard Software Loads (Images) into different pre-defined configurations (admin/lab/library, as well as classroom-specific), then updated them to further accommodate user needs by installing appropriate software.

Projects

Front-End Developer (January 2013- Feburary 2013) Techzoku

Worked on creating a live tile 'tags' section

Modeler, & Level Designer (January 2012- January 2012) International Game Developers Assoication - Game Jam 2012 - Susie's Summer Home

Modeled and Textured Rooms

Modeled and Textured Grandfather Clocks

Placement of objects in rooms

Modeler, & Level Designer (January 2011- January 2011) International Game Developers Assoication - Game Jam 2011 - Space Exodus

Modeled the Spaceship

Created Planet Textures

Education

Certificate in Web Applications Developer (January 2012- May 2012), George Mason University -ed2go, Online Self-Pace Course

Bachelor of Fine Arts in Interactive Design & Game Development (September 2004- May 2007), Savannah College of Art & Design - Savannah, GA

Associate's Degree in Applied Sciences in Computer Programming (August 2001- May 2004), College of Southern Maryland - La Plata, MD

© Joshua Bock 2013

main.css
#resumeBd section {
    padding-top: 100px;
}


text:
Q: Evaluating $\lim_{n\to\infty} \left({1\over1\cdot2\cdot3}+{1\over2\cdot3\cdot4}+\cdots+{1\over(n-1)\cdot n\cdot(n+1)}\right)$ The original question was to find $L=\displaystyle\lim_{n\to\infty}\sum_{k=1}^na_k$ where $a_n=\displaystyle{n\over(1+2+\cdots+(n-1))(1+2+\cdots+n)}$,
which I managed to get down to evaluating the following:
$$
L=4\lim_{n\to\infty} \left({1\over1\cdot2\cdot3}+{1\over2\cdot3\cdot4}+\cdots+{1\over(n-1)\cdot n\cdot(n+1)}\right)
$$
I've tried looking around the internet (as much as you can with these things), and the only thing I was able to find is  a method that uses definite integrals. I also found that the partial sum is $$\displaystyle {(n+2)(n+1)\over 4n(n+1)},$$ but this is definitely not something a student should have on the top of the head during the exam.
A hint would be greatly appreciated.

A: We first note that
$$
\frac{1}{(k-1)k(k+1)}=\frac{1}{2}\left(\frac{1}{k(k-1)}-\frac{1}{k(k+1)}\right),
$$
and thus
$$
4\sum_{k=1}^{n-1} \frac{1}{k(k+1)(k+2)}=2\sum_{k=1}^{n-1}\left(\frac{1}{k(k+1)}-\frac{1}{(k+1)(k+2)}\right)=\frac{2}{1\cdot 2}-\frac{2}{n(n+1)}.
$$
Consequently
$$
\lim_{n\to\infty}4\sum_{k=1}^{n-1} \frac{1}{k(k+1)(k+2)}=1.
$$

A: Expand by partial fractions:
$$\frac{1}{(n - 1)n(n + 1)} = -\frac 1 n + \frac 1 2 \frac 1 {n - 1} + \frac 1 2 \frac 1 {n + 1}$$
Now notice that a lot of the terms will cancel, and the series telescopes.

This is similar to, and motivated by the fact that
$$\sum_{n = 1}^{\infty} \frac 1 {n(n + 1)} = \sum_{n = 1}^{\infty} \frac 1 n - \frac 1 {n + 1}$$
telescopes to leave $1$.

A: If you don't know how you should decompose a fraction, you can always use this method:
Let $$\frac{1}{(k-1)k(k+1)}=\frac{A}{k-1}+\frac{B}{k}+\frac{C}{k+1}$$
Then we have
$$1=Ak(k+1)+B(k-1)(k+1)+Ck(k-1)$$
$$\Leftrightarrow 1=Ak^2+Ak+Bk^2-B+Ck^2-Ck$$
$$\Leftrightarrow 1=(A+B+C)k^2+(A-C)k-B$$
Clearly, $A+B+C=0$, $A-C=0$ and $B=-1$
$\Rightarrow A=B=1/2$
Thus
$$\frac{1}{(k-1)k(k+1)}=\frac{1}{2(k-1)}-\frac{1}{k}+\frac{1}{2(k+1)}$$

A: More generally, $$\frac{1}{n(n+1)\dots(n+k)} = \frac{1}k\left(\frac{1}{n(n+1)\dots(n+k-1)}-\frac{1}{(n+1)\dots(n+k)}\right)$$ so $$\sum_{n=1}^\infty \frac{1}{n(n+1)\cdots (n+k)}$$ is a telescoping series with value $\frac{1}{k\cdot k!}$.


text:
Q: Killing a VBA Script when the password is correct I'm a beginner in vba and i'm trying to block all cells except exception in a worksheet with an admin password.
It's working but my problem is that i want to stop the script when the user write his password, he can have an acces to the worksheet until closing the worksheet.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim Pass As String
Pass = "Test"

If Intersect(Target, Range("b6:b82, f6:f82, j6:j82, n6:n82, r6:r82")) Is Nothing Then
    MsgBox "Vous devez disposer d'un accès administrateur pour modifier cette cellule."
    frmLogin.Show
    passform = frmLogin.txtPassword.Value
    If passform <> Pass Then
        MsgBox "Mot de passe érroné", vbExclamation, "Error"
        Range("b6").Select
    End If
End If

End Sub

I tried the Application.Wait and putting a End doesn't worked too. `
Thanks in advance

A: If I understand you correct, you don't want to "kill the script"

*

*you don't want to run it when you select another cell within the procedure because the user put in a wrong password

*you don't want to run it, if the user has authenticated as admin

Regarding the first point: set Application.EnableEvents to false
Regarding the second point: Use a flag, e.g. m_isAdmin on module-level
Option Explicit

Private Const Pass As String = "Test"
Private m_isAdmin As Boolean

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If m_isAdmin = True Then Exit Sub 'no check necessary

Dim passform As String

If Intersect(Target, Range("b6:b82, f6:f82, j6:j82, n6:n82, r6:r82")) Is Nothing Then
    MsgBox "Vous devez disposer d'un accès administrateur pour modifier cette cellule."
    frmLogin.Show
    passform = frmLogin.txtPassword.Value
    If passform <> Pass Then
        MsgBox "Mot de passe érroné", vbExclamation, "Error"
        Application.EnableEvents = False
        Range("A1").Select
        Application.EnableEvents = True
    Else
        'if password is ok, set the module-level varialbe to true
        m_isAdmin = True
    End If
End If

End Sub


text:
Q: WPF / DeferRefresh with bound listbox I am trying to push in a number of updates to a collection to which I have bound a list box. Since the list can get quite big, i am trying to turn off updates (sorting, etc) until I finished inserting all the new items.
I figured:
using (col.DeferRefesh())
{
   .. add the items
}

but this raises an exception saying that I cannot add/remove items while DeferRefresh() is on.
Is there a proper pattern for doing what I am trying to do?

A: Adding or Removing items from a CollectionView would cause an InvalidOperationException as the operations set IsAddingNew or IsEditingItem flags to true for the CollectionView.
What you're allowed to do in DeferRefresh() is to change the sort descriptions.
This blog gives an idea about where DeferRefresh() comes to use. Also, it's pretty much contradictory to defer collection view refresh when you're actually changing values in a collectionview.

A: To do this you will need to implement/derive your own collection and implement a defer refresh functionality at the collection level and then fire a collection changed event with reset as the change type when defer refresh completes


text:
Q: Expected value of betting gains (de Finetti)/ Law of Total Probability Reading de Finetti's "Foresight", there is an issue I would like to clarify:
We have $n$ mutually exclusive events, $E_1, E_2, \dots, E_n$, that we believe to occur with probability $p_1, p_2, \dots, p_n$ respectively. Now we want to bet on those events, so if for example $E_1$ materialized and the others not, we would make a gain of $(1-p_1)S_1 - p_2S_2 - \dots -p_nS : = G_1$, that is we wager $p_1S_1 + p_2S_2+ \dots + p_nS_n$ to win either $S_1, S_2$, or $S_n$.
This gives a system of linear equations, with the determinant of the coefficient matrix necessarily equal to zero. Otherwise, we could construct a Dutch Book.
$$ \begin{vmatrix}
1-p_1 & -p_2 & -p_3 &\dots & -p_n \\
-p_1 & 1-p_2 & -p_3 & \dots & p_n \\
\vdots &  \vdots & \vdots & & \vdots \\
-p_1 & -p_2 & -p_3 & \dots & 1-p_n
\end{vmatrix} = 1 - \sum_{i = 1}^n p_i = 0
$$
De Finetti now claims that, if the determinant is equal to $0$, the expected value of the gains is equal to $0$, or $\sum_{i=1}^n p_iG_i = 0$. I verified the result for the first three dimensions, but have failed to generalize it so far.
Any input would be highly appreciated!

A: Although this can be done by simplifying the double summation, it might be more revealing to do the algebra with matrix notation.
Let $p=(p_1,p_2,\ldots, p_n)^\prime$, $S=(S_1,S_,\ldots, S_n)^\prime$, and $G=(G_1,G_2,\ldots,G_n)^\prime$ represent the information as column vectors. Write $\mathbf{1}=(1,1,\ldots, 1)^\prime$ and let $\mathbb{I}_n$ be the $n \times n$ identity matrix.
We know
$$p^\prime \mathbf{1}=1,$$
we are given
$$G = (\mathbb{I}_n - \mathbf{1}p^\prime)S,$$
and wish to compute the number
$$p^\prime G.$$
Substituting the foregoing into this expression gives
$$p^\prime G = p^\prime(\mathbb{I}_n - \mathbf{1}p^\prime)S = p^\prime S - (p^\prime \mathbf{1}) (p^\prime S) = p^\prime S - (1)(p^\prime S) = 0,$$
QED.


text:
Q: Python SciKitLearn and Pandas categoric data I'm working on multivariable regression from a csv, predicting crop performance based on multiple factors. Some of my columns are numerical and meaningful. Others are numerical and categorical, or strings and categorical (for instance, crop variety, or plot code or whatever.) How do I teach Python to use them? I've found One Hot Encoder (http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html#sklearn.preprocessing.OneHotEncoder) but don't really understand how to apply it here.
My code so far:
import pandas as pd
import statsmodels.api as sm
from sklearn.preprocessing import StandardScaler
df = pd.read_csv('filepath.csv')

df.drop(df[df['LabeledDataColumn'].isnull()].index.tolist(),inplace=True)

scale = StandardScaler()

pd.options.mode.chained_assignment = None  # default='warn'
X = df[['inputColumn1', 'inputColumn2', ...,'inputColumn20']]
y = df['LabeledDataColumn']

X[['inputColumn1', 'inputColumn2', ...,'inputColumn20']] = scale.fit_transform(X[['inputColumn1', 'inputColumn2', ...,'inputColumn20']].as_matrix())

#print (X)

est = sm.OLS(y, X).fit()

est.summary()

A: You could use the get_dummies function pandas provides and convert the categorical values.
Something like this..
predictor = pd.concat([data.get(['numerical_column_1','numerical_column_2','label']),
                           pd.get_dummies(data['categorical_column1'], prefix='Categorical_col1'),
                           pd.get_dummies(data['categorical_column2'], prefix='categorical_col2'),
                          axis=1)

then you could get the outcome/label column by doing
outcome = predictor['label']
del predictor['label']

Then call the model on the data doing
est = sm.OLS(outcome, predictor).fit()


text:
Q: Why does my job get stuck in queue forever : 'Processing - "The printer is in use."'? Why does my job get stuck in queue forever while the previous job got printed successfully ?
CUPS says 'Processing - "The printer is in use."'
Here are a little more details :

$ ping -c3 LexmkMS310dn.lan
PING LexmkMS310dn.lan (192.168.2.3) 56(84) bytes of data.
64 bytes from LexmkMS310dn.lan (192.168.2.3): icmp_seq=1 ttl=254 time=5.95 ms
64 bytes from LexmkMS310dn.lan (192.168.2.3): icmp_seq=2 ttl=254 time=5.88 ms
64 bytes from LexmkMS310dn.lan (192.168.2.3): icmp_seq=3 ttl=254 time=5.33 ms

--- LexmkMS310dn.lan ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 5.335/5.727/5.959/0.285 ms
$ lpstat -d
system default destination: LexmkMS310dn
$ lpr -o landscape -o fit-to-page -o media=A4 carine-ordre-chronoboucled_or.pdf
$ lpq -a +3
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
Rank    Owner   Job     File(s)                         Total Size
active  sebasti 634     carine-ordre-chronoboucled_or.p 62464 bytes
^C
$ pdfinfo carine-ordre-chronoboucled_or.pdf
Title:          les 3 ourschronologie de l'histoire
Subject:
Keywords:
Author:         Sylvaine
Creator:        PDFCreator Version 0.9.9
Producer:       GPL Ghostscript 8.70
CreationDate:   Mon Feb  7 16:42:54 2011
ModDate:        Mon Feb  7 16:42:54 2011
Tagged:         no
UserProperties: no
Suspects:       no
Form:           none
JavaScript:     no
Pages:          3
Encrypted:      no
Page size:      595 x 842 pts (A4)
Page rot:       90
File size:      61769 bytes
Optimized:      no
PDF version:    1.4

Here are some CUPS logs :
$ tail /var/log/cups/{access,error,page}_log
==> /var/log/cups/access_log <==
localhost - sebastien [18/Mar/2020:21:47:51 +0100] "GET /admin/log/error_log? HTTP/1.1" 200 23345 - -
localhost - sebastien [18/Mar/2020:21:48:55 +0100] "GET /admin/log/access_log? HTTP/1.1" 200 19898 - -
localhost - - [18/Mar/2020:21:50:15 +0100] "POST /printers/LexmkMS310dn HTTP/1.1" 200 466 Create-Job successful-ok
localhost - - [18/Mar/2020:21:50:15 +0100] "POST /printers/LexmkMS310dn HTTP/1.1" 200 38240 Send-Document successful-ok
localhost - sebastien [18/Mar/2020:21:51:12 +0100] "GET /admin/log/page_log? HTTP/1.1" 200 0 - -
localhost - sebastien [18/Mar/2020:21:51:20 +0100] "GET /admin/log/access_log? HTTP/1.1" 200 20333 - -
localhost - sebastien [18/Mar/2020:21:51:40 +0100] "GET /admin/log/error_log? HTTP/1.1" 304 0 - -
localhost - - [18/Mar/2020:21:51:57 +0100] "POST /jobs/ HTTP/1.1" 200 178 Cancel-Job successful-ok
localhost - - [18/Mar/2020:21:52:13 +0100] "POST /printers/LexmkMS310dn HTTP/1.1" 200 466 Create-Job successful-ok
localhost - - [18/Mar/2020:21:52:13 +0100] "POST /printers/LexmkMS310dn HTTP/1.1" 200 38240 Send-Document successful-ok

==> /var/log/cups/error_log <==
W [18/Mar/2020:21:41:35 +0100] CreateProfile failed: org.freedesktop.ColorManager.AlreadyExists:profile id 'EPSON_XP-312-RGB..' already exists
E [18/Mar/2020:21:43:57 +0100] [Client 17] pam_authenticate() returned 7 (Authentication failure)
E [18/Mar/2020:21:43:59 +0100] [Client 17] pam_authenticate() returned 7 (Authentication failure)
E [18/Mar/2020:21:44:38 +0100] [Client 17] pam_authenticate() returned 7 (Authentication failure)
E [18/Mar/2020:21:44:49 +0100] [Client 16] pam_authenticate() returned 7 (Authentication failure)
E [18/Mar/2020:21:46:40 +0100] [Client 17] Request for non-absolute resource "".
E [18/Mar/2020:21:46:40 +0100] [Client 17] Request for non-absolute resource "".
W [18/Mar/2020:21:46:40 +0100] CreateProfile failed: org.freedesktop.ColorManager.AlreadyExists:profile id 'LexmkMS310dn-Gray..' already exists
E [18/Mar/2020:21:47:07 +0100] [Client 17] Request for non-absolute resource "".
W [18/Mar/2020:21:47:07 +0100] CreateProfile failed: org.freedesktop.ColorManager.AlreadyExists:profile id 'LexmkMS310dn-Gray..' already exists

==> /var/log/cups/page_log <==

Retried with another document and still the same pb. :
$ lprm
$ lpstat -l
LexmkMS310dn-641        sebastien        38912   mer. 18 mars 2020 22:27:42 CET
    Status: The printer is in use.
    Alerts: job-printing
    queued for LexmkMS310dn
$ lpstat -l -p LexmkMS310dn
printer LexmkMS310dn now printing LexmkMS310dn-641.  enabled since mer. 18 mars 2020 23:10:05 CET
    The printer is in use.
    Form mounted:
    Content types: any
    Printer types: unknown
    Description: Lexmark MS310dn
    Alerts: toner-empty-warning
    Location:
    Connection: direct
    Interface: /etc/cups/ppd/LexmkMS310dn.ppd
    On fault: no alert
    After fault: continue
    Users allowed:
        (all)
    Forms allowed:
        (none)
    Banner required
    Charset sets:
        (none)
    Default pitch:
    Default page size:
    Default port settings:

A: The answer below :

$ lpstat -l -p LexmkMS310dn | grep Alerts:
    Alerts: toner-empty-warning

and the LexmarkMS310dn webinterface says :
Cartridge Status: Black Cartridge

     Replace, 0 estimated pages remain


text:
Q: Google Deployment Manager template using environment variables I have a template called dev.yaml that looks like this:
imports:
- path: generate_config.py

resources:
- name: application_vm
  type: generate_config.py
  properties:
    zone: europe-west1-d
    project: cpb1234567

Note that I am hardcoding the zone and project. I want those to come from these environment variables.
CLOUDSDK_COMPUTE_ZONE=europe-west1-d
GCP_PROJ_ID=cpb1234567

The generate_config.py looks like this:
#!/usr/bin/env python

COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'

def generate_config(context):

  resources = [{
      'name': context.env['name'],
      'type': 'compute.v1.instance',
      'properties': {
          'zone': context.properties['zone'],
          'machineType': ''.join([COMPUTE_URL_BASE,
                                  'projects/',
                                  context.properties['project'],
                                  '/zones/',
                                  context.properties['zone'],
                                  '/machineTypes/n1-standard-1']),
          'disks': [{
              'deviceName': 'boot',
              'type': 'PERSISTENT',
              'boot': True,
              'autoDelete': True,
              'initializeParams': {
                  'sourceImage': ''.join([COMPUTE_URL_BASE,
                                          'projects/',
                                          context.properties['project'],
                                          '/global/images/jre-10gb-debian-jessie'])
              }
          }],
          'networkInterfaces': [{
              'network': ''.join([COMPUTE_URL_BASE,
                                  'projects/',
                                  context.properties['project'],
                                  '/global/networks/default']),
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

I am getting the zone and project from the properties, so that works.
BUT, how do I get the zone and project from the environment variables?
I can't seem to do this in the Python template:
import os
...
os.environ['GCP_PROJ_ID']

As the import fails.
In the YAML, it is not clear what syntax would work.
Many thanks
Nathan

A: Whilst not an answer as such, more information is here:
https://groups.google.com/forum/#!topic/gce-discussion/Md7rCo1ZMJY


text:
Q: Which modules can be disabled in apache2.4 on windows I have an Apache 2.4 webserver running on Windows. I am looking into system hardening and the config file httpd.conf. There are numerous load modules and I am wondering which modules I can safely disable for performance and / or security improvements.
Some examples of things I would think I can disable are:
LoadModule cgi_module
others like
LoadModule rewrite_module
LoadModule version_module
LoadModule proxy_module
LoadModule setenvif_module

I am not so sure they can be disabled.
I am running php5 as a scripting engine, with no databases, and that is it.
My loaded modules are:

core mod_win32 mpm_winnt http_core mod_so mod_access_compat mod_actions mod_alias mod_allowmethods mod_asis mod_auth_basic mod_authn_core mod_authn_file mod_authz_core mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_dav_lock mod_dir mod_env mod_headers mod_include mod_info mod_isapi mod_log_config mod_cache_disk mod_mime mod_negotiation mod_proxy mod_proxy_ajp mod_rewrite mod_setenvif mod_socache_shmcb mod_ssl mod_status mod_version mod_php5


text:
Q: Display the value of a field in a form with rails I am able to display a form in a modal window doing this:
index.html.erb
 <a href="#" onclick="newModal('<%= form_edit_url %>','Title')">Edit

And it works.
Now I want to make an edit link. It will display the same form with the fields that were previously filled.
I send params to the controller with:

<%= link_to 'edit', edit_path(address.attributes) %>

But it doesn't display the form in a modal window...
How can I do this?

A: It might better to have you modal content as a partial that you render in the modal.
$("#shared-modal").html("<%= render('new_modal', locals: {zone: @zone})) %>";
To have your fields fill out again you would need to write some JS in the modal that will find those values and duplicate them into your new form fields.


text:
Q: Connect to eDirectory using application credentials. Then authenticate user I need to connect to NetIQ eDirectory using .NET & C#. The connection must be opened using application credentials. Once the connection is opened, I need to  validate user credentials under the authority of the application credentials using a similar method as S.DS.AccountManagement.
        using (var context = new PrincipalContext(ContextType.Domain, path, appUserDn, appPassword))
        {
            //Username and password for authentication.
            var valid = context.ValidateCredentials(userDn, password);
        }

I tried Novell.Directory.Ldap, S.DS.DirectoryEntry, & S.DS.AccountManagement. The last one requires AD and does not apply.
Test using Novell.Directory.Ldap..
        using (var cn = new LdapConnection())
        {
            cn.Connect(server, int.Parse(port));
            cn.Bind(appUserDn, appPassword); //throws exception if invalid credentials..
            var passwordAttr = new LdapAttribute("userPassword", password);
            cn.Compare(userDn, passwordAttr); // Only compares password, so no locked account check, etc.
        }

My current prototype uses S.DS.Protocols.
        var networkCredential = new NetworkCredential(
            appUserDn,
            appPassword);

        using (proto.LdapConnection cn = new proto.LdapConnection(new proto.LdapDirectoryIdentifier(server, int.Parse(port)), networkCredential, proto.AuthType.Basic))
        {
            cn.Bind();

            /// Next validate user credentials..

        }

I cannot find a way to validate user credentials other than reassigning NetworkCrentials and rebinding using the individual's username & password. How should I proceed?

A: It turns out our client got it wrong. The correct way is to bind the connection directly to an individual's credentials as I demonstrate in the Novell.Directory.Ldap example.
There was a posting on NetIQ's forum about executing a shell script but I did not get it working.


text:
Q: Scroll to closest div with same class So the issue I am having is getting my script to work correctly where it would scroll up to the closest div with the class '.orangered' on click of the 'scrollBtn'. What I want to be able to do is if there are multiple instances then it will scroll to the one closest to the button, if there is only one instance then it'll just scroll to that one.
I've tried using different instances of .closest to no avail.
Can anyone shed any light?
Cheers.
p.s Excuse the legacy code I'm dealing with, I've included a CodePen here because of that!
CodePen: https://codepen.io/nickelse/pen/mgZJQJ

$(".product-availability-list").has("span:contains('This quantity of items is currently not available.')").parents('.cart-row').addClass('orangered');

$(".scrollBtn").click(function() {
    $('html, body').animate({
        scrollTop: $('.orangered').offset().top - 10
    }, 500);
});
.orangered { color: red; }

        <picture>

        </picture>

      This quantity of items is currently not available.

      THIS QUANTITY OF ITEMS IS NOT AVAILABLE

      PLEASE EDIT THE QUANTITY

    THIS QUANTITY OF ITEMS IS NOT AVAILABLE

    PLEASE EDIT THE QUANTITY

        <picture>

        </picture>

      This quantity of items is currently not available.

      THIS QUANTITY OF ITEMS IS NOT AVAILABLE

      PLEASE EDIT THE QUANTITY

    THIS QUANTITY OF ITEMS IS NOT AVAILABLE

    PLEASE EDIT THE QUANTITY

        <picture>

        </picture>

     In Stock Item

   In Stock Item

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.

Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero.

Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut eros et nisl sagittis vestibulum.

    Scroll Button

A: As you put the class onto the siblings of the scroll button, to get the closest sibling with the orangered class, you can use prevAll('.orangered').first()
This will search for all previous siblings with the class orangered and return you the first one (which is the one closest to the button)

$(".product-availability-list").has("span:contains('This quantity of items is currently not available.')").parents('.cart-row').addClass('orangered');

$(".scrollBtn").click(function() {
  var scrollPosition = $(this).prevAll('.orangered').first().offset().top - 10;
  $('html, body').animate({
    scrollTop: scrollPosition
  }, 500);
});
.cart-row {
  height: 100vh;
  /* test only */
}

    <picture>

    </picture>

      This quantity of items is currently not available.

            THIS QUANTITY OF ITEMS IS NOT AVAILABLE

            PLEASE EDIT THE QUANTITY

        THIS QUANTITY OF ITEMS IS NOT AVAILABLE

        PLEASE EDIT THE QUANTITY

    <picture>

    </picture>

      This quantity of items is currently not available.

            THIS QUANTITY OF ITEMS IS NOT AVAILABLE

            PLEASE EDIT THE QUANTITY

        THIS QUANTITY OF ITEMS IS NOT AVAILABLE

        PLEASE EDIT THE QUANTITY

    <picture>

    </picture>

          In Stock Item

      In Stock Item

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
  sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus
  elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.

Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero,
  sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus
  tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero.

Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere
  cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris.
  Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut eros et nisl sagittis vestibulum.

  Scroll Button

More information about prevAll()


text:
Q: Why doesnt set_time_limit work as expected? Take a quick look at the following snippet:
<?
set_time_limit(5);
sleep(30);
echo 'done';
?>

When I execute this on my boxes, the script takes the full 30 seconds, and displays 'done'.
Why?
Shouldnt it terminate in 5 seconds and not give the script the time to display 'done'?
This is NOT in CLI mode. Nginx + PHP_FPM.
Any ideas?

I have opted to put the 'answer' in here as there is quite a few GOOD and VALID answers below. But... It appears to be a specific issue with sleep.
<?
set_time_limit(5);
while(true==true){
}
sleep(30);
echo 'done';
?>

Works as expected.

A: To quote the manual:

The set_time_limit() function and the configuration directive
  max_execution_time only affect the execution time of the script
  itself. Any time spent on activity that happens outside the execution
  of the script such as system calls using system(), stream operations,
  database queries, etc. is not included when determining the maximum
  time that the script has been running. This is not true on Windows
  where the measured time is real.

The sleep call doesn't adds to the execution time because it's an OS process and nothing is being done.

A: According to the set_time_limit() docs:

Note:
The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.

The call to sleep() doesn't count as execution time (except under Windows). This behavior is well documented in the comments on the set_time_limit() page.

A: From php.net: When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
You could subtract to match the time you want


text:
Q: Performant way to load 2000 ts models into Monaco editor for intellisense I'm trying to get intellisense in Monaco editor from the 2000+ .ts files. Loading models is taking 4-5 seconds, but auto complete suggestions are coming after 10-15 seconds and 'Loading...' is seen.

Below is the simplified version of my code which can be run in Monaco Playground
monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true);
monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true);

monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: true,
    noSyntaxValidation: true,
    noSuggestionDiagnostics: true
});

monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: true,
    noSyntaxValidation: true,
    noSuggestionDiagnostics: true
});

editor = monaco.editor.create(
    document.getElementById('container'),
    {
        minimap: { enabled: true },
        scrollBeyondLastLine: true,
        // model: null,
        language: 'typescript',
        theme: 'vs-dark',
        value: 'function () {}\n\n'
    }
);

// simulate 2000 .ts files
for (var fileIdx = 0; fileIdx < 2000; fileIdx++) {
    for (var fnIdx = 0; fnIdx < 1; fnIdx++) {
        monaco.editor.createModel(`
            function test_${fileIdx}_${fnIdx}() {}
            function fn_${fileIdx}_${fnIdx}() {}
            function foo_${fileIdx}_${fnIdx}() {}
            function bar_${fileIdx}_${fnIdx}() {}
            function out_${fileIdx}_${fnIdx}() {}
            `,
            'typescript'
        );
    }
}

I followed https://github.com/microsoft/monaco-editor/issues/2030 and Monaco Editor intellisense from multiple files, but no luck.
Can someone shed some light on the performant way to achieve this?
Mod #1:
Loading .d.ts files instead of .ts files (taken directly from here):
monaco.languages.typescript.javascriptDefaults.setEagerModelSync(false);
monaco.languages.typescript.typescriptDefaults.setEagerModelSync(false);

monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: true,
    noSyntaxValidation: true,
    noSuggestionDiagnostics: true
});

monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: true,
    noSyntaxValidation: true,
    noSuggestionDiagnostics: true
});

monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ES2016,
    allowNonTsExtensions: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    module: monaco.languages.typescript.ModuleKind.CommonJS,
    noEmit: true,
    typeRoots: ["node_modules/@types"]
});

// Case #1: Load 2000 .d.ts files with each having 1 function declaration
let extraLibs = []
for (let i = 0; i < 2000; i++) {
    extraLibs.push(
        {
        content: `export declare function next${i}() : string`,
        filePath:  monaco.Uri.file(`/node_modules/@types/external${i}/index.d.ts`).toString(true)
        }
    );
}

// Case #2: Load 1 .d.ts file with 2000 function declarations
/*let def = ''
for (let i = 0; i < 2000; i++) {
    def = def.concat(`export declare function next${i}() : string\n`);
}
let extraLibs = []
extraLibs.push(
    {
    content: def,
    filePath:  monaco.Uri.file(`/node_modules/@types/external1/index.d.ts`).toString(true)
    }
);*/

monaco.languages.typescript.typescriptDefaults.setExtraLibs(extraLibs);

extraLibs.forEach((lib) => monaco.editor.createModel(lib.content, "typescript", monaco.Uri.parse(lib.filePath)))

var jsCode = `import * as x from "external1"
const tt : string = x.next1();`;

monaco.editor.create(document.getElementById("container"), {
    model: monaco.editor.createModel(jsCode, "typescript", monaco.Uri.file("main.tsx")),
});

Observation: When loading 2000 .d.ts files with each having 1 function declaration, the perf is not good. But when loading 1 .d.ts file with 2000 function definition, the suggestions are instantaneous. Even if increased to 20000 function declarations, perf is good. But in my case, I have 3000+ ts files.
Edit #1: You can follow monaco Github issue if interested

A: For code completion it is enough to have the types of your libraries, not the entire source code, at hand. This is typically accomplished by adding typings (type declarations) to the Monaco TS/JS engines:
    public static addTypings(typings: string, source: string): void {
        if (monaco.languages.typescript) {
            monaco.languages.typescript.javascriptDefaults.addExtraLib(typings, source);
            monacolanguages.typescript.typescriptDefaults.addExtraLib(typings, source);
        }
    }

For 3rd party libs they usually come with typings (when generated from TS code). Otherwise https://github.com/DefinitelyTyped/DefinitelyTyped might be able to help.
If the code you want to load is your own and is coded in Typescript then you can just send it through tsc and let it generate the typings for you. Otherwise write it manually.


text:
Q: Попытка чтения или записи Здравствуйте.
Вот такая проблема. При компиляции программы выводит сообщение:

An unhandled exception of type 'System.AccessViolationException' occurred in ttt.exe
Additional information: Попытка чтения или записи в защищенную память. Это часто свидетельствует о том, что другая память повреждена.

Как это исправить? Всё пишется в Visual Studio 2010. С++. Транслятор с языка Паскаль на язык Си.
Как я понял, проблема в открытии файла

0xC0000005: Access violation reading location 0xce320dfa

Нет доступа к памяти. Ошибку в коде показывает на это
c = instr[inpos+slen];

Как исправить или разрешить этот доступ к памяти?
A: С высокой степенью вероятности, ошибка связана с неверной индексацией массива. Индекс выходит за границы и идет обращение к несуществующей памяти. Либо переменная вообще не инициализирована. Чтобы исправить:

*

*убедиться, что индекс не выходит за границы массива во время выполнения,

*убедиться, что переменная проинициализирована до начала использования.