text:
Q: Radio buttons and hidden fields I am trying to create a list that appears when the radio buttons are clicked, I am having a problem with the way the list appears once the button is clicked.
Here is the example http://jsfiddle.net/c2webdev/4bpKE/
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Untitled Document</title>

<input type="radio" name='thing' value='valuable' data-id="bank"/>Running Event
<input type="radio" name='thing' value='valuable' data-id="school"/>Other challenges
<input type="radio" name='thing' value='valuable' data-id="bakery"/>Baking

    What was the activity called?
    <select id="myList">
        <option value="1">List item 1</option>
        <option value="2">List item 2</option>
        <option value="3">List item 3</option>
        <option value="4">List item 4</option>
    </select>

    What was the activity called?
    <select id="myList">
        <option value="1">Pancake Making</option>
        <option value="2">Egg and spoon race</option>
        <option value="3">Sack race</option>
        <option value="4">Three leg race</option>
    </select>

    What was the activity called?
    <select id="myList">
        <option value="1">Pancake Making</option>
        <option value="2">Egg and spoon race</option>
        <option value="3">Sack race</option>
        <option value="4">Three leg race</option>
    </select>

Please help

A: You didn't set a library, e.g. jQuery on the left pane

A: I added a class name .select to your select containers. If you added another radio in the future, this way fill it. So:
CSS:
.select {
    display: none;
}

JS:
$('input[type="radio"]').click(function (event) {
    $(".select").hide();
    var id = $(this).data('id');
    $('#' + id).show();
});

HTML:
<input type="radio" name='thing' value='valuable' data-id="bank" />Running Event
<input type="radio" name='thing' value='valuable' data-id="school" />Other challenges

    What was the activity called?
    <select id="myList1">
        <option value="1">Virgin London Marathon</option>
        <option value="2">Round the Island cycle challenge</option>
        <option value="3">Kilimanjaro trek</option>
        <option value="4">Thames Path Challenge</option>
    </select>

    What was the activity called?
    <select id="myList2">
        <option value="1">Pancake Making</option>
        <option value="2">Egg and spoon race</option>
        <option value="3">Sack race </option>
        <option value="4">Three leg race</option>
    </select>

See Demo by jquery enabled


text:
Q: css floating beside fixed element I need some help with CSS.
I want to create this structure:
I want to create a menu, center-fixed, with 960px; - that's quite simple..
On the same row as the menu, I want to create two div's: one from the left border of the monitor until the nearest of the centered-div from the midle, and another from the next of the centered until the right border of the monitor.
I will try to describe you using keys.
|left_div| |_fixed_centered_960px_div| |__right_div|
The right and left divs will be fluid and will depends by the screen resolution.
Anyone can help me?
Thanks.

A: Some failed ideas: http://jsfiddle.net/kC35U/ , http://jsfiddle.net/kC35U/1/
The final solution:
http://jsfiddle.net/kC35U/4/
HTML with extra markup:

LEFT

RIGHT

CENTER

  Footer

CSS:
Center div, fixed width, centered, nothing special:
.center {
    width: 500px;
    margin: 0 auto;
}

Now, make two 50% wide wrapper divs for the left/right sides. Set their height to 0 to keep all three div's top aligned nicely:
.left {
    width: 50%;
    margin-right: auto;
    height: 0;
}

.right {
    width: 50%;
    margin-left: auto;
    height: 0;
}

Internal divs fill their parent, but we cut off the half width of the center div.
.left > div {
    margin-right: 250px;
}

.right > div {
    margin-left: 250px;
}

If you want to put something below the three columns, then you have to use some weird tricks:
.left:after, .right:after {
  content: '';
  float: left;
  height: 0;
}

#bar + * {
    clear: both;
}

A: you can use css like this
#fixed{
    margin:0 px auto;
    width: 960px;
}
#container {
    padding-left: 205px;      /* LC fullwidth */
    padding-right: 205px;     /* RC fullwidth + CC padding */
    background:#FFFF99;
}

 #container .column {
    position: relative;
        float: left;
    }

    #center {
        padding: 20px 0px 20px 0px;       /* CC padding */
        width: 100%;
        height:auto;
    }
    #content{padding:10px;height:auto;border-right:1px dashed;color:#fed88e;}

    #right{
        width: 205px;             /* RC width */
        padding: 0px;          /* RC padding */
        margin-right: -100%;
    }
#left{
 width : 205px;
padding: 0px
margin-left:-100%;

}

and the html like

A: I'm pretty sure you can get what you want using this:
The Holy Grail 3 column liquid layout
Just add:
#col1 {
    margin: 0 auto;
    width: 960px;
}
You may need additional tinkerage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: After login to phpmyadmin(ubuntu15.04), no 'phpmyadmin' option in the list How can I resolve this problem?

A: Remove the entry
$cfg['Servers'][$i]['hide_db'] = 'phpmyadmin';

in /etc/phpmyadmin/config.inc.php via
sudo sed -i '/hide_db.*=.*phpmyadmin/d' /etc/phpmyadmin/config.inc.php

Restart your http server.


text:
Q: How To Post Articles To Wordpress Programmatically? Wondering is there a way so that you can post an article to Wordpress directly from your own PHP code. I want to post in my own standalone wordpress from my php page which should call the hosted wordpress 2.8.6 version and post an article with images (create thumbnail automatically). Is it possible?

A: global $user_ID;
$post = array();
$post['post_type']    = 'post';
$post['post_content'] = 'Put your post content here';
$post['post_author']  = $user_ID;
$post['post_status']  = 'publish';
$post['post_title']   = 'Your Post Title';
$postid = wp_insert_post ($post);
if ($postid == 0)
  echo 'Oops!';
else
  echo 'Snazzy!';

From: http://wordpress.org/support/topic/254439

A: As an alternative to PHP script, you can use Yahoo to do so if you find this interesting, here is the link:
http://wordpressmodder.org/how-to-post-to-your-wordpress-site-directly-from-yahoo-mail-570.html

A: Uses Wordpress's existing XMLRPC functions: Post on your WordPress blog using PHP


text:
Q: proxy socket io fails to connect with nginx, node on docker I struggle to connect a socket.io instance in my docker app using nginx, node and react. The socket requests remains pending and then fails after some time. I tried different config to make the socket request proxified by nginx for the node server but no success. It used to work outside docker but now things are completely stuck with my socket failing.
Here is my actual nginx config :
upstream frontend {
    least_conn;
    server client:8080;
}

upstream backend {
    least_conn;
    server server:8080;
}

server {
    listen 80;

    server_name localhost;

    location / {
        proxy_pass http://frontend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location /api {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    location /ws/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Here my docker compose file
version: '3'
   services:

     nginx:
       build:
         context: ../..
         dockerfile: ./dev-kit/docker/nginx/Dockerfile
       ports:
         - 8080:80
       links:
         - client
         - server

  client:
    build: ../../client
    ports:
      - 8088:8080
    volumes:
      - ../../client:/app:cached
    command: npm run start

  server:
    build: ../../server
    ports:
      - "8082:8080"
    volumes:
      - ../../server:/app:cached
    depends_on:
      - "mongo"

  mongo:
    image: "mongo"
    volumes:
      - /usr/local/var/mongodb/:/data/db
    ports:
      - "27017:27017"

Here is the server side on express:
const express           = require('express');
const app               = module.exports = express();
const http              = require('http').Server(app);

const bodyParser        = require('body-parser');
const io                = require('socket.io')(http);

const session           = require('express-session');
const MongoStore        = require('connect-mongo')(session);

const appInterface = process.env.HOST || '0.0.0.0';
const port = process.env.PORT || 8080;

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested- With, Content-Type, Accept, x-access-token');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
    next();
});

io.on('connection', (socket) => {
  console.log('one user connected !');
  socket.on('register', (userId) => {
    users[userId] = socket.id;
  });
});

// Start server
http.listen(port, appInterface.toString(), function (err) {
   console.log('[%s] Listening on http://localhost:%d',
   app.settings.env, port);
});

This is never executed unfortunately because the socket io request fails.
And finally, here my app.js on the client side where I instanciate a socket io instance :
const socket = io('http://server:8080', { path: '/ws/socket.io' });
socket.emit('register', XXXX);

Your help would be really appreciated. I tried a lot of different nginx config to proxy the socket io request to the server but no success.

A: I believe you need to use @sign location, as explained here https://serverfault.com/questions/738452/what-does-the-at-sign-mean-in-nginx-location-blocks
So the nginx.conf looks like this:
location /socket.io {
    try_files $uri $uri/ @websocket;
}
...
location @websocket {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}


text:
Q: Random sampling tweets with tweepy I'm trying to analyze tweets that have the hashtag #contentmarketing. I first tried grabbing 20,000 tweets with tweepy but ran into the rate limit. So I'd like to take a random sample instead (or a couple random samples).
I'm not really familiar with random sampling through an API call. If I had an array that already contained the data, I would take random indices from that array without replacement. However, I don't think I can create that array in the first place without the rate limit kicking in.
Can anyone enlighten me on how to access random tweets (or random data from an API, overall)?
For reference, here's the code that got me in rate limit purgatory:
import tweepy
from tweepy import OAuthHandler

consumerKey = 'my-key'
consumerSecret = 'my-key'
accessToken = 'my-key'
accessSecret = 'my-key'

auth = OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessSecret)

api = tweepy.API(auth)

tweets = []

for tweet in tweepy.Cursor(api.search, q='#contentmarketing', count=20000,
    lang='en', since='2017-06-20').items():
        tweets.append(tweet)

with open('content-tweets.json', 'w') as f:
    json.dump(tweets, f, sort_keys=True, indent=4)

A: This should stop the rate limit from kicking in, just make the following changes to your code:
api = tweepy.API(auth, wait_on_rate_limit=True)

A: I ever heared about getting random tweets. But you can get "forever" tweets and not all of them, so this is quite the same.
With the public search API, you can do 450 requests within 15 minutes (app auth). So you can ask for 100 tweets every 2 seconds. This is never ended.
Then change the "count" parameter to 100, and add a time.sleep(2) :
import time

