text:
Q: Changing cookie expiration with Laravel 4 I'm trying to change the expiration time of the remember me cookie when the user checks the option and logs in, but the expiration time doesn't change when I run this code. What do I need to do to fix this in Laravel 4?
More specifically what I want to do is set the expiration time to 12 hours. I tried the App:after method but every time that code runs, it refreshes the existing cookie back to the original 12 hours. How would I make it run so that it doesn't do that?
LoginController.php
class LoginController extends BaseController {

public function __construct()
{
    $this->beforeFilter('csrf', array('on' => 'post'));
}

public function getIndex()
{
    if (Auth::check()) {
        return Redirect::action('HomeController@usersIndex')
            ->with('message', 'You are already logged in.');
    }

    return View::make('guests.login');
}

public function postIndex()
{
    $validation = User::validateForm(Input::all());

    if ($validation->passes()) {
        $user = array(
            'username' => Input::get('username'),
            'password' => Input::get('password')
        );

        // Try to log the user in.
        if (Auth::attempt($user, Input::has('remember_me'))) {
            return Redirect::to('/');
        }

        return Redirect::to('login')
            ->withErrors(array('password' => 'The username or password you entered is incorrect.'))
            ->withInput(Input::except('password'));
    }

    return Redirect::to('login')
        ->withErrors($validation)
        ->withInput(Input::except('password'));
}

}

filters.php
App::after(function($request, $response) {
    if ( Auth::check()){
        $ckname=Auth::getRecallerName(); //Get the name of the cookie, where remember me expiration time is stored
        $ckval=Cookie::get($ckname); //Get the value of the cookie
        return $response->withCookie(Cookie::make($ckname,$ckval,720)); //change the expiration time
    }
});

routes.php
Route::get('/', 'HomeController@usersIndex');
Route::get('logout', 'HomeController@logout');

Route::controller('login', 'LoginController');
Route::controller('register', 'RegistrationController');
Route::controller('password', 'PasswordController');

A: You can use App::after method to change rememberme cookie expiration time.
so in your filters.php file find App::after() method and change the cookie expiration time. For example-
App::after(function($request, $response)
{
  if ( Auth::check()){
      $ckname=Auth::getRecallerName(); //Get the name of the cookie, where remember me expiration time is stored
      $ckval=Cookie::get($ckname); //Get the value of the cookie
      return $response->withCookie(Cookie::make($ckname,$ckval,360)); //change the expiration time
  }
});

From Discussion:
You: @Trying What I want to do is set the expiration time to 12 hours. I tried the App:after method but every time that code runs, It overwrites/refreshes back to the original 12 hours. How would I fix this?
Me: You can try setting session value in ur login method and thn check it in App::after method, the session value,
If it exists update the cookie and delete the session value,
If u do this it will only update the cookie once i,e when u login.
Example:-
Login code
if (Auth::attempt($user, Input::has('remember_me'))) {
   Session::put('key',value);
   return Redirect::to('/');
}

App after method
App::after(function($request, $response) {
    if(Session::has('key')){
    if ( Auth::check()){
        $ckname=Auth::getRecallerName(); //Get the name of the cookie, where remember me expiration time is stored
        $ckval=Cookie::get($ckname); //Get the value of the cookie
        Session::forget('key');
        return $response->withCookie(Cookie::make($ckname,$ckval,720)); //change the expiration time
    }
}
});