for tweet in tweepy.Cursor(api.search, q='#contentmarketing', count=100, lang='en', since='2017-06-20').items():

tweets.append(tweet)
time.sleep(2)

Reference : https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html


text:
Q: Use custom ASP.NET MVC IValueProvider, without setting it globally? I want to be able to grab keys/values from a cookie and use that to bind a model.
Rather than building a custom ModelBinder, I believe that the DefaultModelBinder works well out of the box, and the best way to choose where the values come from would be to set the IValueProvider that it uses.
To do this I don't want to create a custom ValueProviderFactory and bind it globally, because I only want this ValueProvider to be used in a specific action method.
I've built an attribute that does this:
/// <summary>
/// Replaces the current value provider with the specified value provider
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class SetValueProviderAttribute : ActionFilterAttribute
{
    public SetValueProviderAttribute(Type valueProviderType)
    {
        if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
            throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");

        _ValueProviderType = valueProviderType;
    }

    private Type _ValueProviderType;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        IValueProvider valueProviderToAdd = GetValueProviderToAdd();

        filterContext.Controller.ValueProvider = valueProviderToAdd;
    }

    private IValueProvider GetValueProviderToAdd()
    {
        return (IValueProvider)Activator.CreateInstance(_ValueProviderType);
    }
}

Unfortunately, the ModelBinder and its IValueProvider are set BEFORE OnActionExecuting (why?????).  Has anyone else figured out a way to inject a custom IValueProvider into the DefaultModelBinder without using the ValueProviderFactory?

A: Here is an alternative that lets you specify IValueProviders as attributes against an actions parameters.
This makes the IValueProviders transient and not Global.
public interface IControllerContextAware
{
    ControllerContext ControllerContext { get; set; }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class ValueProviderAttribute : CustomModelBinderAttribute
{
    public Type[] ValueProviders { get; private set; }

    public ValueProviderAttribute(params Type[] valueProviders)
    {
        if (valueProviders == null)
        {
            throw new ArgumentNullException("valueProviders");
        }
        foreach (var valueProvider in valueProviders.Where(valueProvider => !typeof(IValueProvider).IsAssignableFrom(valueProvider)))
        {
            throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The valueProvider {0} must be of type {1}", valueProvider.FullName, typeof(IValueProvider)), "valueProviders");
        }

        ValueProviders = valueProviders;
    }

    public override IModelBinder GetBinder()
    {
        return new ValueProviderModelBinder
            {
                ValueProviderTypes = ValueProviders.ToList(),
                CreateValueProvider = OnCreateValueProvider
            };
    }

    protected virtual IValueProvider OnCreateValueProvider(Type valueProviderType, ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueProvider = (IValueProvider)Activator.CreateInstance(valueProviderType);
        if (valueProvider is IControllerContextAware)
        {
            (valueProvider as IControllerContextAware).ControllerContext = controllerContext;
        }
        return valueProvider;
    }

    private class ValueProviderModelBinder : DefaultModelBinder
    {
        public IList<Type> ValueProviderTypes { get; set; }
        public Func<Type, ControllerContext, ModelBindingContext, IValueProvider> CreateValueProvider { get; set; }

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProviders = from type in ValueProviderTypes
                                 select CreateValueProvider(type, controllerContext, bindingContext);

            bindingContext.ValueProvider = new ValueProviderCollection(valueProviders.Concat((Collection<IValueProvider>)bindingContext.ValueProvider).ToList());

            return base.BindModel(controllerContext, bindingContext);
        }
    }
}

This is basically the code form the ModelBinderAttribute, but with a few tweaks.
It isn't sealed and so you can alter the way in which the IValueProviders are created if need be.
Here is a simple example which looks in another field, possibly a hidden or encrypted field, and takes the data and puts it into another property.
Here is the model, which has no knowledge of the IValueProvider, but does know about the hidden field.
public class SomeModel
{
    [Required]
    public string MyString { get; set; }

    [Required]
    public string MyOtherString { get; set; }

    [Required]
    public string Data { get; set; }
}

THen we have the IValueProvider, in this case, my provider knows explicitly about my model, but this doesn't have to be the case.
public class MyValueProvider : IValueProvider, IControllerContextAware
{
    public ControllerContext ControllerContext { get; set; }

    public bool ContainsPrefix(string prefix)
    {
        var containsPrefix = prefix == "MyString" && ControllerContext.HttpContext.Request.Params.AllKeys.Any(key => key == "Data");
        return containsPrefix;
    }

    public ValueProviderResult GetValue(string key)
    {
        if (key == "MyString")
        {
            var data = ControllerContext.RequestContext.HttpContext.Request.Params["Data"];

            var myString = data.Split(':')[1];

            return new ValueProviderResult(myString, myString, CultureInfo.CurrentCulture);
        }
        return null;
    }
}

and then the action that ties all this together:
    [HttpGet]
    public ActionResult Test()
    {
        return View(new SomeModel());
    }

    [HttpPost]
    public ActionResult Test([ValueProvider(typeof(MyValueProvider))]SomeModel model)
    {
        return View(model);
    }

A: Figured out how to do this.  First, create a custom model binder that takes a value provider type in the constructor - but inherits from default modelbinder.  This allows you to use standard model binding with a custom value provider:
/// <summary>
/// Uses default model binding, but sets the value provider it uses
/// </summary>
public class SetValueProviderDefaultModelBinder : DefaultModelBinder
{
    private Type _ValueProviderType;

    public SetValueProviderDefaultModelBinder(Type valueProviderType)
    {
        if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
            throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");

        _ValueProviderType = valueProviderType;
    }

    /// <summary>
    /// Before binding the model, set the IValueProvider it uses
    /// </summary>
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        bindingContext.ValueProvider = GetValueProvider();

        return base.BindModel(controllerContext, bindingContext);
    }

    private IValueProvider GetValueProvider()
    {
        return (IValueProvider)Activator.CreateInstance(_ValueProviderType);
    }
}

Then we create a model binding attribute that will inject the value provider type in the custom model binder created above, and use that as the model binder:
/// <summary>
/// On the default model binder, replaces the current value provider with the specified value provider.  Cannot use custom model binder with this.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
public class SetValueProviderAttribute : CustomModelBinderAttribute
{
    // Originally, this was an action filter, that OnActionExecuting, set the controller's IValueProvider, expecting it to be picked up by the default model binder
    // when binding the model.  Unfortunately, OnActionExecuting occurs AFTER the IValueProvider is set on the DefaultModelBinder.  The only way around this is
    // to create a custom model binder that inherits from DefaultModelBinder, and in its BindModel method set the ValueProvider and then do the standard model binding.

    public SetValueProviderAttribute(Type valueProviderType)
    {
        if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
            throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");

        _ValueProviderType = valueProviderType;
    }

    private Type _ValueProviderType;

    public override IModelBinder GetBinder()
    {
        var modelBinder = new SetValueProviderDefaultModelBinder(_ValueProviderType);
        return modelBinder;
    }
}

A: You should still use a ValueProviderFactory in this case.
The method that you have to implement on your ValueProviderFactory has this signature:
IValueProvider GetValueProvider(ControllerContext controllerContext)

Within your implementation of that method you can inspect the controller context, and if the incoming request is for the controller/action that you want to leverage cookies on, return some CustomCookieValueProvider.
If you don't want to leverage cookies for the request, just return null and the framework will filter that out of from the list of Value Providers.
As a bonus, you might not want to hard code the logic for when to use the CustomCookieValueProvider into the ValueProviderFactory. You could, perhaps, leverage DataTokens to match when to use cookies with given routes. So add a route like this:
routes.MapRoute("SomeRoute","{controller}/{action}").DataTokens.Add("UseCookies", true);

Notice the DataTokens.Add() call in there, now inside you GetValueProvider method you could do something like this:
if (controllerContext.RouteData.DataTokens.ContainsKey("UseCookies"))
{
    return new CustomCookieValueProvider(controllerContext.RequestContext.HttpContext.Request.Cookies);
}

return null;


text:
Q: how to show error message which is passed by the server when using $asyncValidators <ng-form name="myForm">

                you cannot print {{data}} !!

                <textarea name="text{{$index}}" placeholder="{{textSection.text}}" ng-model="getUserTextSction(textSection.textStyleID, area.userPageText).text" print-validator ng-model-options="{updateOn: 'blur'}"> </textarea>

</ng-form>

above is my html code and below is javascript code
            angular.module('editorApp')
            .directive('printValidator', function ($http, $q,baseService) {
            return {
            restrict: "A",
            require: "ngModel",
            link: function (scope, element, attrs, ngModel) {
            var checkPrintable = function (modelValue, viewValue) {

                var deferred = $q.defer();
                var value = modelValue || viewValue;

                var param = {};
                param.text = value;
                return $http.post(
                    '/api/edittexts/CheckPrintable/',
                   param, {
                       headers: {
                           'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                       }
                   })
                .then(function (response) {
                    if (response.data.ngChar) {
                        ngModel.$setValidity('printValidator', false);
                        alert("you cannot print:"+response.data.ngChar);
                        deferred.reject(response.data);
                    }
                    else
                    {
                        ngModel.$setValidity('printValidator', true);
                        deferred.resolve;
                    }
                    return deferred.promise;
                });
            }
            ngModel.$asyncValidators.text = checkPrintable;
        }
    }
})

the code above worked well.when user typed unprintable characters it shows an error message...
Now I have two questions:
the first one is how can i show the unprintable characters which is passed from the server side (actually it is "response.data.ngChar") in the  tag at " {{data}}" ??
(it means ,how to get the deferred.reject's parameters in the html)
the second one is how can i disable the submit botton when there is unprintable characters errors?
I use "ng-disabled="myForm.$invalid"" but it doesnot work.
thank you.

A: I see you are doing some very complicated stuff for a very easy job.
How i would set this up is something as the following:

Fetching data...

 0">Unprintable characters: {{data}}

<a ng-disabled="data && data.length < 1" ng-click="completeEditPage("/article/")">

Your variable 'data' will be set when the data is retrieved asynchronously. When data is being retrieved, $scope.data will be undefined making your div 'fetching data...' visible
When your variable 'data' gets set by the asynchronous function. the fetching data... div will disappear and you can view another div based on the 'data' not being undefined.
Now the only thing you need to do is set $scope.data when your function finishes.
so... $scope.data = response.data;
(Hoping that your response.data is an array)


text:
Q: LED and photodiode characteristics at very low currents I'm trying to understand the coupled characteristic of a classic 4n35 optocoupler, used in reverse biased photodiode mode (I'm only using the B-C junction only).
Over 1mA input forward voltage, the characteristic is nicely linear, which is to be expected since

*

*the led light output is proportionnal to current,

*the photodiode's photocurrent is proportionnal to photon influx.

However, under ~1mA input forward current I measured the following coupled characteristic :

Measurement notes : The currents are measured as the voltage at the given points, divided by the corresponding resistance value. The voltage is measured by an arduino that also provides the PWM. I vary If through the PWM duty cycle. I wait about 100ms before measuring a new datapoint so that the ADC S&H circuitry stabilizes ; and I increased the PWM frequency so that ripple is more or less negligible.
Obviously, the characteristic is not linear anymore. What is the reason for this behaviour?
I thought that that might come from the diode or the photodiode side :

*

*On the LED side, the input led forward voltage collapses at a low current. That may imply that the energy of the charge carriers is not enough to emit a photon ; however as I understand it the photon energy comes from the electron+hole energy, not from the forward voltage drop. Or am I mistaken?

*Now for the photodiode side. At vanishing photocurrent levels, I'd expect the dark current to be significant. However this dark current should add up to the photocurrent, so that without any input the diode reverse bias current is not zero. We should therefore observe a straight line with a positive offset. This is not what I can see here : it looks like there is the photocurrent plus a negative current that vanishes when some light strikes the junction.
Unfortunately most information I found on the web about leds or optocouplers assume current levels much higher than that. OTOH, information about dark current is plenty but it doesn't seem to apply here.

A: I can make a couple of guesses about what might be going on.

*

*You aren't actually measuring the LED current, but instead you are assuming \$I_{LED} = (V_{in} - V_F)/220\$ and assuming \$V_F\$ is a constant. You are operating in a regime where \$V_F\$ will vary significantly (100's of mV), and neglecting this would explain (qualitatively, anyway) the shape of your graph.

*The LED has some parasitic conductive path through it that does not cause light emission. For low currents, this path is taking more of the current and resulting in reduced light emissions until some threshold is reached and the proper path begins to dominate.

*At very low currents, the optical emission pattern of the LED is changing, causing less of the light to reach the detector and more to be lost into the package.

*The way you are hooking up the detector is causing funny behavior. Hooking up the base but not the emitter is not a common way to use a phototransistor (AFAIK), and is not what the device designers would be designing for. Typical phototransistor circuits are shown in an App Note from Sharp starting on page 13.


text:
Q: Передача значения методом POST Передача значения методом POST из

У меня есть код на Javascript который находит ближайший похожий цвет и мне нужно после того как он его найдет найти его базы данных MySQL. Я хотел это сделать методом POST, только у меня не получается передать значение class="text_color". Как мне это сделать? Помогите пожалуйста.
    <?php
$db = mysql_connect('localhost', 'php_color', '12345');
mysql_query("SET NAMES 'cp1251'");
mysql_select_db("shedow",$db);

//$result = mysql_query("SELECT * FROM color_name WHERE HEX = '$hex'  OR H ='$h_r'  ORDER BY H,S,V") or die(mysql_error());
/*$result = mysql_query("SELECT DISTINCT English_name,Russian_name,HEX,HEX,R,G,B,C,M,Y,K,H,S,V, abs(r-$r)^2+abs(g-$g)^2+abs(b-$b)^2 b FROM color_name ORDER BY R,G,B ASC") or die(mysql_error());*/
$result = mysql_query("SELECT HEX FROM color  ") or die(mysql_error());
$myrow = mysql_fetch_array($result);

/*$options = '';
 do {
 $options .= printf ("%s,", $myrow['HEX']);
}
while($myrow =  mysql_fetch_array($result));
echo "$options";*/
$arr = array();

while($rows = mysql_fetch_array($result)){

    $arr[] = $rows[0];

}

?>

    <input  type="text" maxlength="6" size="15" id="colorpickerField1" value="00ff00" />

    <button>Get the closest color</button>

Base color:

Closest color:

<form action='search_color.php' method='post' name='form_s' align='left'>

<input  name='text_color' type='text'  style='width: 10%;' id='hex' />

<input name='submit_s' type='submit' style='width: 20%;'value='Показать информацию о цвете' />
</form>

A: Рядом с кодом
$('.text_color').text(getSimilarColors($('input').val()));

добавь
$('.text_color').value(getSimilarColors($('input').val()));

В форму добавь
<input name="Замени_на_другой_name" class="text_color" type="hidden"/>

Это создаст скрытое поле в форме, которое не будет видеть пользователь. Но оно, будет заполнятся твоим скриптом (так как он заполняет по классам и именно для этого поля добавили заполнение value).


text:
Q: Using eclipse with processing, cannot get java application to run so i am just trying eclipse with processing and are having a problem with getting the java application to run.
I am basically following this tutorial: https://processing.org/tutorials/eclipse/
I have followed the steps but when i get to this part:
    import processing.core.PApplet;

    public class UsingProcessing extends PApplet{

public static void main(String[] args) {
    PApplet.main("UsingProcessing");

}

}

No errors or nothing but when i press run (run as java application), a java program opens (no window, i can just see the program in the bottom part of the screen). Then it closes after a couple of seconds.
I also get the following errors:
java.lang.NoClassDefFoundError: com/apple/eawt/QuitHandler
at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3119)
at java.base/java.lang.Class.getMethodsRecursive(Class.java:3260)
at java.base/java.lang.Class.getMethod0(Class.java:3246)
at java.base/java.lang.Class.getMethod(Class.java:2065)
at processing.core.PApplet.runSketch(PApplet.java:10707)
at processing.core.PApplet.main(PApplet.java:10504)
at processing.core.PApplet.main(PApplet.java:10486)
at UsingProcessing.main(UsingProcessing.java:6)
Caused by: java.lang.ClassNotFoundException: com.apple.eawt.QuitHandler
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 9 more

That part of code should at least give me an empty sketch but i get nothing..
This guy got it to work but i cant.. https://www.youtube.com/watch?v=0cqSjyvA8EY
I can assure you that i have imported the processing library correct, so that is not where the problem lays. I believe that it is some problem with my java? I am using a macbook pro and the following java:
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)
Thankful for all the help and I am kind of new to this so please be gentle if anything is wrong!
EDIT:
I have also tried with IntelliJ without luck, the same thing, java opens for a brief moment and then closes. This video was my guide: https://www.youtube.com/watch?v=_h2GZgnPcnM

A:
I can assure you that i have imported the processing library correct, so that is not where the problem lays.

You need more than just the core.jar library. In your case you need whatever .jar file contains the com/apple/eawt/QuitHandler class.
This answer says that the .jar you're looking for comes with the Mac JDK. Try adding that .jar file to your classpath.

A: So i believe the problem is sort of solved. The problem was (i think) with the java that apple uses(?). So i downgraded to the Processing 2 core.jar and everything worked fine.
Found here: https://github.com/processing/processing/issues/5371
and a link that i did not fully understand : https://github.com/processing/processing/wiki/Supported-Platforms#java-9
The guy there suggests that you should downgrade your jdk(?), but I think that it was processing 2 that was discussed (when i did that it did not work). So for now, everything in eclipse done with processing has to be done with processing 2.
This is strange because the tutorial on processings website made it work with processing 3
EDIT: the previous answer was asked more than five years ago..


text:
Q: Is resource nesting the only way to enable multiple dynamic segments? This seems to suggest that the answer is yes:
From Ember Pre1 to Pre4: Multiple dynamic segments per route? Update: What is the allowed syntax for dynamic segments?
... but I just want to confirm.
In my case, as a learning exercise, I'm building a calendar in Ember, with monthly displays. I need to be able to link from a given month to the previous month, and to the next month.
So I'd like to be able to
{{ linkTo calendar_month year month }}

and
this.transitionTo('calendarMonth', year, month)

Wondering if this is feasible without using nested resources. I can get it working with something like:
App.Router.map(function() {
  this.resource("year", { path: "calendar/:year" }, function() {
    this.resource("calendar_month", { path: "/:month" }, function() {
      this.route('index');
    });
  });
});

... but this involves introducing a Year object which might not really need to exist from a modeling perspective, just so I can use its id in linkTo
I'd prefer to set up a route with two parameters/dynamic segments:
App.Router.map(function() {
  this.route('calendar_month', { path: 'calendar/:year/:month'});
});

But am I correct that this is not possible? I just want to make sure I'm doing this the cleanest, emberiest way possible.
Put another way:
I understand this notion that "If your user interface is nested, then your routes should be nested", but, if my url is nested, this does not necessarily imply that my interface will be nested as well. So I'm wondering: if my url is nested, is it always best practice to build corresponding nested models?
Any guidance / clarification much appreciated.
thanks,

A: As i am the asker of the question you referenced, i am answering here. I have already updated my question that this is perfectly possible.
Your approach should work:
App.Router.map(function() {
  this.route('calendar_month', { path: 'calendar/:year/:month'});
});

All you have to add are the serialize and model hook implementations:
serialize: function(context){
    // i assume that you wrap year and month in an Object (maybe App.YearAndMonthObject)
    var ret = {
        year : context.get("year"),
        month : context.get("month")
    };
    return ret;
},
model : function(params){
    //somehow create your object from the params
    var model = App.YearAndMonthObject.create({
        year : params.year,
        month : params.month
    });
    return model;
}

This would also need a modification on your use of linkTo:
{{ linkTo calendar_month year month }}

...instead you would just use:
{{ linkTo calendar_month yearAndMonth }}

I think this an emberish way to deal with this.
Summary: So what are routes all about?