text:
Q: Считывание данных из файла через FileInputStream Имеется метод:
private void readFromFile(String path){
        FileInputStream fin = null;
        try {
            fin = openFileInput("fitnessApp/app/src/Articles/"+path+".txt");
            byte[] bytes = new byte[fin.available()];
            fin.read(bytes);
            String text = new String(bytes);
            textView.setText(text);
            fin.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Задача - считать данные из файла и поместить текст в textView. Для хранения файла создал специальный каталог, путь к которому в Android Studio

fitnessApp/app/src/Articles

Однако при выполнении выдает ошибку:

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{asus.example.com.fitnessapp/asus.example.com.fitnessapp.ArticleActivity}:
  java.lang.IllegalArgumentException: File
  fitnessApp/app/src/Articles/ten_ways.txt.txt contains a path separator
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
                        at android.os.Handler.dispatchMessage(Handler.java:106)
                        at android.os.Looper.loop(Looper.java:193)
                        at android.app.ActivityThread.main(ActivityThread.java:6669)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
                     Caused by: java.lang.IllegalArgumentException: File fitnessApp/app/src/Articles/ten_ways.txt.txt contains a path separator
                        at android.app.ContextImpl.makeFilename(ContextImpl.java:2526)
                        at android.app.ContextImpl.openFileInput(ContextImpl.java:559)
                        at android.content.ContextWrapper.openFileInput(ContextWrapper.java:202)
                        at asus.example.com.fitnessapp.ArticleActivity.readFromFile(ArticleActivity.java:49)
                        at asus.example.com.fitnessapp.ArticleActivity.onCreate(ArticleActivity.java:31)
                        at android.app.Activity.performCreate(Activity.java:7136)
                        at android.app.Activity.performCreate(Activity.java:7127)
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)

В чем проблема? При вызове метода полный путь не передаю, а передаю только название файла, например ten_ways

A: У тебя два раза расширение файла *.txt повторяется. В переменной path имя содержится уже с расширением видимо. Попробуй вот так:
openFileInput("fitnessApp/app/src/Articles/"+path)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating Content Blocks with Different Types Disclaimer: I'm a PHP developer and am somewhat new to Rails.
I am working on an application which requires me to create blocks of content. There are different types of blocks but they do share common elements (Title, Location). The issue I'm having a hard time wrapping my brain around is the fact that each block could have its content defined in a different way.
For example:
Content Block (content) - This block stores html entered in by a user, so it would get its data pulled from a database.
Calendar Block (calendar) - This block displays a listing of events, so it would need to render a view
Integration Block (integration) - This block is an example of a third party integration block. It may get its data by parsing a json feed and rendering it in a particular way.
So my thought was maybe to create each of these block types as a module or plugin that registers a block type and provides info as to how and where to get that data. Similar to how Drupal's hook system works. I'm struggling to figure out a smart way to architect this. There could, in theory be an unlimited amount of block types and I want to make sure I can keep this code base modular and organized.
Any insight is greatly appreciated.

A: You could use the strategy pattern:
Assume you get some data from the db such as:
block_content_from_db = [
  { block_type: "Content", content: "some html", ...any other attributes... },
  { block_type: "Calendar", content: "appointment data", ...any other attributes... },
  { block_type: "Integration", content: "integration data", ...any other attributes... }
]

And you implement each block type and a superclass:
class Block
  def initialize(block_data)
    @block_data = block_data
    @renderer = Blocks.const_get "#{block_data[:block_type]}Block"
  end

  def render
    @renderer.new(@block_data).render
  end
end

module Blocks
  class ContentBlock < Block
    def initialize(block_data)
      @block_data = block_data
    end

    def render
      "Rendered ContentBlock: #{@block_data[:content]}"
    end
  end

  class CalendarBlock < Block
    def initialize(block_data)
      @block_data = block_data
    end

    def render
      "Rendered CalendarBlock: #{@block_data[:content]}"
    end
  end

  ... and so on ...
end

Then, to render all block_content_from_db:
block_content_from_db.each do |block_data|
  Block.new(block_data).render
end

# => "Rendered ContentBlock: some html"
# => "Rendered CalendarBlock: appointment data"

Now when you want to add an a new block type just subclass from Block again and define a render method that accepts content from the db to use in rendering. The content can be anything that block type needs.
You don't necessarily need to subclass from Block either, just if you want to share common methods between subclasses.
By putting the subclasses in the Blocks module we're simply namespacing them so we can later do Blocks.constants and get a list of all implemented block renderers and, say, use that in a dropdown menu in the UI for creating new block_content_from_dbs.


text:
Q: How to select specific rows from buttons created in a for loop? I have created a grid of buttons using a for loop (much more efficient for it's purpose), however I want to be able to say that for example, if any button on the second row is chosen, it will have a different command to if a button on the first row was chosen.
    curDay = 1

    for i in range(35):
        if len(rows[0].slaves()) == 7:
            rows.pop(0)
        temp = ButtonsWrap(rows[0], curMonth,curDay,text='',height=1,width=2)
        temp.button.pack(side='left')
        buttons.append(temp)
        if curDay <= months[curMonth]:
            temp.button.config(text=curDay,command=lambda:[f() for f in[lambda: bid(i),temp.popup]])
            curDay += 1

        def bid(self):
            print(i)

This is where the buttons are created, if that helps anyone identify how to get what I'm after.
A better alternative would be to print the number of the button that is chosen, but I'm not sure if that's possible due to the text of the buttons never being constant in the loop.

A: This should work:
def makeCalendar(blank):
    curMonth = int(dropMonths.get())

    for i in buttons:
        if i.thing:
            i.thing.destroy()
    for i in newFrame.slaves():
        i.destroy()

    rows = [Frame(newFrame) for i in range(5)]
    [i.pack() for i in rows]

    curDay = 1

    for i in range(35):
        if len(rows[0].slaves()) == 7:
            rows.pop(0)
        temp_button = ButtonsWrap(rows[0], curMonth, curDay, text='', height=1,
                           width=2)
        temp_button.button.pack(side='left')
        if curDay <= months[curMonth]:
            temp_button.button.configure(text=curDay, command=lambda TMP=i: bid(TMP))
            curDay += 1

        buttons.append(temp_button)

def bid(i):
    print(i)

And your code very hard to read, but that is not about your question.


text:
Q: Making multidimensional lists in python This question maybe asked earlier (atleast topic wise) , but still I couldn't find a solution for my specific problem. Basically, I need a multidimensional array in python. Such that:
I will be able to access contents in list by :
contenets[no_of_record][record].

So I have a file like :
101, Mrs. Jones' Math Class, 10100000001, Jones, Barbara, , , , 10100000011, Gutierrez, Kimberly, 2
101, Mrs. Jones' Math Class, 10100000001, Jones, Barbara, , , , 10100000013, Mercado, Toby, 1
101, Mrs. Jones' Math Class, 10100000001, Jones, Barbara, , , , 10100000014, Garcia, Lizzie, 1
101, Mrs. Jones' Math Class, 10100000001, Jones, Barbara, , , , 10100000015, Cruz, Alex, 1

Now I have to maintain a multi dimensional array where no_of_record points to row number and the record will be the column number.
I want something similar to this:
contents=[][]

for lines in source_file:
                contents[no_of_records][]=lines.rstrip().split(',')
                print contents[no_of_records]
                no_of_records+=1

I am sure the snippet above is syntactically wrong, I am just trying to give an idea of what im searching for. Thanks for your help.
-Sethu

A: from the csv examples of the doc you should do something along the lines
import csv
rows = []
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row
        rows.append(row)

A: If you really want a list of lists you can do it with this:
contents = [l.split(',') for l in fh] # fh is a file handle here.

There's no good reason not to use the csv module if you're actually working with a csv file though.

A: Use a single list, but populate it further using list objects.
contents = []
for i, line in enumerate(source_file):
    contents.append(line.rstrip().split(','))
    print contents[i]

It looks like you're parsing a csv file, though. I'd suggest using the csv module in stead.

A: You can also do it with dicts, which may be better, if you want to use something other than numbers for the indices.
contents = []
tmp_rcd = {'classnum': 101, 'classname': "Mrs. Jones' Math Class", ...}
contents.append.tmp.rcd
...
print contents[i]['classname']


text:
Q: How do I solve the BSOD that appears during my Windows install? In my Core i5 desktop machine I tried to install windows 7 32 bit Ultimate. I received blue screen of death while installing OS. Earlier I had was 64 bit Windows vista which was working fine but now i cant install any of OS.
When I try to re-install OS again same error screen pops up? how can I fix this ? I have 4GB of RAM installed does it have problems with 32 bit OS.
When I install second OS I didn't reformat the entire hard disk.

A: 32 bit Windows operating systems will only recognize the first 3gb of ram but having more won't hurt it.
Between 64 and 32 bit installs did you reformat and repartition the drive you're using for the install?

A: I tried installing OS with external DVD drive I could install the Windwos 7 Ultimate 64 bit edition and it seems to work fine upto now. Some sort of fault in my DVD drive or the DVD drive doesn't recognize by windows OS setup is suspected.

A: The only time I've had BSoD errors during a Windows install was when there were third-party SCSI/RAID drivers that needed loading.  I would not expect this for a Windows 7 install on a system that previously ran Vista, but it may be something to look up.
Other than that, the only things I've known likely to cause BSoDs since XP, which would also apply during the install process, are faulty hardware components.  CPU, RAM, and Motherboard are the big three "usual suspects" in these cases.

A: Go into your BIOS and see if there is anything about "SATA Operation" or "SATA Mode."  Change it to "ATA mode," if it is currently on "RAID" or "IRRT" mode.  Once it's installed, try switching it back.


text:
Q: LinQ to SQL data insert issue I have two tables Settlement and Violations.SettlementID is primary Key in Settlements  table and foreign key in Violations.
In my dbml file I dragged and dropped both the tables and the association is set.
In my VB.net code when I try to insert records into db it is not giving option to add values Violation collection into Settlements
I am trying to read an xml file with Settlements and Violation and insert into SQL. But only Settlement table is getting inserted with records.
I am not able to add _v to settlement s as it is not listed.
Please help
Dim Orders As XDocument = XDocument.Load("c:/inetpub/violations.xml")

    Dim _Orderss = violations.<Collections>.<Settlement>

    For Each _settlement In _settlements
        Dim s As New Settlement

        s.CamisID = _settlement.<CamisID>.Value
        s.DocketID = _settlement.<DocketID>.Value
        s.RespFName = _settlement.<RespFName>.Value
        s.RespMName = _settlement.<RespMName>.Value
        s.RespLName = _settlement.<RespLName>.Value
        s.DispDate = Date.Parse(_settlement.<DispDate>.Value)

        Dim _violations = _settlement.<ViolationList>.<Violation>

        For Each _violation In _violations
            Dim _v As New Violation

            _v.DocketID = _settlement.<DocketID>.Value
            _v.ViolationInfo = _violation.<ViolationInfo>.Value
            _v.violationCD = _violation.<ViolationCd>.Value
            _v.Severity = Integer.Parse(_violation.<Severity>.Value)
            _v.Point = Integer.Parse(_violation.<Point>.Value)
            _v.Occurence = Integer.Parse(_violation.<Occurence>.Value)

        Next
        _db.Settlements.InsertOnSubmit(s)
        _db.SubmitChanges()
    Next

A: You need to set the parent property of each child instead of adding children to the parent.
Can you try to set the Settelment property of each _v instead of adding the violations to the settlement?
For Each _settlement In _settlements
    Dim s As New Settlement

    s.CamisID = _settlement.<CamisID>.Value
    s.DocketID = _settlement.<DocketID>.Value
    s.RespFName = _settlement.<RespFName>.Value
    s.RespMName = _settlement.<RespMName>.Value
    s.RespLName = _settlement.<RespLName>.Value
    s.DispDate = Date.Parse(_settlement.<DispDate>.Value)

    Dim _violations = _settlement.<ViolationList>.<Violation>

    For Each _violation In _violations
        Dim _v As New Violation

        _v.DocketID = _settlement.<DocketID>.Value
        _v.ViolationInfo = _violation.<ViolationInfo>.Value
        _v.violationCD = _violation.<ViolationCd>.Value
        _v.Severity = Integer.Parse(_violation.<Severity>.Value)
        _v.Point = Integer.Parse(_violation.<Point>.Value)
        _v.Occurence = Integer.Parse(_violation.<Occurence>.Value)
        _v.Settelment = s
        _db.Violations.InsertOnSubmit(_v)
    Next

    _db.Settlements.InsertOnSubmit(s)
    _db.SubmitChanges()

Next


text:
Q: vscode installed in other directory gives access denied error I recently reinstalled my windows 10
For easy software management I chose to install all my software in the following directories:

*

*C:\Program Files\

*C:\Program Files (x86)
This meant installing vscode and vscode-insiders on the C:\Program Files\
instead of the default C:\Users\User\AppData\...\
However when I am working I get notified with the following popup:

clicking > Try again gives the same popup instantly
clicking > Cancel installation removes the popup for a short period
clicking > Skip this file keeps giving kind of the same access is denied error

A: The error comes from vscode wanting to update in the background.
The C:\Program Files\ and C:\Program Files (x86) are restricted to admin
So running vscode in admin mode will fix this issue.
To make sure vscode runs in admin mode via this:

We need to make sure it always runs in admin mode:
Opening the Code.exe with properties (right click and then properties).
Switch to the Compatibility tab and tick the box before:
Run this program as an administrator
Remember do this only when you know what you are doing.
Your are giving admin / sudo powers to vscode

This will fix the popup error.


text:
Q: Create button partially behind background image I need to create a button that partially behind a background image.  Meaning, basically just the left edge of the button is covered.  The problem I'm running into, is that because it's a background image, the only way I'm able to get the button behind it is to set the button's z-index lower than the layer with the background image, which in turn, makes the button unclickable.

A: You can hide the button behind an adjacent element. You can't hide it behind just the "background image" because the image is applied to the element itself, so you have to hide it behind the element. The visible part of the button is still clickable.

body {
  position: relative;
}

div {
  background: url('http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg') top left no-repeat;
  background-size: cover;
  display: inline-block;
  position: relative;
  width: 100px; height: 100px;
}

button {
  position: absolute;
  right: 0;
  left: 80px;
}
<button>button</button>


text:
Q: create table with jquery. wrong order of code execution? i've got another problem with my jquery code.
Here some example code:
$(document).on('click', 'input.goto_batterie_pruefung', function() {
   /** some code**/
    $.ajax({
        url: "example.php",
        type: "post",
        data: /* some data */,
        datatype: "json",
        success: function(data) {

            var data=$.parseJSON(data);

            $('#div_testausgabe').html('');
            $('#div_testausgabe').append('

');

            $.each(data, function(index, value) {
                  /* some variables for tabledata */

                $('#div_testausgabe').append('
');
                var text=''+data+'	'+data+'	'+data+'	'+data+'	'+data+'	'+data+'	'+data+'	';
                $('#div_testausgabe').append(text);
                $('#div_testausgabe').append('
');
            });

            $('#div_testausgabe').append('

');

        }
    });
});

My problem is that the table doesn't get created correctly. the table tags will surround only the thead part.

A: You're definitely building the table wrong. .append() is going to be appending to your
, so you end up with

 id="div_testausgabe">

 blah blah blah from your first .append call

row #1 from the .each() call>

row #2 from the .each() call()

   etc...

You need to isolate the actual table inside your div, e.g.
$('#div_testausgabe table tbody').append(....);
                    ^^^^^^^^^^^

so that your new tr/td nodes are going into the correct location.

A: Don't append partial html, you will be updating the DOM a lot of times, making it slower and causing multiple redraws and the browser will try to correct it.
You should build a string of html and append that at the end, after the $.each() loop.
Something like:
$('#div_testausgabe').html('');
var table_html = '

';

$.each(data, function(index, value) {
    table_html += '
'+data+'	'+data+'	'+data+'	'+data+'	'+data+'	'+data+'	'+data+'
';
});

table_html += '

';
$('#div_testausgabe').append(table_html);

A: You are using jQuery's append() as if it was a string concatenation, which it isn't.


text:
Q: Can we have multiple properties under a single property key in No4j? I am trying to create a node with a Property key that can have multiple values.
For example jobs:"HSBC","American Bank", "Russian Bank", "Indian Bank"
Is there a way to do this via Neo4j using cypher?
Also, if there is, can I edit a node to include the same?

A: Sure, you can have a list of Strings-
CREATE (n:Person {jobs:["HSBC","American Bank", "Russian Bank", "Indian Bank"]})

List Operators: http://neo4j.com/docs/developer-manual/current/#query-operators-list


text:
Q: How to remove a mod_rewrite rule Today, I try to redirect in my web using Mod_rewrite. But I do something wrong with it and I want to fix the rule.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^my\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://localhost:8067/$1 [R=301]

I want to change the rule to something else. But when I delete rule in .htaccess and restart apache. The rule still affect to url. I try to delete .htaccess file but the problem still occur.
Please help me

A: After a while, I decided to open my web page on other computer and get no error. So I clear my browser data and the problem is solved.
Hope this help!!


text:
Q: Use a second AWS account for s3 files in laravel I am using laravel and need to use a second aws account for publishing to an s3 bucket. I have been using some s3 buckets for internal use in the framework, however I have another external aws account I need to use and send files to. Of course I have the access key and secret for this new account, just not quite sure how to setup the config, etc in laravel. Using laravel 4.

A: Found a way to do this without using the config settings using the factory:
`$s3 = \Aws\S3\S3Client::factory(array(
  'region' => 'region-name',
  'key' => 'key',
  'secret' => 'secret'
));`


text:
Q: Is it possible to specify an uri in Nginx proxy_pass? I have a question, is it possible to specify a URI in the Nginx proxy_pass directive?
I currently host two websites on my windows server on a lan network that are set up and accessible via nginx. But I have one problem. One of these sites, which is hosted at my home, needs to specify a uri, because it is not possible to reach it via the normal ip address that I have set in nginx.
To be specific, a subdomain "emfavm.emfasandbox.tk" is reverse proxyed to lan ip "192.168.1.106" by using proxy_pass. I can get to this page using this ip address, but I need to specify the uri, something like this: "https://192.168.1.106/some/uri". I host these pages on another virtual server. When I put this uri as above in proxy_pass in nginx.conf, and I connect to the domain "emfavm.emfasandbox.tk", it gives me an error "bad request, your browser sent a request that this server could not understand"
Here is my nginx.conf:
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
server_names_hash_bucket_size  64;
    include       mime.types;
    default_type  application/octet-stream;
#=============== HERE IS THE CONF WITH THE HOSTED WEBISTES ======================
    include       C:/Users/Administrator/Desktop/nginx/conf/sites-enabled/*.conf;
#================================================================================

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

And this is the conf with the website in C:/nginx/sites-enabled/emfavm.conf
server {
    listen 80;
    server_name emfavm.emfasandbox.tk;

    location / {
        proxy_pass https://192.168.1.106/#/?username=www.emfasandbox.tk&password=emfasandbox/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Thanks for any help :)

A: Maybe you can try to change https to http in C:/nginx/sites-enabled/emfavm.conf


text:
Q: Скачать все открытые вкладки в браузере как скачать все открытые в браузере вкладки? Может, есть какая-то комбинация клавиш, может плагин? Именно скачать, а не добавить в закладки! То есть совершить действие CTRL+S!
У каждого файла в итоге обязательно должно быть уникальное имя. Причем не важно, пусть это будет даже:
файл.html
файл(1).html
Суть в том, что нужно сохранить все вкладки и всё)

A: Это можно сделать с помощью imacros. Для удобства также стоит установить расширение Tab Count Icon или аналогичное.
Работает в FireFox версий 35 - 56.02 + iMacros плагин версии 8.9.7
TAB T={{!LOOP}}
SAVEAS TYPE=CPL FOLDER=* FILE={{!LOOP}}+_{{!NOW:yyyymmdd_hhnnss}}
WAIT SECONDS=3

Переходите на первую вкладку, вводите количество повторов и нажимаете Воспр. (Цикл). Для понимания, также можете прочитать подробную справку об использовании команды SaveAs на русском языке
Для работы imacros с версиями FF старше 56.02 и Chrome придётся покупать лицензию, чтобы разблокировать возможность работы с файлами .


text:
Q: Information on USB Audio I was checking out the new features of Android and I stumbled across a bullet point for USB Audio. Additionally, from the Android website:

USB audio output support allows hardware vendors to build hardware such as audio docks that interface with Android devices. This functionality is also exposed with the Android Open Accessory Development Kit (ADK) to give all developers the chance to create their own hardware.

Is there some standard out there for audio data across USB?  Can anyone point me to some references/specifications?

A: There are but it might be over kill for you depending on what you want to do.   Here's a link to the USB.org spec about audio devices http://www.usb.org/developers/devclass_docs/frmts10.pdf
That's probably not what you're looking for.  It looks like they're saying that now they'll support you plugging in a USB audio codec and your Android device will recognize it and add it as an output you can play sound through.  They have USB OTG so in theory you could plug any USB audio chip/device in and play sound through it.
There are a ton of USB audio codec chips out there if you're trying to build a piece of hardware.  TI makes a few parts just google for USB DAC.
If you just want to write some software that uses it, I think it'll just show up as another audio device for you.
Oh and here's a cool link to a forum topic where some people are messing around with it.  The pictures probably do more for an explanation.  http://androidforums.com/samsung-galaxy-s3/547033-usb-audio.html
Good Luck


text:
Q: Is this a bug in swift or my code is not correct(uialertcontroller)? In this case I am using a uialertcontroller to inform user chose save , discard or cancel changes . but after the message appearing and before disappearing  , the other code after that(makeNewDocument()) is executed.
I am not sure is there a solution?
 @objc func deleteToNew(_ notification: Notification) {
    if AppDelegate.DocInEditing{
        let dialogMessage = UIAlertController(title: "Save changes?", message: "This file belongs to \(UserManager.shared.firstname)  \(UserManager.shared.lastname). Do you want to save changes?", preferredStyle: .alert)

                    let Yes = UIAlertAction(title: "Yes save", style: .default, handler: { (action) -> Void in
                        NotificationCenter.default.post(name: Notification.Name(rawValue: "saveChanges"), object: nil)

                    })
                    let No = UIAlertAction(title: "No Discard changes", style: .default, handler: { (action) -> Void in

                    })

                    let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
                    return
                    }
                    dialogMessage.addAction(Yes)
                    dialogMessage.addAction(No)
                    dialogMessage.addAction(cancel)
            present(dialogMessage, animated: true, completion: nil)

    }

    makeNewDocument()
    }

A:
Is this a bug in swift

No

or my code is not correct(uialertcontroller)?

Yes

The alert controller and its actions work asynchronously, to run something on completion there is the completion parameter. Call it there
present(dialogMessage, animated: true, completion: makeNewDocument)

Or if you want to call makeNewDocument only in one of the actions, move the line into the action body
let yes = UIAlertAction(title: "Yes save", style: .default, handler: { action in
             NotificationCenter.default.post(name: Notification.Name(rawValue: "saveChanges"), object: nil)
             self.makeNewDocument()
          })

Side note:
It's highly recommended to create Notification.Name constants only in an extension to take advantage of the safety of those constants
extension Notification.Name {
    static let saveChanges = Notification.Name(rawValue: "saveChanges")
}

and use it
let yes = UIAlertAction(title: "Yes save", style: .default, handler: { action in
             NotificationCenter.default.post(name: .saveChanges, object: nil)
             self.makeNewDocument()
          })


text:
Q: VBA doesn't divide local variable (Error 6 overflow) I'm trying to program a simple z-test but my code gives an error when calculating the Z-score with this code: Z = (P1 - P2) / SD; does anyone know why? The error that comes up is an overflow (error 6)
Here's the full code:
Sub ChiSquare()

    Total_Groep_1 = Application.Sum(Range("C4", Range("C4").End(xlDown)))
    Total_Groep_2 = Application.Sum(Range("E4", Range("E4").End(xlDown)))

    For i = 5 To Range("C4").End(xlDown)
                Dim P1 As Double
    P1 = Cells(i, 3) / Total_Groep_1
    Cells(i, 4) = P1

    Dim P2 As Double
    P2 = Cells(i, 5) / Total_Groep_2
    Cells(i, 6) = P2

    Dim SD As Double
    SD = Sqr((P1 * (1 - P1) / Total_Groep_1) + (P2 * (1 - P2) / Total_Groep_2))
    Cells(i, 7) = SD

    Dim Z As Double
    Z = (P1 - P2) / SD
    Cells(i, 8) = Z

    Next i

End Sub

A: The loop that I made didn't go to a number but to a range. It works now I changed that.


text:
Q: Sampling distribution Assume I have some distribution defined by probabilities like the following [0.1, 0.6, 0.2, 0.1]. The sum of probabilities equals 1. I wonder how I can sample this distribution, such that the sampling will follow the distribution.

A: Assuming that the PRNG of Node.JS follows a uniform distribution a simple solution could be this one:
var v = Math.random(); // return a number between 0 and 1

if(v < 0.1)
    // first value
else if(v < 0.7) // (0.1 + 0.6)
    // second value
else if(v < 0.9) // (0.1 + 0.6 + 0.2)
    // third value
else
    // forth value

This question has been already answered here (the proposed solution is more general since they proposed a function that can accept an array of probabilities):
distributional sampling in Node.js

A: It depends on whether your distribution is discrete or continuous. For the continuous case you have to interpolate linearly between two values. Here is the pseudocode

*

*Let u be a random number between 0 and 1

*Let i such that p[i] <= u <= p[i+1]

*Return (x[i+1] - x[i]) / (p[i+1] - p[i]) * (u - p[i]) + x[i]
Note that in 2 there could be no such i because of two reasons: (a) u < p[1] or (b) p[n] < u (I'm assuming 1-based arrays). In case (a) return x[1] in case (b) x[n].


text:
Q: Word for refusing to do what you're supposed to What's another word that describes that act of not doing what you're supposed to do?
Eg: The electoral voter did not vote for his state's preferred candidate. He [the word]'ed.
"Reneged" doesn't quite sound right.


text:
Q: Paypal Invalid Merchant Configuration sandbox error I am using paypal pro in sandbox. when I send the request and in response I get this error:
Array
(
    [TIMESTAMP] => 2010%2d11%2d23T09%3a21%3a12Z
    [CORRELATIONID] => 2aa783b64659
    [ACK] => Failure
    [VERSION] => 51%2e0
    [BUILD] => 1620725
    [L_ERRORCODE0] => 10501
    [L_SHORTMESSAGE0] => Invalid%20Configuration
    [L_LONGMESSAGE0] => This%20transaction%20cannot%20be%20processed%20due%20to%20an%20invalid%20merchant%20configuration%2e
    [L_SEVERITYCODE0] => Error
    [AMT] => 20%2e00
    [CURRENCYCODE] => USD
)
I google this error and it is something with the "Billing Aggrement"
Can anyone suggest what to do on this?

A: The API credentials in the Sandbox environment uses the default buyer account you have. You need to make sure to use the "payments pro" option when you create a buyer account in the sandbox environment. You'll then see a new set of API credentials under API credentials...just use those and you should be fine.

A: I was having this same problem while trying to use the DoDirectPayment example on the sandbox using the provided API user/pass.
L_ERRORCODE0: 10501
L_SHORTMESSAGE0: Invalid Configuration
L_LONGMESSAGE0: This transaction cannot be processed due to an invalid merchant configuration.

I logged into my sandbox account, but there was no billing agreement to agree to. Trying to enable Website Payments Pro from there proved fruitless as well.
There seem to be a lot of issues with the Paypal sandbox right now, where test accounts are not populating with the right info. This 10501 problem is due to "Website Payments Pro" not being enabled on the account.
Contact customer support and they can enable it for you. They asked me to create a new test seller account so they could toggle it on.

A: Click products and enable payment pro sorted it for me.

Update Aug 12, 2013: Enabling PayPal Payments Pro has been moved to the "Profile" tab.  There is no longer a "Products" tab.

A: PayPal is currently working on addressing this issue. You may want to file ticket with MTS (www.paypal.com/mts) to be updated on when it's fixed.
Accounts created before the latest release do have Pro set up correctly. All new accounts have a problem with the billing agreement that affects Pro functionality and results in error 10501.

A: I had this problem when I was using the default Business sandbox account that exists when you set up the PayPal developer account. When I created a new business account everything worked.
Also, be sure to use a personal sandbox account that you set to test against your business sandbox account.


text:
Q: Reloading log4j.properties using Log4j Bridge I have to migrate an existing project from Log4j to Log4j2. The easiest way seems to use the Log4j 1.2 Bridge. This works fine, even the existing log4j.properties file can be used.
The question that I have is:

*

*Can the log4j.properties file be reloaded periodically at runtime, so that a restart of the application is not necessary after changing
the log4j.properties file?

In Log4j version 1.x this could be done using
PropertyConfigurator.configureAndWatch(fileName, 10000),
but it seems this does not work any longer using the bridge.

A: You can use the log4j1.monitorInterval system property:
log4j1.monitorInterval=10

The value is in seconds.
The above mentioned property can be set in any property source, e.g. in log4j2.component.properties file.


text:
Q: Issue any command using sftp in JSch Hi I am currently using the below code line to issue commands to the remote server
ChannelSftp sftp = (ChannelSftp)session.openChannel("sftp");
sftp.connect();
System.out.println("Current Directory: " + sftp.pwd()); <= This Line
But pwd is already be defined as a method in Class ChannelSftp, My Question is what if I want to issue some command or run any .sh file which is not a method in JSch?
Let say if I want to run : sudo /opt/bin/run.sh file.
OR is there any method which I can use to do the job
(Kindly note I have a Jump Server in between localhost and web Server. And web server can only be accessed via the jump server.So that is the reason I am not using exec or shell).

A: The ChannelSftp class is implementing the SFTP protocol, which is cabable of preforming FTP operations. Executing a random command is clearly not permitted via SFTP. What you need in this case is using a different class of the jsch lib: ChannelExec.
Example is here.


text:
Q: libgit2: git_clone() fails with a "failed to create ssl object" error I'm trying to clone a git repository using libgit2's git_clone() function, however, when I call the function it returns -1, and using giterr_last() (I get "undefined reference" if I use git_error_latest(), not sure why) I get the error "failed to create ssl object".
I've looked into the source code for the relevant file, here, and it seems as though it fails on line 711, SSL_new(git__ssl_ctx).
Here's my code:
#include <string>
#include <git2/clone.h>
#include <git2/errors.h>
#include <git2/common.h>
#include <iostream>

int main() {
    git_repository* pGitRepository = nullptr;
    std::string url = "https://github.com/Newbie13XD/nashmap.git";
    std::string path = "/home/neboula/CLionProjects/gut/foo";
    const git_clone_options* options = nullptr;

    if (git_clone(&pGitRepository, url.c_str(), path.c_str(), options) != 0) {
        const git_error* error = giterr_last();

        std::cout << error->message;
    }

    return 0;
}

I'm compiling with g++ (version: Red Hat 8.3.1-2) and libgit2 version 0.27.8.

A: I figured it out, you have to call git_libgit2_init() prior to using any other functions in libgit2. Adding this to the start of my program solved the issue.


text:
Q: Token authentication with Azure functions Using ASPNET webapi, it's very easy to setup a 3. party authority for token validation. I've looked around to do the same with Azure Functions but haven't found an answer yet. Is it possible yet and also if it is, can it be done not using Azure AD, but integrate something like Firebase Authentication?

A:
Is it possible yet and also if it is, can it be done not using Azure AD, but integrate something like Firebase Authentication?

Yes, it is possible. Refer to this article.
Firebase is an application platform from Google which offers many useful services to get your mobile or web app project started up quickly. To authenticate your users, the Firebase Auth service offers registration screens and authorization functionalities.


text:
Q: iptables: Index of deletion too big BASH I am having some difficulties setting a default iptables script as it won't run. It shows the error: iptables: Index of deletion too big
I have tried re-ordering the rules, attempting to delete all first before adding, etc. but it doesn't seem to be helping. What am I doing wrong?
Here is the script:
#!/bin/bash

iptables -P FORWARD DROP
iptables -D FORWARD 1
iptables -P INPUT DROP
iptables -D INPUT 5
iptables -D INPUT 4
iptables -I INPUT -p tcp --dport 22 -j ACCEPT
iptables -D INPUT 3
iptables -I INPUT -p icmp -j ACCEPT

the original IP tables looks like this:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
  119 13723 ACCEPT     all  --  any    any     anywhere             anywhere             state RELATED,ESTABLISHED
    0     0 ACCEPT     icmp --  any    any     anywhere             anywhere
    0     0 ACCEPT     all  --  lo     any     anywhere             anywhere
    1    60 ACCEPT     tcp  --  any    any     anywhere             anywhere             state NEW tcp dpt:ssh
    0     0 REJECT     all  --  any    any     anywhere             anywhere             reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 REJECT     all  --  any    any     anywhere             anywhere             reject-with icmp-host-prohibited


text:
Q: create parent child array from inline data in php actually i have simple problem but i forget how to solve it.. :D
i have data on table with following format
01 Johson 01 Craig
01 Johson 02 Daniel
01 Johson 03 Abbey
02 Dawson 01 Brown
02 Dawson 02 Agust
03 Brick  01 Chev
03 Brick  01 Flinch
so i want it to become an array like this
01 Johson => 01 Craig
``````````````02 Daniel
```````````````03 Abey
`
etc...
how to iterate trough the data and make it array like that...
i'm newby in PHP :))

A: There are a number of ways to get the outcome, though I am partial to using a mysql group concat:
select
    col1,
    group_concat(col2) as col2
from
    tableName
group by
    col1;

This will return that particular column of data in a comma delimted string, which you can then very easily explode inside your PHP code as it comes from the database.
Even though a comma is the default for group_concat, you can easily change it to concat the rows of data on a different string as well.

A: Is this what you want?
$results = array();
while ($row = mysqli_fetch_assoc($query_result)) {
  $parent = $row['parentid'].' '.$row['parentname'];
  if (!array_key_exists($parent, $results)) {
    $results[$parent] = array();
  }
  $results[$parent][] = $row['childid'].' '.$row['childname'];
}


text:
Q: Restoring a database is not working I have a database called FDB. I have created this database on my PC with SQL Server Express Edition and added one table. I made a backup of this database. The SQL Server version on the server is 2005.
I copied this backup to the server and tried to restore it, but I get this message:

The media family on device C:\Program File\Microsoft SQL Server\MSSQL.1\MSSQL\Bacup\FDB.bak is incorrectly formatted. SQL Server cannot process this media family. RESTORE Headeronly is terminating abnormally. Microsoft SQL Server error 3241

A: If you have created the backup of a SQL Server 2008 database and are trying to restore it on a SQL Server 2005 instance, you will receive this error.  You cannot do this.
Your best bet would be to script out the database (as long as all of the schema and objects are 2005 compatibile).  You can't downgrade a database.

A: You need to fix the connection so it is using the SQL 2008 instance.
Try to run the SQL Server 2008 Express install program again, and during Name Instance configuration, specify a Name Instance with a different name.  Example: MachineName\instancename
After installation, logged in with New Instance name created.
Try to create database, create tables for database and try to run restore again.  It will work
Source: http://dotnetguts.blogspot.in/2010/06/restore-failed-for-server-restore.html

A: If you're restoring a SQL Server 2008 database on a SQL Server 2005, using backups won't work.
You can script a database instead:
In SSMS Object Explorer right click a database
Select Tasks, Generate Scripts

Check 'Script all objects in the selected database'

In the Choose Script options:
      Set ' Script for Server version' to SQL Server 2005
      Set'Script data' to true to insert the data. It's false by default

When the script is created, create a database with the same name on SQL Server 2005 and execute the script


text:
Q: kafka connect -> pubsub -> dataflow pipeline data loss I'm creating a streaming data pipeline that streams data from a kafka cluster to Google BQ.
Currently, I am pushing these data to pubsub through pubsub kafka connector, then from pubsub to BQ through dataflow.
However, in some cases, there are some data which have seems to gone missing at certain times.
For a whole day of data, about 300k rows, there seems to be 17 rows on average missing.

It only happens on a certain time (refer to image)
When I check the logs for kafka connector, the data is present in the logs and there isn't any errors found :
[2019-11-26 13:30:01,618] INFO Key record: Struct{ad_id=95177783,action_id=2,state_id=999113806} (com.google.pubsub.kafka.sink.CloudPubSubSinkTask)
[2019-11-26 13:30:01,618] INFO Value record: Struct{ad_id=95177783,action_id=2,state_id=999113806,state=activated,transition=activate,timestamp=Struct{DateTime=Struct{year=2019,month=11,day=26,hour=13,minute=30,second=1,micro=602125}},remote_addr=202.184.54.140,remote_browser=} (com.google.pubsub.kafka.sink.CloudPubSubSinkTask)
[2019-11-26 13:30:01,618] INFO data: {"ad_id":95177783,"action_id":2,"state_id":999113806,"state":"activated","transition":"activate","timestamp":{"DateTime":{"year":2019,"month":11,"day":26,"hour":13,"minute":30,"second":1,"micro":602125},"SpecialTime":null},"remote_addr":"202.184.54.140","remote_browser":"","token_id":null,"old_token_id":null,"auth_admin_id":null,"auth_store_id":null,"auth_store_email":null} (com.google.pubsub.kafka.sink.CloudPubSubSinkTask)

This is the example log for the state_id = 999113806. A unique row identifier.
However, I'm not able to find any log in the pubsub logs for the same data.
Hence, I'm kinda lost here. Did kafka conenctor successfully send the data over and did pubsub successfully receive it ?
Or is this a problem with dataflow reading all records from pubsub ?
My dataflow code is literally:
class transform_class(beam.DoFn):
    def process(self, element, publish_time=beam.DoFn.TimestampParam, *args, **kwargs):
        logging.info(element)

def run(output_path, window_size=1.0, pipeline_args=None):
    pipeline_options = PipelineOptions(
        pipeline_args, streaming=True, save_main_session=True)

    with beam.Pipeline(options=pipeline_options) as pipeline:
        lines = (pipeline
                | 'Read PubSub Messages' >> beam.io.ReadFromPubSub(topic='pubsubtopic',with_attributes = True)
                | 'Transforming Messages' >> beam.ParDo(transform_class()))

Any help is appreciated.


text:
Q: What to call "casual" or "commonplace" death? In a science fiction future, people naturally live forever, although accidents and murders are still possible, even if much less common as there's a lot to lose.
Suppose a future person looks at our time, when death was commonplace, when people died left, right an centre, when everyone has dead relatives (e.g. grandparents, those lost to cancer or car accidents), when everyone knew their death was inevitable.
What would future people call our death? Common? Casual?

A: I think you yourself can be a judge of that, I mean we ourself are future for the people living during the plagues like The Black Death. I don't think anyone would call their deaths 'casual'. Cause life is always very important to even a immortal as they will be in future(according to your question). I don't think we can use 'common' for their deaths too. We just call them deaths. maybe natural deaths, or a death due to a pandemic etc. And if it's a term you want to discuss more you can check out our sister sites
https://scifi.stackexchange.com/
or
https://worldbuilding.stackexchange.com/

A: Today, when people die much younger than their projected lifespan, their deaths are described as premature. Perhaps that term would persist as lifespans grow.

A: From the viewpoint of a future person in your sci-fi universe, maybe this is primitive death, or archaic death.

A: I would replace commonplace with prosaic.

Prosaic (adj): Ordinary and not especially interesting or unusual. [Cambridge English Dictionary]

The person from future would say that the death was prosaic or perhaps certain death.

A: "Routine" is a possibility. It might strike beings from the future as truly bizarre that death was once 'routine,' if dreaded,
https://www.merriam-webster.com/dictionary/routine

routine adjective
rou·tine | \ rü-ˈtēn  , ˈrü-ˌtēn

1 : of a commonplace or repetitious character : ORDINARY
routine problems
2 : of, relating to, or being in accordance with established procedure
routine business

A: The word that came to my mind was ubiquitous, which Merriam-Webster defines as "existing or being everywhere at the same time; constantly encountered; widespread".
People in the distant future, when death has been all but eliminated, might think of our time as being a time in which death was ubiquitous. Everyone has close relatives who have died. Everyone knows about lots of people who have died. Everyone expects themselves to die, and worry about how they can postpone it. That's what I'd call ubiquitous.

A: natural death
Merriam-Webster

death occurring in the course of nature and from natural causes (as
age or disease) as opposed to accident or violence

These people of the future would not 'naturally' live forever. If possible, this everlasting life would most definitely be artificial:
same source

artificial
1 humanly contrived often on a natural model
2 b: caused or produced by a human and especially social or political
agency

A: Mundane carries the normalcy and hints at the condescension that the future humans would have for such.

characterized by the practical, transitory, and ordinary : COMMONPLACE

Kids' definition (from that same entry):

dull and ordinary


text:
Q: Calculating regression line from given quantile of values depending on category I have a quite huge dataframe (nearly 100,000 observations with about 40 variables) from which I want ggplot to draw scatterplots with lm- or loess-lines. But the lines should be calculated only based on a certain quantile of variable-values of each observation date. And I would like to do the filtering or subsetting directly in ggplot without creating a new data object or subdataframe in advance.
As my 'real' dataframe would be too large I created fictive example with a dataframe of 144 observations named df_Bandvals (Code at the end of the post).  Here following structure, the first 25 lines and a scatterplot with a loess-line based on ALL observations
> str(df_Bandvals)
'data.frame':   144 obs. of  5 variables:
 $ obsdate      : int  190101 190101 190101 190101 190101 190101 190101 190101 190101 190101 ...
 $ transsect    : chr  "A" "A" "A" "A" ...
 $ PointNr      : num  1 2 3 4 5 6 1 2 3 4 ...
 $ depth        : num  31 31 31 31 31 31 31 31 31 31 ...
 $ Band12plusmin: num  169 241 229 159 221 196 188 216 233 149 ...

> df_Bandvals
    obsdate transsect PointNr depth Band12plusmin
1    190101         A       1    31           169
2    190101         A       2    31           241
3    190101         A       3    31           229
4    190101         A       4    31           159
5    190101         A       5    31           221
6    190101         A       6    31           196
7    190101         B       1    31           188
8    190101         B       2    31           216
9    190101         B       3    31           233
10   190101         B       4    31           149
11   190101         B       5    31           169
12   190101         B       6    31           181
13   190102         A       1     3           356
14   190102         A       2     3           368
15   190102         A       3     3           293
16   190102         A       4     3           261
17   190102         A       5     3           313
18   190102         A       6     3           374
19   190102         B       1     3           327
20   190102         B       2     3           409
21   190102         B       3     3           369
22   190102         B       4     3           334
23   190102         B       5     3           376
24   190102         B       6     3           318
25   190103         A       1    25           183

The plot shows depth vs. Band12plusmin with an according loess-line. Point colors are assigned to the respective observation date (obsdate). Each observation date includes 12 observations.
Now, my basic question was: How to get a loess line based only on the lower 50%-quantile Band12plusmin-values of each observation date? Or in other words with referring to the plot: ggplot should only use the 6 lower points of each color for calculating the line.
And as mentioned before I would like to do the filtering or subsetting directly in ggplot without creating a new data object or subdataframe in advance.
I tried around with subsetting, but my problem in this case is that I cannot just specify a universal Band12plusmin-threshold as, of course, the 50%-treshold individually differs for each obsdate-group.  I am quite new to R and ggplot, so, for now I failed to find a solution for that say class-individual-derived-threshold-conditionned filtering.
May anybody help here?
Here the code of the dataframe and plot
obsdate<-rep(c(190101:190112),each=12, mode=factor)
transsect<-rep(rep(c("A","B"), each=6), 12)
PointNr<-rep(c(1,2,3,4,5,6), times=24)
depth<-rep(c(31,3,25,-9,13,18,7,-10,3,-4,11,21),each=12)
Band12<-rep(c(199,349,225,844,257,231,301,875,378,521,210,246), each=12)
set.seed(13423)
plusminRandom<-round(rnorm(144, mean=0, sd=33))
plusminRandom
Band12plusmin<-Band12+plusminRandom
df_Bandvals<-data.frame(obsdate, transsect, PointNr, depth, Band12plusmin)
str(df_Bandvals)
head(df_Bandvals, 20)

library (ggplot2)

ggplot(data=df_Bandvals, aes(x=depth, y=Band12plusmin))+
  scale_x_continuous(limits = c(-15, 35))+
  scale_y_continuous(limits = c(120, 960))+
  geom_point(aes(color=factor(obsdate)), size=1.5)+
  geom_smooth(method="loess")

A: You should be able to use the data argument within geom_smooth()
ggplot(data = df_Bandvals, aes(x = depth, y = Band12plusmin)) +
  scale_x_continuous(limits = c(-15, 35)) +
  scale_y_continuous(limits = c(120, 960)) +
  geom_point(aes(color = factor(obsdate)), size = 1.5) +
  geom_smooth(
    data = df_Bandvals %>%
      group_by(obsdate) %>%
      filter(Band12plusmin < median(Band12plusmin)),
    method = "loess"
  )


text:
Q: Bad pointer in URL response I am trying to upload a photo to Facebook from my app and all goes well when I upload and wait for it to finish, but when I press on upload then go back to the previous view, when the upload is complete i get an error
Thread 1:EXC_BAD_ACCESS(code=2, address=0x9)

In the code:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_responseText = [[NSMutableData alloc] init];

NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([_delegate respondsToSelector:
     @selector(request:didReceiveResponse:)]) {
    [_delegate request:self didReceiveResponse:httpResponse];
}
}

It breaks on the if. I'm not sure how I would go about solving this.
Thank you
EDIT:
This is called before I go back to the previous view:
-(IBAction)shareToFacefook{
        [[self appDelegate] facebooking]; // checke that the user is loged in
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   labeledImage, @"source",
                                   [[MyStrings myLocalStrings] getBackLocalstring:FB_IMG_POST_TITLE],@"message",
                                   nil];

    [[[self appDelegate] getFacebookVar] requestWithGraphPath:[NSString stringWithFormat: @"/me/photos?access_token=%@", self.appDelegate.getFacebookVar.accessToken] andParams:params andHttpMethod:@"POST" andDelegate:self];
}

A: Seems like a memory management issue.  EXC_BAD_ACCESS generally means the memory address which is being accessed is no longer valid.
Are you using retain to increment the reference count for _delegate when you receive it?  If not, then it may have been garbage collected.  You should either use retain or make a copy of the delegate when you receive it.

A: you can try this:
1.check the Facebook.m
2.find the "dealloc"
3.you'll see the following code:
for (FBRequest* _request in _requests) {
        [_request removeObserver:self forKeyPath:requestFinishedKeyPath];
    }

replace it to
for (FBRequest* _request in _requests) {
        _request.delegate = nil;
        [_request removeObserver:self forKeyPath:requestFinishedKeyPath];
    }


text:
Q: My function from js file is not getting called from html file I am working on a website which used node js. I added a function in my js file. Now when I am trying to call the function from the html page the function is not getting called.
This is the code which I used in the html page:
<div id ="bubble" class="bubble-style" data-action="getSpeechBubble()

I just added a console statement in the function :
getSpeechBubble: function() {

        console.log(' getSpeechBubble ');
}

A: There is several ways to create and call functions, most popular used is below

function getSpeechBubble(){
console.log("getSpeechBubble");
}
//get function from data-action attribute
var exc = document.getElementById("bubble").getAttribute("data-action");

//or window.addEventListener("load",new Function(exc),false);
window.onload = new Function(exc);
//or .addEventListener("clik",new Function(exc),false);
document.getElementById("bubble").onclick = new Function(exc);

click me

//1st way
this.getSpeechBubble = function() {
            console.log(' 1st way: getSpeechBubble ');
}
this.getSpeechBubble();
//2nd way
this["getSpeechBubble"] = function() {
            console.log(' 2nd way: getSpeechBubble ');
}
this["getSpeechBubble"]();
//3rd way
window["getSpeechBubble"] = function() {
            console.log(' 3rd way: getSpeechBubble ');
}
window["getSpeechBubble"]()
//4th way
var getSpeechBubble = function() {
            console.log(' 4th way: getSpeechBubble ');
}
getSpeechBubble();
//5th way
var js = {
getSpeechBubble: function(){
            console.log(' 5th way: getSpeechBubble ');
}
};
js.getSpeechBubble();
//6th way
function getSpeechBubble () {
            console.log(' 6th way: getSpeechBubble ');
}
getSpeechBubble();


text:
Q: Store password securely and retrieve it later Use case: To run installer in unattended mode.
How:
To achieve this I am using Process.Start and passing it ProcessStartInfo as below:
 var processStartInfo = new ProcessStartInfo
 {
       FileName = installerPath,
       Arguments = commandLineArguments
 };

Issue: One of the parameters in the command line arguments is username and password. The username and password are provided by an API. What I am doing is saving encrypted password in database and then return it through the API. Then on the receiving end decrypting it. I know its not a best practice to save encrypted passwords (instead should save hash of the password) but pls. see the use case mentioned above.
I would like to know if saving encrypted password (and decrypting it later) is the best way to go here or is there a better way.

A: For encryption I'm using this class :
/// <summary>
/// Encrypt Password with local key
/// </summary>
public class SecureIt
{
    #region Declaration

    static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("Salt Is Not A Password");

    #endregion

    #region Methods

    public static string EncryptString(System.Security.SecureString input)
    {
        byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
            System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
            entropy,
            System.Security.Cryptography.DataProtectionScope.CurrentUser);
        return Convert.ToBase64String(encryptedData);
    }

    public static SecureString DecryptString(string encryptedData)
    {
        try
        {
            byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
                Convert.FromBase64String(encryptedData),
                entropy,
                System.Security.Cryptography.DataProtectionScope.CurrentUser);
            return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
        }
        catch
        {
            return new SecureString();
        }
    }

    public static SecureString ToSecureString(string input)
    {
        SecureString secure = new SecureString();
        foreach (char c in input)
        {
            secure.AppendChar(c);
        }

        secure.MakeReadOnly();
        return secure;
    }

    public static string ToInsecureString(SecureString input)
    {
        string returnValue = string.Empty;
        IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
        try
        {
            returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
        }
        finally
        {
            System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
        }

        return returnValue;
    }

    #endregion
}

The encryption is done with a the Local Machine key so only the same machine can Decrypt the password
Convert Secure string to InSecure:
SecureIt.ToInsecureString(SecureIt.DecryptString(this._password));

Convert InSecure String to Secure:
SecureIt.EncryptString(SecureIt.ToSecureString(connection.Password));


text:
Q: Why isn't Android L listed in the SDK Manager? I want to try CardView that is available on Android L. But Android L isn't listed in the SDK Manager.

I use android studio. This is the screenshot.

Some said that I need to upgrade my JDK to 7.0. My JDK is already 7.0.

What should I do? I use Fedora by the way.

A: Android L was the identifier for the 5.0 preview SDK, which is no longer available. The release version is Android 5.0.1 (API 21).


text:
Q: IdentityServer4 - Inject ConfigurationDbContext for use in class I am persisting configuration in the ConfigurationDbContext.  I am now creating a ServiceProvider that will allow to dynamically add Clients, ApiResources, etc. at a later time.
My question is, what is the best way to retrieve the ConfigurationDbContext in a class?  If dependency injection is the best answer, how do I register the ConfigurationDbContext as a service, and how do I retrieve that service from a class outside of Startup.cs where IApplicationBuilder.ApplicationServices is not available?

A: Here is how you do it once you define ConfigurationDbContext.

*

*In Startup.cs file register ConfigurationDbContext as follows.
public void ConfigureServices(IServiceCollection services)
{
   string connectionString = "my connection string";

   services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ConfigurationDbContext>(options =>
            options.UseSqlServer(connectionString));

    //Add more services here e.g.
    services.AddMvc();
}

*Use ConfigurationDbContext wherever its needed.
public class MyClassWhereDbContextIsNeeded
{
   private readonly ConfigurationDbContext dbContext;

   //Inject context instance here.
   public MyClassWhereDbContextIsNeeded(ConfigurationDbContext dbContext)
   {
      this.dbContext = dbContext;
   }

   public void SomeMethod()
   {
      //Use DbContext here e.g. Get customers from database.
      var customers =  dbContext.Customers.ToList());
   }
 }


text:
Q: mysql between current year and current year + 6 months I need to make query where is where condition date between current year and current year + 6 months
SELECT VOZ.prez_vozac,VOZ.ime_vozac,LOD.naz_lok,LDO.naz_lok,V.datum
    FROM voznja AS V
    INNER JOIN vozac AS VOZ ON V.sif_vozac = VOZ.sif_vozac
    INNER JOIN lokacija AS LOD ON V.sif_lok_od = LOD.sif_lok
    INNER JOIN lokacija AS LDO ON V.sif_lok_do = LDO.sif_lok
    INNER JOIN vozilo AS VOZI ON V.regbr = VOZI.regbr
    INNER JOIN teret AS T ON V.sif_teret = T.sif_teret
    WHERE T.tezina <= 5 AND V.datum BETWEEN ***CURENT YEAR*** AND ***CURRENT YEAR + 6 MONTHS ***

A: Assuming you mean current date and six months from now...
   SELECT VOZ.prez_vozac,VOZ.ime_vozac,LOD.naz_lok,LDO.naz_lok,V.datum
    FROM voznja AS V
    INNER JOIN vozac AS VOZ ON V.sif_vozac = VOZ.sif_vozac
    INNER JOIN lokacija AS LOD ON V.sif_lok_od = LOD.sif_lok
    INNER JOIN lokacija AS LDO ON V.sif_lok_do = LDO.sif_lok
    INNER JOIN vozilo AS VOZI ON V.regbr = VOZI.regbr
    INNER JOIN teret AS T ON V.sif_teret = T.sif_teret
    WHERE T.tezina <= 5 AND V.datum BETWEEN CURDATE()
AND DATE_ADD(CURDATE(), INTERVAL 6 MONTH)


text:
Q: Git: what is the difference between dev and refs/heads/dev? From recent work in devops, it seems as though there are "two ways" to check out a branch in git: using the plain branch name, e.g. dev, or using the branch name prefixed with refs/heads/, e.g. refs/heads/dev.
What is the difference between the two?
Certain HTTP POST content in the Bitbucket webhook to Jenkins gives the "refs/head" version of the branch. Other POST content gives the "basename" branch.
E.g. using (what I think is) Jenkins syntax to fetch POST content from a pull-request Bitbucket event, $.pullRequest.fromRef.id == /refs/heads/dev...
and $.pullRequest.fromRef.displayId == dev
In a cloned repository, checking out refs/heads/dev and dev resolves to the same SHAID, but their respective stdouts differ:
$ git checkout refs/heads/dev
Note: checking out 'refs/heads/dev'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at c320fd1... wip

$ git checkout dev
Switched to branch 'dev'
Your branch is up-to-date with 'origin/dev'.
$ git log --oneline -n 1
c320fd1 wip

The stdout of the former looks the same as when you check out a SHAID.

A: Names are resolved to revision id's early, according to the rules in the docs.
When the ref you give is resolved by (just) adding a refs/heads/ prefix, Git's convenience machinery kicks in, git checkout will make HEAD be an alias for the branch tip, so all the convenience commands that rely on HEAD will be referring to and updating the branch tip ref.
So when you say git checkout dev, you're using Git's convenience machinery and it does the convenience thing for you, it wires HEAD to be a symbolic reference to refs/heads/dev and git commit's HEAD update will be redirected to that branch tip.
But if you bypass the convenience logic by taking explicit steps yourself, that doesn't happen. That's really the sole difference. If you want, you can
git checkout refs/heads/dev
git symbolic-ref HEAD refs/heads/dev

and now you've done Git's convenience processing yourself.


text:
Q: How to make a service remain alive if the application is destroy from the memory The main thing i just want to do is that i have to check on me webservice when my application is closed when it gets any alert on webservice then it shows notification or activity.
I read about services and make an example but when i remove the application from recent apps then some time the service is restarted or some the service got killed to.
Code:
package com.usamaakmal.startedservice;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.widget.Toast;

public class NewService extends Service {
    public NewService() {
    }

    int i = 0;

    Handler handler = new Handler();
    Thread runnable = new Thread() {
        @Override
        public void run() {
            i++;
            Toast.makeText(getBaseContext(), "Hello World! " + i, Toast.LENGTH_SHORT).show();
            handler.postDelayed(this,1000);
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
        handler.postDelayed(runnable,2000);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

}

A: Removing app from recent apps list kills app process. Returning START_STICKY from onStartCommand() means you want the system to restart the service after it was killed (either because you removed the app from recents list or system killed service because it ran out of resources).
If you want to keep your service (and it's process) alive you will need foreground service.
System tries to keep foreground services alive as long as possible.
See: Running service in foreground


text:
Q: Leer archivo de texto en ejecutable C++ Lo que quiero es que en la opción 2, lea los clientes que he guardado en la opción 1 pidiendo la cedula de cada cliente, es decir, sólo mostrar en pantalla los datos solo del cliente que se pida.
En la opción 1, logré guardar a los clientes con la cedula, y en el archivo de texto se va guardando bien. El único problema es en la opción 2, que no sé realmente cómo pedir un solo dato (cedula) para que me imprima solo a el cliente llamado.
Ahí intenté hacer algo, pero ya no pude encontrar nada en foros y videos. Y si es posible, hacer en la opción 3 y 4 lo mismo que en las 2 primeras.
/* Biblioteca de Peliculas*/
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<fstream>
using namespace std;

struct cliente{
       char nombre[20], apellido[20], nempresa[100], rif[10];
       char direccion[50];
       char sexo[10];
       char ci[10];

       int edad, telfijo, telmovil;

}cli;
struct inventario{
       char codigo[3], pelicula[100], duracion[100], genero[20], director[20], provedor[20];
       int cant, disp;
       float psi, po,pdetal,pmayor;
}inv;

int opc;

char tipoc[9], ci[10], rif[10], codigo[3];

void encabezado()
{
 printf("\t------------------------------------------------------\n");
 printf("\t-                   BLOCKBUSTER                      -\n");
 printf("\t-     Meb Escobedo, Av. Raul Salinas Lozano 297      -\n");
 printf("\t-              66050 Cd Gral Escobedo, N.L           -\n");
 printf("\t-               MOVIL: 81 8901 2437                  -\n");
 printf("\t-                 HORARIO: 10AM-8PM                  -\n");
 printf("\t-                                                    -\n");
 printf("\t------------------------------------------------------\n\n");
 }

 void ingresoc(){
      ofstream archivo;
      FILE*ar;
      system("cls");
      printf("\t OPCION 1: CREAR CLIENTES\n\n");
       if((ar = fopen("cliente.txt","a+")) ==NULL){
        printf("No se pudo abrir el archivo correctamente. Verifique por favor.");
        }
        else
        {
        fflush(stdin);
        printf("\n Cedula de identidad: ");
        gets(cli.ci);
        fprintf(ar,"%s\t",cli.ci);
        printf("\n Nombre(s): ");
        gets(cli.nombre);
        fprintf(ar,"%s\t",cli.nombre);
        printf("\n Apellido: ");
        gets(cli.apellido);
        fprintf(ar,"%s\t",cli.apellido);
        printf("\n Direccion: ");
        gets(cli.direccion);
        fprintf(ar,"%s\t",cli.direccion);
        printf("\n Sexo (M/F): ");
        gets(cli.sexo);
        fprintf(ar,"%s\t",cli.sexo);
        printf("\n Edad: ");
        scanf("%d",&cli.edad);
        fprintf(ar,"%d\t",cli.edad);
        printf("\n Telefono Movil: ");
        scanf("%d",&cli.telmovil);
        fprintf(ar,"%d\t",cli.telmovil);
        printf("\n Telefono Fijo: ");
        scanf("%d",&cli.telfijo);
        fprintf(ar,"%d\t",cli.telfijo);

        }

      }
      // Ver datos guardados de la opción 1
      void verDatos(){
           system("cls");
           FILE*ar;
           fflush(stdin);
            printf("\tOPCION 2. VER DATOS DE CLIENTES ");
           printf("\n\n  Ingrese Cedula:");
                gets(cli.ci);
                if((ar = fopen("cliente.txt","r")) ==NULL){
                printf("No se pudo abrir el archivo correctamente. Verifique por favor.");
                }
                else
                else
                {
                while(!feof(stdin)){
                fprintf(ar,"%s %s %d %d %d %s %s\n", cli.nombre,cli.apellido, cli.telfijo, cli.direccion, cli.sexo );
                }
            fclose(ar);
            }
        getch();

}
      void ingresoi(){
           int j=0;
      system("cls");
      printf("\t OPCION 3: CREAR INVENTARIO\n\n");
      fflush(stdin);
      printf("\n Equipo: #%d",j);
                                       printf("\n Codigo del producto: ");
                                       gets(inv.codigo);
                                        printf("\n Nombre de la pelicula: ");
                                       gets(inv.pelicula);
                                        printf("\n Duracion: ");
                                       gets(inv.duracion);
                                       printf("\n Genero: ");
                                       gets(inv.genero);
                                       printf("\n Director: ");
                                       gets(inv.director);
                                        printf("\n Cantidad: ");
                                       scanf("%d",&inv.cant);
                                        printf("\n Disponible: ");
                                       scanf("%d",&inv.disp);
                                       printf("\n Precio al detalle: ");
                                       scanf("%f",&inv.pdetal);
                                       printf("\n Precio al mayor: ");
                                       scanf("%f",&inv.pmayor);
                                        printf("\n Precio sin IVA: ");
                                       scanf("%f",&inv.psi);
                                       printf("\n Precio oferta: ");
                                       scanf("%f",&inv.po);
                                       printf("\n Proveedor:");
                                       gets(inv.provedor);
                                       getch();
                                       }
      void verinv(){
           system("cls");
           printf("\n 4.  VER INVENTARIO");
                            printf("\n\n  Ingrese Codigo:");
                            scanf("%s",&codigo);

                            if(strcmp(codigo,inv.codigo)==0){
                                     printf("\n Codigo del producto:",inv.codigo);
                                        printf("\n Nombre de la pelicula:",inv.pelicula);
                                        printf("\n Duracion:",inv.duracion);
                                       printf("\n Genero",inv.genero);
                                       printf("\n Director",inv.director);
                                        printf("\n Cantidad: %d",inv.cant);
                                        printf("\n Disponible:%d",inv.disp);
                                       printf("\n Precio al detal %.2f",inv.pdetal);
                                       printf("\n Precio al mayor: %.2f",inv.pmayor);
                                        printf("\n Precio sin IVA: %.2f",inv.psi);
                                       printf("\n Precio oferta: %.2f",&inv.po);
                                       printf("\n Proveedor:",inv.provedor);
           }
           getch();
           }

int main(){
    encabezado();
    while(opc!=5){
                  printf("******MENU******\n");
                  printf("\n1. CREAR CLIENTES");
                  printf("\n2. VER DATOS DE CLIENTES");
                  printf("\n3. CREAR INVENTARIO");
                  printf("\n4. VER INVENTARIO");
                  printf("\n5. SALIR ");
                  printf("\nIngrese opcion: ");
                  scanf("%d",&opc);

                  switch(opc){
                              case 1:{
                                   ingresoc();
                                   system("cls");
                                   encabezado();
                                   }break;
                              case 2:{
                                   verDatos();
                                   system("cls");
                                   encabezado();
                                   }break;
                              case 3:{
                                   ingresoi();
                                   system("cls");
                                   encabezado();
                                   }break;
                              case 4:{
                                   verinv();
                                   system("cls");
                                   encabezado();
                                   }break;
                  }
                  }
                 return 0;

           }

introducir el código aquí

A:
Lo que quiero es que en la opción 2, lea los clientes que he guardado en la opción 1 pidiendo la cedula de cada cliente, es decir, sólo mostrar en pantalla los datos solo del cliente que se pida.

Guarda los clientes en un mapa, clasificados por cédula.
struct cliente{
   std::string nombre, apellido, nempresa, rif;
   std::string direccion;
   std::string sexo;
   std::string ci;

   unsigned int edad;
   unsigned long telfijo, telmovil;
};

using clientes_t = std::map<std::string, cliente>;

clientes_t clientes;

De esta manera será muy fácil buscar clientes mediante su cédula:
std::string cedula;
std::cout << "Busca cliente: ";
std::cin >> cedula;

if (auto found = clientes.find(cedula); found != clientes.end())
    std::cout << "Cliente encontrado:\n" << *found << '\n';
else
    std::cout << "Cliente " << cedula << " no encontrado\n";

Observarás que he hecho varios cambios a tu código. Para empezar, dado que has etiquetado la pregunta como c++ he cambiado todas las formaciones de caracteres a std::string la edad a entero sin signo y los teléfonos a entero largo sin signo (porque 232 es insuficiente para almacenar teléfonos con prefijo internacional) y además te estoy aconsejando usar std::map.
Dicho esto, tu código es un auténtico caos incomprensible: Mezclas cabeceras de C con cabeceras de C++, creas un flujo de salida a archivo (std::ofstream) para no usarlo a la vez que usas utilidades de C (FILE*, printf) y el sangrado de tu código y su distribución haría llorar a las pesadillas Lovecraftianas.
En resumen, tu código no tiene salvación, esta es mi…
Propuesta.
Crea las clases pertinentes con su correspondiente operador de lectura/escritura en flujo de datos:
struct cliente {
   std::string nombre, apellido, nempresa, rif;
   std::string direccion;
   std::string sexo;
   std::string ci;

   unsigned int edad
   unsigned long telfijo, telmovil;
};

// Escritura desde flujo de datos a cliente
std::istream &operator>>(std::istream &i, cliente &c) {
    std::cout << "Nombre: ";
    std::getline(i, c.nombre);

    // […] etc, etc

    std::cout << "Edad: ";
    i >> c.edad;

    // […] etc, etc

    return i;
}

// Lectura de cliente a flujo de datos
std::ostream &operator<<(std::ostream &o, const cliente &c) {
    o << c.nombre << '\n' << c.apellido << '\n' …

    // […] etc, etc

    return o;
}

Con ello, tus funciones de ingreso o búsqueda quedarían así:
void guardar(const clientes_t &clientes) {
    if (std::ofstream archivo{"cliente.txt"}) {
        for (const auto &c : clientes)
            archivo << c.second << '\n';
    } else {
        std::cout << "No se pudo abrir el archivo correctamente. Verifique por favor.\n";
    }
}

void cargar(clientes_t &clientes) {
    if (std::ifstream archivo{"cliente.txt"}) {
        while (archivo) {
            cliente c;
            archivo >> c;
            clientes.insert({c.ci, c});
        }
    } else {
        std::cout << "No se pudo abrir el archivo correctamente. Verifique por favor.\n";
    }
}

void ingresoc(clientes_t &clientes) {
    cliente c;
    std::cin >> c;

    if (auto found = clientes.find(c.ci); found != clientes.end()) {
        std::cout << "El cliente ya existe";
    } else {
        clientes.insert({c.ci, c});
        guardar(clientes);
    }
}

void verDatos(clientes_t &clientes) {
    std::string cedula;
    std::cin >> cedula;

    if (auto found = clientes.find(cedula); found != clientes.end())
        std::cout << "Cliente encontrado:\n" << found->second << '\n';
    else
        std::cout << "Cliente " << cedula << " no encontrado\n";
}

Puedes ver el código funcionando en Wandbox.


text:
Q: Age Calculation with DOB column from Table A and Date column from Table B I am new to Power BI and would like to know how I can calculate the age of a customer based on the DOB from Table A and Date from Table B. Table B is a Date table which is used to select a date period to run the report. So the report runs on Month Year e.g run the report for August 2020 etc
I have tried to use datediff(dob,max(date)),year but i am getting the wrong results. E.g if a customer has birth date 01/08/1991 and i run the report for July 2020, the age should be 28 and not 29.
TIA

A: Do not connect those table, Date table is a Parameter table.
Create a measure:
Average Age =
    VAR _maxDate = MAX('Table B'[Date])
RETURN
   AVERAGEX(
        'Table A',
        INT ( YEARFRAC ( Customer[Birthdate], _maxDate, 1 ) )
   )

source of the code is from sqlbi.com go check the article for more details
Did not tested this out.

A: Instead "year" use "hours" and then transform the result to years


text:
Q: QScintilla: how to create a new lexer or modify an existing one? I find the default lexer for C++ highlighting not very specific enough.
I want to at least be able to specify a different color for:
type keyword (void, int, float etc)
instruction keyword (if while do return for etc)
class-related keyword (template class virtual friend)
type modifiers keywords (static const extern unsigned etc)
I found this in the LexerCPP source:
const char *QsciLexerCPX::keywords(int set) const
{
    if (set == 1)
        return
            "and and_eq asm auto bitand bitor bool break case "
            "catch char class compl const const_cast continue "
            "default delete do double dynamic_cast else enum "
            "explicit export extern false float for friend goto if "
            "inline int long mutable namespace new not not_eq "
            "operator or or_eq private protected public register "
            "reinterpret_cast return short signed sizeof static "
            "static_cast struct switch template this throw true "
            "try typedef typeid typename union unsigned using "
            "virtual void volatile wchar_t while xor xor_eq";

    if (set == 3)
        return
            "a addindex addtogroup anchor arg attention author b "
            "brief bug c class code date def defgroup deprecated "
            "dontinclude e em endcode endhtmlonly endif "
            "endlatexonly endlink endverbatim enum example "
            "exception f$ f[ f] file fn hideinitializer "
            "htmlinclude htmlonly if image include ingroup "
            "internal invariant interface latexonly li line link "
            "mainpage name namespace nosubgrouping note overload "
            "p page par param post pre ref relates remarks return "
            "retval sa section see showinitializer since skip "
            "skipline struct subsection test throw todo typedef "
            "union until var verbatim verbinclude version warning "
            "weakgroup $ @ \\ & < > # { }";

etc
I tried this
- Copy/paste the qscilexercpp.cpp to a new file name qscilexercxx.cpp
- replace the code above by a switch with an appropriate switch:
switch(set)
    {
    case Oper:
        //operators
        return
        "and and_eq bitand bitor "
        "catch compl const_cast "
        "delete dynamic_cast "
        "new not not_eq "
        "operator or or_eq "
        "reinterpret_cast sizeof "
        "static_cast throw "
        "try typeid typename "
        "xor xor_eq";

    case BaseType:
        // basic types
        return
        "bool char double enum float int long "
        "short struct union void wchar_t";

    case ClassRelated:
        // class/template-related
        return
        "class inline friend private protected public "
        "template this virtual";

    case Misc:
        // misc
        return
        "asm namespace typedef using";

    case Modifiers:
        // type modifiers
        return
        "auto const explicit extern mutable register "
        "signed static unsigned volatile";

    case Instruct:
        return
        "break case continue default do else "
        "for goto if return switch while";
    }

After creating the appropriate enum:
    Oper = 20,
    BaseType = 21,
    ClassRelated = 22,
    Misc = 23,
    Modifiers = 24,
    Instruct = 25

At the end of the existing ones.
Now most of my text is black, and I'm pretty sure I missed something about the link between the enum and the char array of keywords returned...
Can somebody direct me to something or help me ?


text:
Q: Grep exact match "/etc" I would like to make an exact search of the string /etc, in the next file:
  -14: _etcrpm    /etc/rpm
  -14: _nssdb_path       /etc/pki/nssdb
  -14: _rpmds_ldconfig_cache      /etc/ld.so.cache
  -14: _sysconfdir        /etc
    -DKDE_DISTRIBUTION_TEXT="%(cat /etc/mandriva-release)" \
  -14: distepoch  %(sed -e 's#.*release\ \(\S*\).*#\1#' /etc/release)
  -14: distro_class       %(. /etc/sysconfig/system; echo $META_CLASS)

I would like that in the output of grep, appears the line that contains only "/etc"
    -14: _sysconfdir        /etc

Can somebody help me with that?
Thank you

A: This should work:
grep -P "(?<=\s)/etc(?=\s|$)" file

Or:
grep -E "\s/etc(\s|$)" file

Or:
grep  "[[:space:]]/etc\([[:space:]]\|$\)" file

Output:
  -14: _sysconfdir        /etc

-P is for Perl regex.
-E is for extended regex.

A: In this case, you could use awk to check if the last word is "/etc"
awk '$NF == "/etc" file


text:
Q: Parameter 'req' implicitly has an 'any' type - Typescript I am new to typescript, I am trying to learn how to use Json Web Token to authenticate a typescript API but I am getting this error whenever I do npm start.
Parameter 'req' implicitly has an 'any' type.
19 app.get('/api', (req, res) => {
                    ~~~

Parameter 'res' implicitly has an 'any' type.
19 app.get('/api', (req, res) => {

This is my code, it is just a simple authentication with JWT
app.get('/api', (req, res) => {
  res.json({
    message: 'Welcome to the API'
  });
});

app.post('/api/posts', verifyToken, (req, res) => {
  jwt.verify(req.token, 'secretkey', (err, authData) => {
    if(err) {
      res.sendStatus(403);
    } else {
      res.json({
        message: 'Post created...',
        authData
      });
    }
  });
});

app.post('/api/login', (req, res) => {
  // Mock user
  const user = {
    id: 1,
    username: 'brad',
    email: 'brad@gmail.com'
  }

  jwt.sign({user}, 'secretkey', (err, token) => {
    res.json({
      token
    });
  });
});

function verifyToken(req, res, next) {
  const bearerHeader = req.headers['authorization'];
  if(typeof bearerHeader !== 'undefined') {
    const bearer = bearerHeader.split(' ');
    const bearerToken = bearer[1];
    req.token = bearerToken;
    next();
  } else {
    res.sendStatus(403);
  }
}

how can I fix this error?

A: If you are using express:
import { Request, Response } from 'express'
app.get('/api', (req: Request, res: Response) => {..}

You can be general and write the code as: (not advised)
app.get('/api', (req: any, res: any) => {..}

A: You have to add the type of the parameter just after it.
app.get('/api', (req:any, res:any) => {


text:
Q: How to create a file-input and store into database using Laravel 4? Here what I have so far, and for some reason,
I couldn't get it to save to database.
I've check everything.
Can someone tell me what did I do wrong ?
But for some reason, the file is save to my local system.
$user                = new User;
        $user->firstname = Input::get('firstname');
        $user->lastname  = Input::get('lastname');
        $user->username  = Input::get('username');
        $user->email     = Input::get('email');

$logo_path = Input::file('logo_path');

        if (Input::hasFile('logo_path'))
        {

            $file            = Input::file('logo_path');
            $destinationPath = base_path().'/app/files/logo_path/';
            $filename        = $file->getClientOriginalName();
            $uploadSuccess   = $file->move($destinationPath, $filename);
            $user->logo_path = $filename;
        }

            return Redirect::to('/users/')
            ->with('success',' Your Account has been created');

        }

A: I notice you forget one most important thing.
Try this  $user->save(); before return Redirect. Let me know.

A: You did not execute save() method your code should be
$user = new User;
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->username = Input::get('username');
$user->email = Input::get('email');

if (Input::hasFile('logo_path'))
        {
            $allowedext = array("png","jpg","jpeg","gif");
            $photo = Input::file('logo_path');
            $destinationPath = public_path().'/uploads';
            $filename = str_random(12);
            $extension = $photo->getClientOriginalExtension();
            if(in_array($extension, $allowedext ))
            {
                $upload_success = Input::file('logo_path')->move($destinationPath, $filename.'.'.$extension);
            }
}

$user->photo = $filename ;
$user->save();
please mind the variable names


text:
Q: Is the infinite regular tree $T_\infty$ quasi-isometric to the $n$-regular tree $T_n$? It is known that for $n\geq 3$ all $n$-regular trees $T_n$ are quasi-isometric to each other. This can e.g. be seen by using an edge contraction argument.
Is there also a quasi-isometry between the countably infinite regular tree $T_\infty$ and some $T_n$?

A: The easiest argument that $T_n$ and $T_\infty$  are not quasiisometric is based on growth, more precisely, it is a fragment the same proof that shows that growth is quasiisometry-invariant:
Every finite valence graph has the "finite packing" property: There exists $\rho\ge 0$ such that for every $R\ge r\ge \rho$, every ball $B(x,R)$  contains only finitely many pairwise disjoint balls of the radius $r$. (One can even take $\rho=0$ for graphs of finite valence.) In fact, if the valence is uniformly bounded like in your case, then the number of such $r$-balls is also uniformly bounded by a function of $R$ and $r$.
The finite packing property is easily seen to be quasiisometry-invariant: If $X_1, X_2$ are quasiisometric metric spaces and $X_1$ has finite packing property then $X_2$ does as well. The finite packing property is clearly false for regular trees of infinite valence.