They are used to separate concerns. And in your case it seems so, that year and month are part of the same concern (=route). Therefore they should be wrapped together in an new Ember Object and your route (CalendarMonthRoute) should deal with this new object (maybe YearAndMonthObject or CalendarMonthObject?).


text:
Q: No configuration file found when using log4j with log4j2 in project? In our project we are using log4j with log4j2. When I run the Junits I am getting the error saying: No log4j2 configuration file found.
But the log4j.properties file is already available in that location. Using Google I found that it requires logj2.xml file then I provided log4j2.xml file. Junits runs smoothly.
Does log4j2 support property file or not?

A: Log4j2 does support property file.
Property file can be provided to log4j2 by either of the following 2 ways:

*

*Set the configuration file path (with .properties extension) in "log4j.configurationFile" system property.

*Name the configuration file log4j2.properties (or log4j2-test.properties) and keep that in the classpath.

You can learn more about log4j2 configuration here.


text:
Q: .NET Core - cannot find a simple soap request code I need to send an xml like this
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="**************">
    <soap:Header/>
    <soap:Body>
        <web:Open>
            <web:username>USERNAME</web:username>
            <web:password>PASSWORD</web:password>
        </web:Open>
    </soap:Body>
</soap:Envelope>

from this tutorial https://stackify.com/soap-net-core/
var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(new Uri("http://server/PingService.svc"));
var channelFactory = new ChannelFactory(binding, endpoint);
var serviceClient = channelFactory.CreateChannel();
var result = serviceClient.Ping("Ping");
channelFactory.Close();

but how do I modify this code to do my own request ?
I parsed microsoft documentation about WCF and svcutils and it appears infuriatingly complicated
I mean, all that, just to send an XML ?
how to I do a SOAP request in the simplest manner possible ?
thanks for helping me on this

A: The simplest way is to import the wsdl from the server side into your project. this will generate most of the required code. An example has been provided in the other question that you asked related to this.
It is also possible to do it completely manually. First you need create one or 2 xml schema's that describe your header and payload (the header is optional).
Open.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:web="http://bvdep.com/webservices/" targetNamespace="http://bvdep.com/webservices/" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:complexType name="OpenType">
        <xs:sequence>
            <xs:element name="username" type="xs:string"/>
            <xs:element name="password" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
    <xs:element name="Open" type="web:OpenType"/>
</xs:schema>

header.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:head="http://bvdep.com/webservices/Header" targetNamespace="http://bvdep.com/webservices/Header" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="Header" type="head:HeaderType"/>
    <xs:complexType name="HeaderType">
        <xs:sequence>
            <xs:element name="From" type="xs:string"/>
            <xs:element name="To" type="xs:string"/>
            <xs:element name="MsgType" type="xs:string"/>
            <xs:element name="Datetime" type="xs:dateTime"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

then you use xsd.exe to generate class files. I use a bat file to do so.
@echo off
set exepad=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\xsd.exe
set sourcepad=..\..\

set xsdpad=%sourcepad%\ConsoleCore\xsd
set Outpad=%sourcepad%\ConsoleCore\generated

Set NameSpace=ConsoleCore.generated

"%exepad%" "%xsdpad%\Open.xsd" /c  /n:%NameSpace%  /o:%Outpad%
"%exepad%" "%xsdpad%\Header.xsd" /c  /n:%NameSpace%  /o:%Outpad%

In your vs core project you need to add 2 nuget packages
System.ServiceModel.Primitives and System.ServiceModel.Http
next you need to add an interface that describes the service an operation(s) that you want to invoke just as you found in the ping example
[ServiceContract(Namespace = "http://Open.webservice.namespace")]
    public interface IOpenService
    {
        [XmlSerializerFormat()]
        [OperationContract(IsOneWay = false, Action = "urn:#OpenOperation")]
        OpenReturnMsg OpenOperation(OpenMsg msg);
    }

    [MessageContract(IsWrapped = false)]
    public class OpenMsg
    {
        [MessageHeader(Name = "Header", Namespace = "http://bvdep.com/webservices/Header")] public HeaderType Header { get; set; }
        [MessageBodyMember(Name = "Open", Namespace = "http://bvdep.com/webservices/")] public OpenType Open { get; set; }
    }

    [MessageContract(IsWrapped = false)]
    public class OpenReturnMsg
    {
        [MessageBodyMember(Name = "ResponseMsg", Namespace = "http://Open.webservice.namespace")] public string ResponseMsg { get; set; }
    }

And last the actual statements to invoke the service and get a response:
static void Main(string[] args)
        {
            Console.WriteLine("Start Program!");

            var binding = new BasicHttpBinding();
            var endpoint = new EndpointAddress(new Uri("http://LOCALHOST:8085/mockOpenBinding"));
            var channelFactory = new ChannelFactory<IOpenService>(binding, endpoint);
            var serviceClient = channelFactory.CreateChannel();

            var msg = new OpenMsg
            {
                Header = new HeaderType
                {
                    From = "source",
                    To = "dest",
                    MsgType = "open",
                    Datetime = DateTime.Now
                },
                Open = new OpenType
                {
                    username = "user",
                    password = "pw"
                }
            };

            var result = serviceClient.OpenOperation(msg);
            channelFactory.Close();
            Console.WriteLine(result.ResponseMsg);
        }

i've tested this using a mock service from the below WSDL in SOAPUI.
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://Open.webservice.namespace" xmlns:web="http://bvdep.com/webservices/" xmlns:head="http://bvdep.com/webservices/Header" targetNamespace="http://Open.webservice.namespace">
    <wsdl:types>
        <xs:schema targetNamespace="http://Open.webservice.namespace" elementFormDefault="qualified">
            <xs:import namespace="http://bvdep.com/webservices/Header" schemaLocation="Header.xsd"/>
            <xs:import namespace="http://bvdep.com/webservices/" schemaLocation="Open.xsd"/>
            <xs:element name="ResponseMsg" type="xs:string"/>
        </xs:schema>
    </wsdl:types>
    <wsdl:message name="OpenMessageHeader">
        <wsdl:part name="MsgHeader" element="head:Header"/>
    </wsdl:message>
    <wsdl:message name="OpenMessageRequest">
        <wsdl:part name="Open" element="web:Open"/>
    </wsdl:message>
    <wsdl:message name="OpenMessageResponse">
        <wsdl:part name="Response" element="tns:ResponseMsg"/>
    </wsdl:message>
    <wsdl:portType name="OpenPortType">
        <wsdl:operation name="OpenOperation">
            <wsdl:input message="tns:OpenMessageRequest"/>
            <wsdl:output message="tns:OpenMessageResponse"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="OpenBinding" type="tns:OpenPortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="OpenOperation">
            <soap:operation soapAction="urn:#OpenOperation"/>
            <wsdl:input>
                <soap:body use="literal"/>
                <soap:header message="tns:OpenMessageHeader" part="MsgHeader" use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="OpenService">
        <wsdl:port name="OpenPort" binding="tns:OpenBinding">
            <soap:address location="No Target Adress"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>


text:
Q: onBackPressed to hide Not destroy activity i know how to cancel back keypress, so that the activity / main window stays visible:
public void onBackPressed() {
    return;
}

my aim is to hide the activity, however, without finishing it, how do you do that in the onBackPressed event?
i.e. I would like to get as far as onPause(), but not evoke the onBackPressed() default behaviour that essentially calls finish(). another way to put it is that i would like to mimic onUserLeaveHint() ?
any help appreciated!

A: If you want to mimic the "Home" button on specific Activities just do this:
Below API 5:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Above and on API 5:
@Override
public void onBackPressed() {
  moveTaskToBack(true);
}

It will move the Task to background.. when you return, it will be as it was.
You can see more information about this here: Override back button to act like home button

A: If you don't destroy your activity you must set acitvity launch mode to single_instance and use moveTaskToBack(true) to send to background.

A: If you want to mimic the "Home" button on specific Activities :
1st Method :
@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

2nd Method :
@Override
public void onBackPressed() {
   moveTaskToBack(true);
}

And if you want to move to the previous activity without destroying current :
@Override
public void onBackPressed() {
    startActivity(new Intent(CurrentActivity.this, DestinationActivity.class);
}

And now from any activity if you want to open the activity which is in Background . I name CurrentActivity. you could call it form anywhere..like..it wil take that actvity and put it to top of stack . and open it where you left off.
Intent intent = new Intent(FromAnyActivity.this, CurrentActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

Flags :
FLAG_ACTIVITY_REORDER_TO_FRONT : To reorder the activity from stack
FLAG_ACTIVITY_CLEAR_TOP : To remove all the activities from the top

A: Well, you can't move back in the current stack without finishing the activity. Perhaps you could detect onBackPressed() and then launch the home intent in a new task:
public void onBackPressed() {
    Intent i = new Intent("android.intent.action.MAIN");
        i.addCategory("android.intent.category.HOME");
        i.addCategory("android.intent.category.DEFAULT");
        i.addCategory("android.intent.category.LAUNCHER");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    return;
}

Let me know if that works.


text:
Q: How to check which format is date in python I'm getting the date in a string and it's not always same format, is there a way to detect what format is that date for example:
If data comes like this 2023-12-03
I want to somehow get output like this "%Y-%m-%d", so I know which format is using. This is just an example format date in the string can come also like this 13/02/2023 and the format would be "%d/%m/%Y"

A: You can use dateutil to parse it
from dateutil.parser import parse

date_string = "2023-12-03"
date = parse(date_string)

print(date.strftime("%Y-%m-%d"))

This code will output "2023-12-03" because the input date string is already in the format "%Y-%m-%d".
If the input date string is in a different format, dateutil will try to automatically detect the format and parse the date correctly. For example, if the date string is "12/03/2023", the following code will output "2023-12-03"


text:
Q: Batch File Gives Message: "1 was unexpected at this time" I wrote a batch file that checks if a server is online. It uses a few cygwin-64 tools.
Here's the batch file:
wget -S http://www.example.com/ -o headers.txt -O index.html
cat http-commands.txt | ncat --idle-timeout 5 -vvv www.example.com 80 >> ncat.txt

unix2dos headers.txt

grep -i apache headers.txt > comparison-now.txt

fc comparison-known-good.txt comparison-now.txt

if %errorlevel% 1 goto email

echo Exit Code is %errorlevel%

if %errorlevel% 0 goto good

:email
del /f /q files.zip
zip -xi ncat.txt index.html headers.txt files.zip
C:\commands\Blat.exe C:\path\message.txt -attach C:\path\files.zip -tf     C:\path\recipients.txt -subject "Example.com Down!" -server relay.server.com -f example@gmail.com -log C:\path\log.txt -debug -timestamp -overwritelog

:good
REM Hooray! The server is alive!
exit

The output is below:
1 was unexpected at this time.
C:\path>if 0 1 goto email

Perhaps the logic should be this, since there's only going to be two different errors?
if errorlevel 1 do this
.
else do this

A: Batch File Gives Message: "1 was unexpected at this time"
You are using:
if %errorlevel% 1 goto email

...
if %errorlevel% 0 goto good

Try instead:
if %errorlevel% equ 1 goto email

...
if %errorlevel% equ 0 goto good

IF - Conditionally perform a command

IF will only parse numbers when one of (EQU, NEQ, LSS, LEQ, GTR, GEQ)
  is used. The == comparison operator always results in a string
  comparison.
IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64
An alternative and often better method of checking Errorlevels is to
  use the %ERRORLEVEL% variable:
IF %ERRORLEVEL% GTR 0 Echo An error was found
IF %ERRORLEVEL% LSS 0 Echo An error was found

IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found

Source IF - Conditionally perform a command

Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*if - Conditionally perform a command.


text:
Q: Best practices when manually connecting to various wifi networks How do we manage wireless connections without a network manager?
This excellent answer walked me through connecting to the protected wireless network at home. In short,
nano /etc/network/interfaces  # enable dhcp
service networking start
nano /etc/wpa_supplicant.conf  # indicate ssid and password
ifdown wlan0  # name determined by 'ip a show'
ip a flush wlan0
ifup wlan0
wpa_supplicant -Dnl80211 -c /root/wpa_supplicant.conf -iwlan0 -B
dhclient wlan0

Another answer suggests adding this to /etc/network/interfaces:
auto wlan0
iface wlan0 inet static
address ASSIGNED_IP
netmask 255.255.255.0
gateway THE_GATEWAY
wireless-essid YOURSSID
wireless-key WIRELESSKEY_HERE

Because over time I will be encountering different networks, with different ssdi and password, I was wondering which would be the best way to approach this, without a network manager. Priorities:

*

*Don't disclose ssid and passwords if my laptop is compromised - those are sensitive information that people have entrusted me with.

*Don't clutter /etc with a ton of custom(user-created) files.

*Don't use high-level utilities, like network-manager or wicd.

A: To accomplish the conditions:

Don't disclose ssid and passwords if my laptop is compromised - those are sensitive information that people have entrusted me with.
Don't clutter /etc with a ton of custom(user-created) files.
Don't use high-level utilities, like network-manager or wicd.

You should run wpa_supplicant as follows:
wpa_supplicant -B -Dnl80211 -iwlan0 -c<(wpa_passphrase "Your-SSID" Your-Passwd)
dhclient wlan0

You don't need to create a wpa_supplicant.conf .
You don't need to store your SSID and Password under /etc/network/interfaces
You don't need Network-manager , wicd ...
to correctly connect through wpa_supplicant (If you have the NetworkManager installed) , you should stop the NetworkManager.service before runing the wpa_supplicant command:
systemctl stop NetworkManager.service
systemctl disable NetworkManager.service


text:
Q: Galois representation associated to a modular form is crystalline iff... I am looking for the reference for the following fact (used, for example, in the proof of theorem 4.4. in Breuil's expose about local-global compatibility at Bourbaki):
For $f$ a modular cuspidal form of weight $k \geq 2$, let $\rho _f$ be the associated Galos representation and  let $\pi _p (\rho _{f, |Gal(\overline{\mathbb{Q}} _p/\mathbb{Q}_p)})$  be the smooth representation associated to $\rho _f$ by the Local Langlands correspondance. Then $\rho _{f, |Gal(\overline{\mathbb{Q}} _p/\mathbb{Q} _p)}$ is crystalline iff
$  \pi _p (\rho _{f, | Gal(\overline{\mathbb{Q}} _p / \mathbb{Q} _p)}) ^{GL_2(\mathbb{Z} _p)}$ is non-zero.
Additional question: does there exist a generalisation of this fact? For instance, to the totally real setting?

A: As Keerthi writes in his comment above, this follows from T. Saito's results.  The statement in one direction, that non-trivial $GL_2(\mathbb Z_p)$-invariants implies that the associated $p$-adic Galois rep'n is crystalline at $p$, is in fact easier, and goes back to Scholl, and in principle goes back further than that.  The point is that modular curves, and the universal elliptic curves over them, have good reduction at $p$ when $p$ doesn't divide the level, and the Galois representations appearing in the $p$-adic etale cohomology of a good reduction variety are crystalline.  (As Arno Kret observes, there are technical issues related to the non-compactness of modular curves, but these were essentially resolved by Deligne already in his Bourbaki seminar on the construction of Galois rep's for modular forms, and were treated carefully by Scholl in his paper on motives attached to modular forms.)
The statement in the other direction is more difficult, because one has to show that ramified-at-$p$ modular forms give rise to Galois representations which are non-crystalline; Saito proves this (in fact he proves a much more precise local-global compatibility result).
These results all extend to the Hilbert modular case.  In most cases, the Galois representations can be constructed directly from $p$-adic etale cohomology, and then the same geometric arguments apply (on Shimura curves now, rather than modular curves).  (I think that Saito has a paper specificallly dealing with this.)  In those situations for which the Galois representations are not constructed geometrically, but instead by a $p$-adic limiting process, one can still deduce these kinds of local-global compatibility-at-$p$ arguments in various ways.  There is an eigenvariety argument due to Chenevier, which is written up in a paper of his, and in a joint paper of his and Harris.  I think there are also arguments by Kisin, by Skinner, and by T. Liu.  (I hope that commmenters will clarify or correct this list if it is incomplete or otherwise in error.)
One caveat: without chasing references, I'm not sure whether one can show that the monodromy operator is non-trivial in these limiting cases when it should be (the monodromy operator is hard to keep track of in arguments via $p$-adic families), so it may be that in these cases, when $\pi_v$ is Steinberg for a prime $v$ above $p$, one doesn't know whether the Galois representation is semi-stable but non-crystalline (as it should be) rather than crystalline.
(Perhaps someone can comment on this.)
Also, Ana Caraiani has introduced a geometric method which pins down the monodromy operator in these limiting cases (and with $GL_2$ replaced by $GL_n$).  Her results at the moment only cover primes $v$ not dividing $p$, but it seems likely that she will be able to extend them to the case of $v$ dividing $p$.
In general, to see the state of the art on such local-global compatibility results at primes dividing $p$ (for $GL_n$, not just $GL_2$), you should look at the recent preprints on this topic by Barnet-Lamb--Gee--Geraghty--Taylor, available on Taylor's web-site.  The general statement is given by Theorem A of the second preprint.  (The assumption about Shin regular weight appearing in that result is what would be removed by the generalization of Caraiani's work to the case $v$ divides $p$ mentioned above.)


text:
Q: When to use "A" before a proper noun? I wonder if we can put "A" before a proper noun. Here's an example I found on Google:

As a Vietnam veteran I remembered that it was 16 years after my tour in Vietnam.

I wish to know why the author use "A" before "Vietnam." Thanks.

A: In this case Vietnam is descriptive, sometimes called  'a restrictive appositive' or, better, a 'noun adjunct.'(thanks Mari-Lou A) which includes appositives and attributives.
Here are some other examples:

A George I Penny.
  An Easter Island statue.
A Burns supper with a piper and haggis.

It is better to think of the "A" going with "veteran" and the descriptor coming in between the two.


text:
Q: How to update Terraform state without apply changes the scenario is:

*

*I have 1 repository with many terraform files including IAM, Instances etc

*I have to split this repository in two (IAM configs will migrate to another repository that stores terraform state in another bucket)

So I want update the state for this new repository adding the IAM configs state and delete IAM state from the older repository but I don't want to apply changes in my infrastructure because I would have to delete all configurations from older repository and then create all again.
Is there any way to update state without apply changes?

A: The best way would be to create the new repositories that each hold new state files.
Let's say the resources created from you old repo are stored in a state called "repo1.tfstate". Then you create a new repo where you want some stuff that is split from repo1 here. You could then use terraform import to import resources into repo2. Don't forget to remove the resources you just imported from repo1 with terraform state rm.
Another way would be to do a terraform state pull > state-for-repo-2.tfstate, edit that manually, put it into repo2 and do a terraform state push. Of cause, you would have to edit the state for repo1 as well. But be aware that terraform state push will overwrite the original state file...


text:
Q: Spring Kafka bean return types The documentation for spring kafka stream support shows something like:
@Bean
public KStream<Integer, String> kStream(StreamsBuilder kStreamBuilder) {
    KStream<Integer, String> stream = kStreamBuilder.stream("streamingTopic1");
// ... stream config
    return stream;
}

However, I might want a topology dependent on multiple streams or tables. Can I do:
@Bean
public KStream<Integer, String> kStream(StreamsBuilder kStreamBuilder) {
    KStream<Integer, String> stream1 = kStreamBuilder.stream("streamingTopic1");
    KStream<Integer, String> stream2 = kStreamBuilder.stream("streamingTopic1");
// ... stream config
    return stream;
}

In other words, is the bean returned relevant, or is it only important that kStreamBuilder is being mutated?

A: It depends.
If you don't need a reference to the KStream elsewhere, there is no need to define it as a bean at all you can auto wire the StreamsBuilder which is created by the factory bean.
If you need a reference, then each one must be its own bean.
For example, Spring Cloud Stream builds a partial stream which the application then modifies. See here.


text:
Q: How do you denote the statements $(*)$ and $(**)$ using set notation? I know that if $a$ is an element of the set $A$ then this is denoted as $a\in A$. This is for all elements $a$ and for all sets $A$. If, however, $a$ is not an element of $A$, then this is denoted as $a\notin A$. The same applies if a set $B$ is contained within $A$, denoted as $B\subset A$ or $A\supset B$. And if the contrary, then $B\not\subset A$ or $A\not\supset B$.
If we have the set of elements $\{x, y, z\}$ that are common to both $A$ and $B$, then this is denoted as $\{x, y, z\} = A\cap B$. If the contrary, then this is denoted as $A\Delta B$. If we want to combine both sets together to form a new set $C$ with all of its elements either members of $A$ or $B$, then this is denoted as $C = A\cup B$.
What if $(*)$ $A$ had $n$ elements and $m$ of its elements were also in $B$ for some $0 < m < n$ then how do we write this? How would we write $(**)$ the contrary? By $(**)$, I mean how to denote if $A$ had $n$ elements and $m$ of its elements were not in $B$. I know that if $m = n$ then $(*)$ is denoted as $A = B$ or $A\leftrightarrow B$ or $A\subset B$ depending on the value of $m$, what elements are in $A$ and $B$, and how many elements are in $B$. If on the other hand $m = 0$, then this is denoted as $A\cap B = \varnothing =$ the empty (null) set. This makes $A$ and $B$ disjoint sets.
But if $0<m<n$ then how do we denote $(*)$ and $(**)$ using set notation? Would we just write $\{\ldots\} \subset B$ of some sort? I am not aware of a possible duplicate of this question.
Thank you in advance.

A: (*) $A$ has $n$ elements and $m<n$ of them are in $B$: $|A\cap B| = m$.
(**) $A$ has $n$ elements and $m<n$ of them are NOT in $B$: $|A\setminus B| = m$.
If you meant something else by "the contrary", please let me know!
EDIT: If, by "the contrary", you meant that $m<n$ elements of $A$ are in $A\Delta B$, then $|A\Delta B| \geq m$. You can write $A\setminus B \subset A\Delta B$ with $|A\setminus B| = m$. Or, if you mean that there are $m$ elements total in $A\Delta B$, this can obviously be written $|A\Delta B| = m$.


text:
Q: How do you create an index for unique variables in sas? I am trying to combine the odds ratios outputted from two models with different adjustments in SAS:
i.e:
ods output oddsratios=adjustedOR1(rename=(OddsRatioEst=OR1);
 proc logistic data=dataname;
      model y= b d c a e; run;

ods output oddsratios=adjustedOR2 (rename=(OddsRatioEst=OR2);
 proc logistic data=dataname;
      model y= b d c; run;

proc sort.....
data Oddsratios (keep=Effect OR1 OR2);
merge adjustedOR1 adjustedOR2; by effect; run;

Problem is that if I sort and merge by the Effect variable, I lose the order in which I put the explanatory variables in the model.
Is there anyway to assign an index to the variable according to the order I put it in the model, so that the final table will have the effect column in the order: b d c a e?
Thanks for your help

A: I think the easiest way to sort your data is to do the merge in Proc Sql and use a case statement in an 'order by' clause. Here is an example.
ods output oddsratios=adjustedOR1(rename=(OddsRatioEst=OR1));
 proc logistic data=sashelp.class;
      model sex= height age weight; run;

ods output oddsratios=adjustedOR2 (rename=(OddsRatioEst=OR2));
 proc logistic data=sashelp.class;
      model sex= height age; run;

proc sql;
create table Oddsratios as select
a.effect,
a.or1,
b.or2
from    adjustedOR1 as a
            left join
        adjustedOR2 as b
            on a.effect=b.effect
order by
    case a.effect
        when 'Height' then 1
        when 'Age' then 2
        when 'Weight' then 3
    end;
quit;

A: I suggest creating a new sequence variable in your "primary" dataset with the sort order you want. then re-sorting the merged result by that variable:
data adjustedOR1;
   set adjustedOR1;
   sortkey = _n_;
run;
proc sort data=adjustedOR1;
   by effect;
run;
proc sort data=adjustedOR2;
   by effect;
run;
data Oddsratios (keep=Effect OR1 OR2 sortkey);
   merge adjustedOR1 adjustedOR2;
      by effect;
run;
proc sort data=Oddsratios;
  by sortkey;
run;

This would be a bit more generic than hard-coding the sort sequence as Keith suggests using PROC SQL (which also works by the way).
And thanks to Keith for providing a practical example!

A: If you want to just change the order in which the variables appear in the data set, you can use the retain statement:
data Oddsratios (keep=Effect OR1 OR2);
 retain b d c a e;
 merge adjustedOR1 adjustedOR2;
 by effect;
run;

This isn't really what retain is for, but it works.
But I wonder why you care what the order of the variables in the data set is. You can specify the order when you display results with proc print, for example.

A: Simplest answer I think that is still fairly flexible is to create an informat from your original dataset.  Then during the merge you can create a new variable with the numeric order variable and sort by that afterwards.
Another solution would be to merge in a fashion not requiring a sort - create a hash table, for example, or create a format out of the odds ratio 2 dataset and append it on in a simple data step rather than via merge.
data have;
input effect $;
datalines;
b
d
c
a
e
;;;;
run;

data for_format;
set have;
fmtname='EFF';
type='j';
hlo='s';
start=effect;
label=_n_;
keep hlo type fmtname start label;
run;

proc format cntlin=for_format;
quit;

proc sort data=have;
by effect;
run;

data want;
set have; *your merge here instead;
by effect;
eff_order=input(effect,$EFF.);
run;

proc sort data=want;
by eff_order;
run;
proc print data=want;
run;


text:
Q: Plone - Cannot untick "Inherit permissions from higher levels" On the sharing tab of any Folder or File, I can untick "Inherit permissions from higher levels", but when I click save, it does not stick.
I do not want my SalesGroup to have access to or even see the name of my ManagementFolder.
Plone 4.3.1 running on Windows. I have tried logging into Plone as admin & a folder owner. I have also tried from multiple browsers.


text:
Q: Returning a value from a stored procedure after value has been used in an If statement I have a simple MSSQL stored procedure that should query a table and return a value.
I have added an IF Statement after my SELECT to perform an action should a match be made. However this IF Statement is preventing the @countrycode value from being returned.
So my question is, how do I return the @countrycode value whilst still performing the IF action?
Please feel free to suggest a more elegant method.
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @countrycode VARCHAR(10)

-- Insert statements for procedure here
SELECT @countrycode = countrycode FROM tblIpLocation WHERE ipnumber = @ipnumber

-- Perform action if countrycode is found
IF @countrycode is null
    PRINT 'Nothing found'
ELSE
    -- Increment the positivequerycount column in the same row from which the countrycode was made
    UPDATE tblIpLocation
             SET positivequerycount = positivequerycount + 1
             WHERE ipnumber = @ipnumber

END

A: Thanks Dan Guzman, you got me on the right track.
I had tried the following to return the value...
SELECT @countrycode

However, of course it needs to be...
SELECT @countrycode AS countrycode

The final solution is..
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @countrycode VARCHAR(10)

-- Insert statements for procedure here
SELECT @countrycode = countrycode FROM tblIpLocation WHERE ipnumber = @ipnumber

-- Perform action if countrycode is found
IF @countrycode is null
    PRINT 'Nothing found'
ELSE

    -- Increment the positivequerycount column in the same row from which the countrycode was made
    UPDATE tblIpLocation SET positivequerycount = positivequerycount + 1 WHERE ipnumber = @ipnumber

    SELECT @countrycode AS countrycode

END
Thanks for your help


text:
Q: Canceling a custom drag function when mouse slides off div I have a draggable function in jquery to make it so I can drag and move elements on a div. Sometimes, when dragging the mouse comes off the div and I am not able to put back down the element.
I'm trying to add a keydown event for the escape button or something so that when pressed, the same thing happens on .on("mouseup", function(event) {
I've tried doing .on("mouseup keydown", function(event) { but it doesn't catch any keys that are being pressed.
Does anyone have any ideas on how I can cancel the drag? Either by a keydown or even on a mouseup regardless of if the mouse is on the div or not that is being dragged?
Just to be clear, the problem I am having is sometimes I will be dragging the element, I will mouseup but the mouse wasn't on the element when mouseup was called. Therefore, the element is still dragging and I no longer have my finger on the mouse and I have no way to stop the element from dragging to get it back on the document.
EDIT: Here is a jsfiddle, notice I am trying to get this to work on a scaled container. youtube video showing drag glitch
(function($) {
    $.fn.drags = function(opt, callback) {
        opt = $.extend({
            handle: "",
            cursor: "move"
        }, opt);
        if (opt.handle === "") {
            var $el = this;
        } else {
            var $el = this.find(opt.handle);
        }
        return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
            if (opt.handle === "") {
                var $drag = $(this).addClass('draggable');
            } else {
                var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
            }
            var z_idx = $drag.css('z-index'),
                drg_h = $drag.outerHeight(),
                drg_w = $drag.outerWidth(),
                pos_y = $drag.offset().top + drg_h - e.pageY,
                pos_x = $drag.offset().left + drg_w - e.pageX;
            $drag.css('z-index', 1000).parents().on("mousemove", function(e) {
                $('.draggable').offset({
                    top: e.pageY + pos_y - drg_h,
                    left: e.pageX + pos_x - drg_w
                }).on("mouseup", function() {
                    $(this).removeClass('draggable').css('z-index', z_idx);
                });
            });
            e.preventDefault();
        }).on("mouseup", function(event) {
            if (opt.handle === "") {
                $(this).removeClass('draggable');
            } else {
                $(this).removeClass('active-handle').parent().removeClass('draggable');
            }

            if (typeof callback == 'function') {
                alert("this is a callback");
            }

        });
    }
})(jQuery);

A: Here are a few things that might work:
Instead of listening for mouseup on the target element, listen for it on document.body. That way it will fire regardless of if the cursor is over the dragged element.
If you want to cancel the drag when the cursor wanders out of the page, add an event listener for mouseleave on document.body and use it to cancel the drag.
If you make a code-pen (or similar) test case, I will be happy to dig into the code.
Edit__
Handling mouseleave on the document prevents it from getting stuck in a draggable state. It also fixes the multiplied movement that you were seeing.
$(document.body).on('mouseleave', function(){
    $el.removeClass('draggable').css('z-index', z_idx);
});

Edit2__
Previous JSFiddle was incorrect.
https://jsfiddle.net/spk4523t/6/


text:
Q: Why my android foreground service has been killed automatically in some Device like (Vivo,Oppo,Mi,Oneplus) after 5 minutes I create background and foreground service both to get android location on every Interval and send it to server.
When App is in foreground at that time service run fine but when app is in background my foreground service notification display perfect for few minutes after some time it automatically killed my service and I am not getting any location update after that.
It runs fine in Samsung device but create issue in Oppo,Vivo, Mi and OnePlus device
So please help me out to find best way to run Location service when app is closed, background or foreground in any state in all device and Android version greater Than "O"
Thanks in Advance


text:
Q: Lag spikes since upgrading to Windows 10 EDIT: Sorry for not mentioning earlier: I've tried reducing the roaming sensitivity to no avail. I also fiddled with my router settings, which rendered it unusable for a short time before I reset the defaults.
I've been getting nasty lag spikes ever since I upgraded from Win7 to Win10 about 2 weeks ago. They are most noticeable during multiplayer gaming (since everything sort of locks up or stutters), but I'm sure that it's happening all the time.
The spikes happen one or two minutes apart, and last for about 3 seconds each.
I've tried looking for a solution, but nobody seems to even know where the problem is coming from, so I installed MS Network Monitor and set up a constant ping to www.google.com to try and catch the culprit. These were my findings:
Pinging Google once every second, printing the timestamp of each ping. Here you'll notice a sudden spike in response time (from 65ms to 500+). After the spike, it settles back down to 65ms.

Monitoring network traffic. Using the timestamp data from the ping command, I was able to isolate the network activity that was occurring during the spike. You'll notice that most of the traffic during those 3 seconds is related to wifi probe responses and wifi beacons.

(Click image to enlarge)
I've done this test a few times, with no other network intensive programs running, and it's always this same group of network activities that happen during the lag spikes.
This didn't happen on Windows 7, so I think my router is not the problem. I have no idea what probes or beacons are. I see wifi hotspot names in the list, so I'm guessing that this is Windows trying to keep the list of hotspots up to date, but I don't understand why it has to lock up my connection when doing so.
If there is a way to delay this process, so that it doesn't happen every couple of minutes, that would be great. Ideally though, I'd like to fix it all together.


text:
Q: Explanation of $\int_0^{2\pi}\sin^{100}x\,dx$. I was browsing this thread when I came across this answer. I can neither make heads nor tail of it. Can someone help me understand it?
This I understand:
$$\int_0^{2\pi}e^{ikx}\,dx=\left\{\begin{array}{cl}0&k\ne0\\ 2\pi&k=0\end{array}\right.,$$
But how does he get this? Where does the summation come from?
$$\int_0^{2\pi}\sin^{100}x\,dx=\frac1{2^{100}}\sum_{k=0}^{100}\binom{100}{k}\int_0^{2\pi}e^{ikx}(-1)^{100-k}e^{-i(100-k)x}\,dx=\frac{\binom{100}{50}}{2^{100}}2\pi.$$
EDIT: The answer is so obvious...I can't believe I didn't notice it! I kept expanding $\sin^{100}(x)$ as $\frac{1}{2i} (e^{100ix} + e^{-100ix})$ which got me nowhere.

A: We have
$$\sin x=\frac1{2i}(e^{ix}-e^{-ix})$$
so by the binomial formula we get
$$\frac1{2^{100}}\sum_{k=0}^{100}(-1)^{100-k}\binom{100}ke^{kix}e^{-ix(100-k)}$$
so
$$\int_0^{2\pi}\sin^{100}xdx=\frac1{2^{100}}\sum_{k=0}^{100}(-1)^{k}\binom{100}k\underbrace{\int_0^{2\pi}e^{(2k-100)ix}dx}_{=2\pi\;\text{only for}\; k=50}=\frac{2\pi}{2^{100}}\binom{100}{50}$$

A: Hint: Using the binomial theorem
$$\sin x=\frac{e^{ix}-e^{-ix}}{2i}\implies \sin^{100}x=\frac1{2^{100}}\sum_{k=0}^{100}\binom{100}ke^{kix}e^{-ix(100-k)}\;\ldots$$

A: Write
$$
\sin x = \frac{e^{ix} - e^{-ix}}{2i}
$$
Then
$$
\sin^{100} x  = \frac{(a + b)^{100}}{2^{100}}
$$
where $a = e^{ix}$ and $b = -e^{-ix}$.
Now use the binomial theorem:
$$
(a + b)^{100} = \sum_{k=0}^{100}\left( \begin{array}{c} 100 \\ k \end{array}  \right) a^k b^{100-k}
$$
and the first summation step in the formula you were puzzled about you give falls out.
And then in that integral,  only the term where the factor in front of $x$ in the exponent gives a non-zero integral.  So only the term with $k - (100-k) = 0$, or $k=50$, is non-zero. That is where the $\left( \begin{array}{c} 100 \\ 50 \end{array}  \right)$ comes from.


text:
Q: ion-datetime - set date without datepicker IONIC 3 I am using  with the built-in datepicker to create an event.
I would like to be able to dynamically set a date from another page, just like below using NavParams

<ion-datetime #dateTime displayFormat="DD MMM YYYY" pickerFormat="DD MMM YYYY" [(ngModel)]="date" ></ion-datetime>

I have tried as follows:
The AddTaskPage page is displayed from the CalendarPage
1- calendar.ts
 add(){
    this.navCtrl.push(AddTask, {'date': this.selected})
    console.log("AddTask")
  }

2 - add-task.ts
I pass the date using NavParams
export class AddTask {

  remindTimes = [10, 30, 60, 120, 160, 1440];
  locations: Location[] = [];
  title:string
  date:any
  selectedDate:string
  reminder:any
  isChecked:boolean = false
  @Output() saveItem = new EventEmitter<any>();
  @ViewChild('dateTime') addDateTime;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public popCtrl: PopoverController,
    private dataService: DataServiceProvider
  ) {
    if(this.navParams.get('date')) {

       this.date =  new Date(this.navParams.get('date'))
       this.selectedDate = moment(this.date).format('DD MMM YYYY');

       console.log(`date selected: ${this.date}`)
       console.log(`date selected: ${this.selectedDate}`)

    }
  }

3- [(ngModel)]="date"
I am using [(ngModel)] to update the UI (the Start date)
this is not possible to set date unless the date is selected with the datepicker.
Has anyone been able to force the  directive to display a date dynamically from an object and not from the datepicker ?
Any thoughts?
Thanks


text:
Q: One column of Azure SQL database appears sorted I have a SQL database in Azure as seen in the link below. I'm making an applet in python using pyodbc to update the Elos of the people in the database. I made three connection objects (one for each of the columns seen), and used a while loop to iterate through.
It'll take an input from the user, iterate until it finds the ID code entered, and since all the cursors are in the same while loop the Rating and Name cursors will always be in the same row.
https://i.stack.imgur.com/ZssyW.png
Except for some reason, the ID column is sorted. The table on the left is a screenshot from Microsoft Sql Server Management Server, and the one on the right is what happens when the three cursors iterate through and print each time.
How do I fix this/what's causing this?
Here's (the relevant part of) my code:
current_id = (ID_cursor.execute("SELECT LocalID FROM MEMBERS"))
current_rating = (rating_cursor.execute("SELECT Rating FROM MEMBERS"))
current_firstname = (firstname_cursor.execute("SELECT FirstName FROM MEMBERS"))

counter = 0
while counter < 10:
    counter += 1
    temp_id = ID_cursor.fetchone()[0]
    temp_rating = rating_cursor.fetchone()[0]
    temp_firstname = firstname_cursor.fetchone()[0]

    print(temp_id, temp_firstname, temp_rating)

print("end")

A: Apply an ORDER BY clause to all three queries so they are sorted the same way. I'm assuming LocalID is your primary key identity column?
current_id = (ID_cursor.execute("SELECT LocalID FROM MEMBERS ORDER BY LocalID"))
current_rating = (rating_cursor.execute("SELECT Rating FROM MEMBERS ORDER BY LocalID"))
current_firstname = (firstname_cursor.execute("SELECT FirstName FROM MEMBERS ORDER BY LocalID"))

Without an ORDER BY clause specified, SQL Server may order by the column in the SELECT statement.


text:
Q: Cuando usar metodo mongoClient.close() en controlador de node.js? Estoy usando el API nativo de Mongodb con Node.js. Para cada controlador, abro una conexion con await client.connect() la cual cierro al ejecutarse el query con await client.close().
Mi problema es que recibo un mensaje que dice:
MongoExpiredSessionError: Cannot use a session that has ended

Este error se da porque el metodo client.close() se ejecuta antes de que se ejcute el query.
Por ello, decidí eliminar el client.close() de mi función. Como resultado, ya no recibo ese error y mi codigo funciona como espero.
Sin embargo, me gustaría saber si mi solucion es correcta. Es decir, client.close() era inecesario. O bien, si usar client.close() es imprecindible, cual es la forma correcta de emplearlo.
Mi codigo se ve asi:
// db.js
//conectarse mongodb
require('dotenv').config()

const { MongoClient } = require("mongodb");

const uri = process.env.MONGO_CLIENT2;

const client = new MongoClient(uri)

module.exports=client

//este es el controlador en donde recibo el error
const client= require('../services/db')

getSits: async (req, res) => {
    try {
        const resolver = Resolver(res)
        await client.connect()

      const userSitPost =  await client.db('wkkerpark').collection('sits').aggregate([
         {

        $lookup:{
            from: 'users',
            localField: 'requiredBy',
            foreignField: '_id',
            as : 'user'
        } }
        ]).toArray()
        console.log('this is the agregation',userSitPost)
        resolver.success(userSitPost, 'all the sit post and the user info')
    }

    catch (error) {
        console.log(error)
    }
    finally{
        await client.close() //cuando elimino esta linea el error deja de ocurrir.
    }
},


text:
Q: Help me debug my SQL INSERT, please? I am pulling back some data from the twitter query API, and parsing it through PHP like so:
    $i =0;
    foreach ($tweetArray->results as $tweet) {
        $timeStamp = strtotime($tweet->created_at);
        $tweetDateTime = date('m-d-Y H:m:s', $timeStamp);
        if($i > 0){
            $SQL .= ',';
        }
        $SQL .= "(". $tweet->id .",'" . $tweet->from_user ."','". addslashes($tweet->profile_image_url) . "','". addslashes($tweet->text). "','" . $tweetDateTime ."')";
        $i++;
    }
    $SQL .= " ON DUPLICATE KEY UPDATE 1=1";

This leaves me with a SQL statement looking like this:
INSERT
    INTO
        tblTwitterSubmit (tweetId, twitterAuthor, authorAvatar, tweetText, tweetDateTime)
    VALUES
    (111,'name','http://url.com','a string of text','03-04-2011 13:03:09'),
    (222,'anothername','http://url.com','another tweet','03-04-2011 12:03:51')
ON DUPLICATE KEY UPDATE 1=1;

I am unfortunately getting the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1=1' at line 1.
Edit:
The 1=1 is supposed to not do anything. The tweets don't change, and so if I pull the same one back twice for any reason, nothing will happen, but it also won't throw a duplicate key error.
Re-edit:
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just make a bunch of submissions instead of one long sql string.
Hopefully this is better practice.
Leaving this open for a couple minutes hoping for some feedback if this is the way to do it or not.

A: The ON DUPLICATE KEY UPDATE requires a column name, something like this, assuming tweetId is the key column that's getting duplicates.
ON DUPLICATE KEY UPDATE tweetId=tweetId+1

Your 1=1 doesn't actually do anything.

A: Are you sure you're using the right syntax for on duplicate key update ?
Judging from it's manual's page, it seems you have to specify a column name, and not 1=1.

From what I understand, if you want to indicate "use the value from the values() clause when there's a duplicate", you should use something like this :
on duplicate key update your_col=values(your_col)

Quoting the relevant part :

You can use the VALUES(col_name)
  function in the UPDATE clause to
  refer to column values from the
  INSERT portion of the INSERT ... ON
  DUPLICATE KEY UPDATE statement.
  In other words,
  VALUES(col_name) in the ON
  DUPLICATE KEY UPDATE clause refers to
  the value of col_name that would be
  inserted, had no duplicate-key
  conflict occurred. This
  function is especially useful in
  multiple-row inserts.

Then, as a sidenote, you must escape your strings using the function that matches your API -- probably mysql_real_escape_string -- and not the generic addslashes, which doesn't know about the specificities of your database engine.

A: The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just


text:
Q: Overfull hbox from wrapfigure I'm trying to include a figure (a pdf chart) in my document and wrap around it, but it's giving me tons of overfull hbox errors. Here is the code:
\documentclass{article}

\usepackage{wrapfig}
\usepackage{graphicx}
\usepackage{lipsum}
\begin{document}

\lipsum[2]
    \begin{wrapfigure}{r}{0.6\textwidth}
        \centering
        \includegraphics[width=0.55\textwidth]{example-image-a}
        \caption{\label{fig:simpres}Residual values plot}
    \end{wrapfigure}\lipsum
\end{document}

I get all of these warnings:

They go away if I remove the wrapfigure part, but obviously then I lose the ability to wrap around the figure which is important here. Any ideas?

A: Two documents - the one shown as an example, and the one with all the overfull warnings.
The example code has an underfull box because you forced a line break with wrapfigure, by using it as part of the paragraph. Documentation of wrapfig, on page 2, says:

*

*It is convenient to begin the environment between paragraphs, but if you want placement in the middle of a paragraph, you must put the environment between two words where there is a natural line break.

If at all possible, put the environment between paragraphs (leave a blank line before it).
It has an overfull box because the nonsense

asdfasfasdfasfasdfasfasdfasfasdfasfasdfasfasdfasdfasdfasdfasdfasdf

is wider than the line and has no separate words.
Back to the original list of multiple warnings. Look at the document output pdf and see what formatting happened. See if there are big words or formulas that can't fit in the narrow portion of the text. The underfull warnings, especially, are to be expected in narrow columns. Using package "microtype" can help the typesetting in narrow columns. Also make sure you have the proper language selected for hyphenation.

A: Works fine with article class

\documentclass{article}

\usepackage{wrapfig}
\usepackage{graphicx}
\usepackage{lipsum}
\begin{document}

\lipsum[2]
    \begin{wrapfigure}{r}{0.6\textwidth}
        \centering
        \includegraphics[width=0.55\textwidth]{example-image-a}
        \caption{\label{fig:simpres}Residual values plot}
    \end{wrapfigure}\lipsum
\end{document}


text:
Q: sms broadcast receiver not call in api 26 until re-run application I have an application with SMS broadcast receiver , everything is working good but in android android api 26 after get android.permission.RECEIVE_SMS permission from user it's still has not permission until app restart at least one time . how can i solve this problem ?

A: I requested 4 dangerous permission in string array at same time . by placing sms permissions at first and second position of array my problem resolved


text:
Q: TypedParameter is not used if the type is already register I have an unexpected behavior of the TypedParameter in Autofac. It ignored if the type is already register and I don't know if is it correct or how to obtain the expected behavior. Example:
I have a Foo class with the following constructor.
public class Foo
{
    public Foo(IEnumerable<IRule> rules)
    {..}
}

I've already register a lot of rules inside the builder (scanning the assembly), but when I resolve, I would like to pass an Autofac TypedParameter with a custom list of IRules
TypedParameter iocParam = new TypedParameter(typeof(IEnumerable<IRule>), rules);
var result = container.Resolve(FOO, iocParam);

The problem here is Autofac is ignoring myCustomListOfRules and creating a list with all available IRules already register in first place, instead of using the TypedParameter.
If I use a NamedParameter:
 NamedParameter iocParam = new NamedParameter("rules", myCustomListOfRules);

works fine, but I have to hardcode the name of the parameter instead of resolve it by the type.
Is it correct the behavior of the TypedParameter or there is a way to use it as I want?
Update:
I was doing something else bad because the TypedParameter has the expected behavior. The following example works as expected.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Rule1>().As<IRule>();
            builder.RegisterType<Rule2>().As<IRule>();
            builder.RegisterType<Foo>();

            var resolver=builder.Build();

            // autofac resolve foo with all of available rules, ok¡
            var foo1=resolver.Resolve<Foo>();
            Console.WriteLine(foo1.GetNumberOfRules());

            // resolve with custom rules, ok¡
            var rules=new List<IRule>();
            rules.Add(new Rule1());
            TypedParameter param = new TypedParameter(typeof(IEnumerable<IRule>), rules);
            var foo2 = resolver.Resolve<Foo>(param);
            Console.WriteLine(foo2.GetNumberOfRules());

            Console.ReadLine();
        }
    }

    public class Foo
    {
        IEnumerable<IRule> rules;
        public Foo(IEnumerable<IRule> rules)
        {
            this.rules = rules;
        }

        public int GetNumberOfRules()
        {
            return this.rules.Count();
        }
    }

    public interface IRule
    {
    }

    public class Rule1 : IRule
    {
    }

    public class Rule2 : IRule
    {
    }
}


text:
Q: Possible to use ecommerce tracking to track multiple users for a single transaction? We're creating a flow for boarding new customers and would like to use the enhanced ecommerce tracking of universal analytics to track the boarding steps.
A single applicant fills in a form supplying information about their business and delivery addresses and such. The problem is that after the application has been submitted, the applicants need to electronically sign an agreement. There can be multiple people signing, and the person signing therefor doesn't necessarily need to be the same person that filled in the application. Is it possible to track a flow where another user/session takes over and finalizes the application?

A: If all participants in the application process sign in with a token - same token for all - you can set it as userID and enable session stitching - you'll need special userID view (and update your privacy policy) which will only show visits for which the userID was set and will recognize users across multiple computers, devices etc.
However this will still give you aggregated data only, so if you want to track individual users in addition to the flow you have to set the userID as a custom dimension (talk to your lawyer first, even with an anonymous ID profile building might be a privacy issue). The userID must contain nothing that would allow anybody but your own company to identify a specific user or device (no e-mail-addresses, no MAC addresses etc). Then you can pull the individual data with the custom dimension as key and match it with your CRM data.
No guarantees, but that seems the closest you can get to your requirements using GA.


text:
Q: PowerShell Script - Report specific string from filename I am currently trying to build a simple script that would report back a string from a filename
I have a directory full of files named as follows:
C:\[20141002134259308][302de103-6dc8-4e29-b303-5fdbd39c60c3][U0447744][10.208.15.40_54343][ABC_01].txt
C:\[20141002134239815][302de103-6dc8-4e29-b303-5fdbd39c60c3][U0011042][10.168.40.34_57350][ABC_01].txt
C:\[20141002134206386][302de103-6dc8-4e29-b303-5fdbd39c60c3][u1603381][10.132.171.132_54385][ABC_01].txt
C:\[2014100212260259][302de103-6dc8-4e29-b303-5fdbd39c60c3][U0010217][10.173.0.132_49921][ABC_01].txt

So, I'd like to extract from each filename the user ids that are identified starting with a letter U and  seven digits, then create a new txt o csv and have all these Ids listed. That's it.

A: As Patrice pointed out, you really should try and do it yourself and come to us with the relevant piece of code you tried and the error that you are getting. That said, I'm bored, and this is really easy. I'd use a regex match against the name of the file, and then for each one that matched I'd output the captured string:
Get-ChildItem 'C:\Path\To\Files\*.txt' | Where{$_.Name -match "\[(U\d{7})\]"} | ForEach{$Matches[1]}

That will return:
U0447744
U0011042
u1603381
U0010217

If you want to output it to a file, just pipe that to Out-File, and specify the full path and name of the file you want to save that in.