text:
Q: Phaser warning "Audio source already exists" when mp3 sound sample is played consecutively I'm a bit confused about loading and playing sound effects. My game is setup in different states, first the Preloader state makes sure all images and sounds are loaded. The GameState is the main game, this state is re-started for each next level. There are different levels but the state is the same, it just changes a _levelIndex variable and uses the same state.
The GameState adds the needed audio to the game in the .create() function, and this create-function is called every time the GameState is started. See code below
mygame.Preloader.prototype = {
    preload: function(){

        this.loadingbar_bg = this.add.sprite(80, 512, "loadingbar_bg");
        this.loadingbar_fill = this.add.sprite(80, 512, "loadingbar_fill");
        this.load.setPreloadSprite(this.loadingbar_fill);

        // load sounds
        this.load.audio("button", ["snd/button.mp3", "snd/button.ogg"]);
        this.load.audio("punch",  ["snd/punch.mp3",  "snd/punch.ogg"]);
        this.load.audio("coin",   ["snd/coin.mp3",   "snd/coin.ogg"]);
    },
    create: function() {
        this.state.start("MainGame");
    },
};

mygame.GameState.prototype = {

    create: function() {
        this.stage.backgroundColor = "#f0f";
        // etc.

        // sound effects
        this.sound1 = this.game.add.audio("button");
        this.sound2 = this.game.add.audio("punch");
        this.sound3 = this.game.add.audio("coin");
        //etc.
    },

    update: function() {
        if (hitFace) {
            this.sound2.play();
            hitFace = false;
        };
    },

    doNextLevel: function() {
        this.sound1.play();
        this._levelIndex++; // next level
        this.state.start("MainGame"); // restart this state
    },
    //etc.
};

The problem is that when I play the punch sound a couple of times in a row a couple of seconds apart, the console gives this warning (which Phaser raises in code here)

Phaser.Sound: Audio source already exists

This warning appears even when the GameState is started for the first time.
I suspect that it has to do with decoding the mp3 and ogg sounds. Do I have to decode the sound samples every time the player starts (or restarts) a level i.e. restart the GameState? In other words, if the GameState will be .create() each time a level is (re)started and the audio samples are added using game.add.audio, will the decoded samples from the previous level be destroyed and have to be reloaded/decoded each time? That seems wasteful, what is the best way to do this? So my questions are:

*

*What does this message "Audio source already exists" mean ? Or
should I ignore it?

*if I want to use sounds in a state, do I have to re-add them every time the state is started and .create() is called ?

*also somewhat related, if I want to use the same sound sample in multiple different States (menu, game, options etc.) do I have to do game.add.audio() for the same sound for each state?

A: Well, as far as I can see you code seems to be doing things right. So I will try to answer your questions with the knowledge I have:
1. What does this message "Audio source already exists" mean ? Or should I ignore it?
The message means that there is already an instance of that sound playing as you can see in the place where it is raised:
if (this._sound && ***!this.allowMultiple***)
    {
        console.warn('Phaser.Sound: Audio source already exists');

        // this._disconnectSource();
    }

It will throw this error if the sound you are trying to play is already being played by Phaser.Sound and if is not allowMultiple... There it is the quid of the issue. AllowMultiple from source code:
/**
* @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels.
* @default
*/
this.allowMultiple = false;

So basically is complaining that you are trying to spawn several instances of a sound that is not being allow multiple times. You shouldnt ignore it, but instead use the right flags.
Questions 2 and 3:
You shouldnt have re-add the resource, since thats why you load in the engine the source of audio, to can be reused through all the levels. Nor you have to do it for all the states.
In order to reuse an Sound in multiple states, you should be able to add the audio or any game object in the global scope and access it (Here I found someone trying to do what you ask in the question)
Other ways will be to add this resources as an attribute to the game object, so you dont contaminate the global scope but only the Game object context.
But I believe that is better strategy to add this audios in different states and manage their deletion/creation in the states. Mainly because JS is evil* and mutability may play a bad card on you
*Not that evil
To resolve this warning: Simply use the flag allowMultiple (created in here), eg:
    this.sound1 = this.game.add.audio("button") // allowMultiple is false by default
    this.sound2 = this.game.add.audio("punch");
    // Allow multiple instances running at the same time for sound2
    this.sound2.allowMultiple = true;
    this.sound3 = this.game.add.audio("coin");
    // Allow multiple instances running at the same time for sound3
    this.sound3.allowMultiple = true;


text:
Q: Fatal errors installing a package from source in R due to zstd I am trying to install gwsem (v2.1.5) in R (v4.2.1) on an intel MacBook Pro.  I know the package was removed from CRAN, but the GitHub lists detailed instructions for installing from source.  However, I have tried both in R and in the command line to install it, but I receive the error each time.  The instructions for install are
git clone https://github.com/jpritikin/gwsem
cd gwsem
./tools/rox
cd ..
R CMD INSTALL gwsem R_LIBS_USER
Rscript tools/test.R

I know it requires roxygen2 to run, so using install_github or devtools doesn't work.  Each time I get to ./tools/rox and it fails with the following:
./tools/rox

R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid"
Copyright (C) 2022 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin17.0 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> library(roxygen2)
> pkgload::load_all()
ℹ Loading gwsem
Re-compiling gwsem
─  installing *source* package 'gwsem' ...
   ** using staged installation
   ** libs
   clang++ -mmacosx-version-min=10.13 -std=gnu++14 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG  -I'/Library/Frameworks/R.framework/Versions/4.2/Resources/library/BH/include' -I'/Library/Frameworks/R.framework/Versions/4.2/Resources/library/Rcpp/include' -I/usr/local/include      -I. -Iinclude  -fPIC  -Wall -g -O2  -UNDEBUG -Wall -pedantic -g -O0 -fdiagnostics-color=always -c bgen.cpp -o bgen.o
   In file included from bgen.cpp:14:
   In file included from include/genfile/bgen/bgen.hpp:20:
   include/genfile/zlib.hpp:14:10: fatal error: 'zstd.h' file not found
   #include <zstd.h>
            ^~~~~~~~
   1 error generated.
   make: *** [bgen.o] Error 1
   ERROR: compilation failed for package 'gwsem'
─  removing '/private/var/folders/9x/x3jyk269287916gzlmg35kyh0000gn/T/RtmpjDZzGD/devtools_install_582f289c75a6/gwsem'
Error in `(function (command = NULL, args = character(), error_on_status = TRUE, …`:
! System command 'R' failed
---

If I try to use the "remotes" package in R and install from GitHub using remotes::install_github("jpritikin/gwsem") I have the same error message about the zstd.h file. I have re-installed zstd to make sure there wasn't an error there and made sure all of the dependency packages are installed and ready for use.
Any help to get this package installed and running in R would helpful!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting Class Object Array Property I'm trying to set a property of an object which is part of a class object array, for excel in VBA.
The code looks like this:
Dim myClass(5) as class1
Dim i as integer

For i = 0 to 5
    set myClass(i) = New class
    myClass(i).myProperty = "SomeValue"
Next i

Class code is simply:
Private pmyProperty as string

Public Property Let myProperty(s as string)
    pmyProperty = s
End Property
Public Property Get myProperty() as string
    myProperty = pmyProperty
End Property

However when I run this, I get a compile error "expected: list separator." This hits on the myClass(i).myProperty = "SomeValue" line.
How do I set the value of a property of an class object that is part of an array?
Any help would be great!

So the actual code is as follows...
Module code:
Public Sub main_sb_BillingApp()

    Dim intCountComplete As Integer
    Dim intLastRow As Integer
    Dim Line() As clsLine
    Dim i As Integer, x As Integer

    intCountComplete = WorksheetFunction.CountIf(Sheets(WS_NAME).Columns(COL_W_COMPLETE), "Yes")
    intLastRow = Sheets(WS_NAME).Cells(LAST_ROW, COL_W_COMPLETE).End(xlUp).Row - 1

    ReDim Line(intCountComplete - 1)

    For i = ROW_W_HEADER + 1 To intLastRow

        If Sheets(WS_NAME).Cells(i, COL_W_COMPLETE) = "Yes" Then

            Set Line(x) = New clsLine
            Line(x).Row = i
            x = x + 1

        End If

    Next i

End Sub

Class code:
Private pDate As Date
Private pUJN As String
Private pDesc As String
Private pCharge As Currency
Private pCost As Currency
Private pMargin As Double
Private pComplete As Boolean
Private pRow As Integer

Public Property Let Row(i As Integer)
    pRow = i
    Update
End Property
Public Property Get Row() As Integer
    Row = pRow
End Property

Private Sub Update()

    With Sheets(WS_NAME)

        pDate = .Cells(pRow, COL_W_DATE)
        pUJN = .Cells(pRow, COL_W_UJN)
        pDesc = .Cells(pRow, COL_W_DESC)
        pCharge = .Cells(pRow, COL_W_CHARGE)
        pCost = .Cells(pRow, COL_W_COST)
        pMargin = .Cells(pRow, COL_W_MARGIN)

        If .Cells(pRow, COL_W_COMPLETE) = "Yes" Then
            pComplete = True
        Else
            pComplete = False
        End If

    End With
End Sub

A: Line is a VBA reserved keyword, so you're confusing the compiler.  Change the name of your object array and it works just fine:
Dim lineArray() As clsLine
'...

        Set lineArray(x) = New clsLine
        lineArray(x).Row = i


text:
Q: Enable clean urls through htaccess - modrewrite in Drupal I'm trying to set up a Drupal installation to be able to have clean urls. I have searched for the .htaccess-file in the root-folder, but haven't found it. In the phpinfo-file I created, I see under Loaded Modules mod_rewrite, so it is enabled on the server.
I created a .htaccess-file which contained a simple
RewriteEngine On

But when I ran the test under Configuration -> Search and metadata -> Clean URLs, it still failed. I then uploaded a .htaccess-file a friend sent me from a Drupal installation, but the test still failed.
What now?

A: The .htaccess for Drupal is a lot more complicated than a single line, I suggest you download a fresh copy of Drupal and take the .htaccess file out of the root folder and use that. If you can't find it I suggest turning on hidden files, there are different ways of doing this depending on your OS.
For a quick fix sake, adding these lines should sort your issue:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]


text:
Q: Autocomplete for dynamically created input Sorry for asking something that has been already asked by people (for instance here :
jQuery autocomplete for dynamically created inputs)
but i cannot make work it despite the help i found on internet.
So, i need to use Jquery autocomplete with dynamically created inputs.
My code looks as follows:
$("#add_ligne2").live("click", function() { ...
         if (nb_ligne < 10) {
            var html = "";
            var next_ligne = last_ligne;
            html = '
';
            html += '<input type="text" id="autoCompleteProjets' + next_ligne + '"/>	';
            html += '
';
            $("#content_tr").append(html);
            $('#autoCompleteProjets1', html).autocomplete(autocomp_opt);
         }
      }
      var autocomp_opt = {
         source: "/index/autocomplete",
         minLength: 2,
         select: function(event, ui) {
            /* console.log( ui.item ?
                 "Selected: " + ui.item.value + " aka " + ui.item.id :
                 "Nothing selected, input was " + this.value
             );*/
            $('.hidden').val(ui.item.id);
         }
      }

A: You use fixed id "autoCompleteProjets1", I believe you want "autoCompleteProjets" + next_ligne
$('#autoCompleteProjets' + next_ligne, html).autocomplete(autocomp_opt);

You might already have it, but I'll mention it anyway - make sure you initialize last_ligne outside of the anonymous function, else you create local variable, which is unset once out of scope:
var last_ligne = 0;

Then, you don't increment the last_ligne variable, use this:
var next_ligne = ++last_ligne;

And most important: use firebug in firefox, or equivalent for other browsers, to find out what you really generate.


text:
Q: How to take backup of package of Webrole in the new Azure Resource manager Fluent I need to take backup of web role package and store it in a azure storage
In the older version of I had use Azure Management Library
https://www.nuget.org/packages/Microsoft.WindowsAzure.Management.Libraries/
            string deploymentName = computeClient.Deployments.GetBySlot(serviceName, DeploymentSlot.Production).Name;
            string label = computeClient.Deployments.GetBySlot(serviceName, DeploymentSlot.Production).Label;

            DeploymentGetPackageParameters packageParam = new DeploymentGetPackageParameters();

            Uri containerUri = new Uri(storageBackupURI);
            string containerName = containerUri.AbsolutePath.Remove(0, 1);

            packageParam.ContainerUri = containerUri;
            packageParam.OverwriteExisting = true;

            Console.WriteLine("Copying Package");
            OperationStatusResponse osr = computeClient.Deployments.GetPackageByName(serviceName, deploymentName, packageParam);

how would I accomplish using fluent api.
https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent

A: It seems that currently this Library v1.0.0 supports major parts of Azure Virtual Machines, Virtual Machine Scale Sets, Managed Disks, Storage, Networking, Resource Manager, SQL Database, App Service, Key Vault, Redis, CDN and Batch etc. Cloud Services are not supported and this library will only support Azure Resource Manager Providers, you could find the below info from this blog.

To manage Cloud Services, as you did in your earlier project, you could still use Microsoft.WindowsAzure.Management.Libraries.
Besides, you will find "Feature Availability and Road Map as of Version 1.0.0" in this article.


text:
Q: Spring-data-mongodb not persist multiple objects on list I am using Spring-data-mongodb and i can persist an object on a list, but when i try to add another, it doesn't work, the application doesn't throw an exception.
this is my Json:
[
  {
    idUser: "4a9f10d9-e19f-42af-ba00-891a567cc41f",
    login: "peter",
    password: "mypassword",
    email: "peter@eeee.com",
    patients:
      [
        {
          idPatient: "d31e8052-36d3-4285-9f97-454f3437812d",
          name: "ada",
          birthday: 1363474800000,
          idUser: "4a9f10d9-e19f-42af-ba00-891a567cc41f",
          region:
          {
            idRegion: "d8acfa45-486e-49e0-b4e6-edde6743cf30",
            name: "Madrid"
          },
          personalCalendars: null
        },
        null
      ]
   }
]

As you can see, my first Patient element is correctly, and the second was insert as null.
I leave my code:
User.java
@Document(collection = "users")
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private String id;

@Indexed
private UUID idUser;

@Indexed(unique = true)
private String login;

private String password;

@Indexed(unique = true)
private String email;

@DBRef
private List<Patient> patients;

@PersistenceConstructor
public User(UUID idUser, String login, String password, String email, List<Patient> patients){
    this.idUser = idUser;
    this.login = login;
    this.password = password;
    this.email = email;
this.patients = patients;
}

Patient.java
@Document(collection = "patients")
public class Patient implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private String id;

@Indexed
private UUID idPatient;

private String name;

private Date birthday;

private UUID idUser;

private Region region;

@Transient
private List<PersonalCalendar> personalCalendars;

@PersistenceConstructor
public Patient(UUID idPatient, String name, Date birthday,UUID idUser, Region region){
    this.idPatient = idPatient;
    this.name = name;
    this.birthday = birthday;
    this.idUser = idUser;
    this.region = region;
}

and the DAO whereI do the insert.
@Override
public Patient createPatient(User user, Patient patient) {
    this.mongoOps.save(patient , "patients");
    this.mongoOps.save(user , "users");
    return this.getPatientById(patient.getIdPatient());
}

The console returns this, but no persists the patient:
15:16:16.718 [tomcat-http--6] DEBUG o.s.data.mongodb.core.MongoTemplate - Saving DBObject containing fields: [_class, _id, idPatient, name, birthday, idUser, region]
15:16:16.723 [tomcat-http--6] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[application]
15:16:16.747 [tomcat-http--6] DEBUG org.mongodb.driver.protocol.insert - Inserting 1 documents into namespace application.patients on connection [connectionId{localValue:2, serverValue:119}] to server 127.0.0.1:27017
15:16:16.761 [tomcat-http--6] DEBUG org.mongodb.driver.protocol.insert - Insert completed

I need help.
Thanks a lot

A: First, if you use Spring Data with MongoDB, use it properly:
@Repository
public interface UserRepository extends MongoRepository<User, String> {

}

Now just inject UserRepository via @Autowired annotation:
@Autowired
private UserRepository userRepository;

User user = new User();
Patient patient = new Patient();
user.addPatient(patient);

// Just call save from userRepository to save your User with Patient.
// save method will return instance of saved user (together with instance of
// patient)
User user = userRepository.save(user);

Note that save method can also be used for updating of existing User. If User is new (not having generated id) it will be inserted. If user exists (has generated id) it will be just updated.
Presuming that User class has a addPatient method that looks like this:
public void addPatient(Patient patient) {
    this.patients.add(patient);
}

Also, make sure that your list is initialized: List<Patient> patients = new ArrayList<>();


text:
Q: ng-include not getting file name with utf-8 character I have the ng-include below, the file name it's getting contains an ñ character so it's showing an not found error.

I also tried using decodeURI like the code below before passing it to the ng-include but it didn't work.
self.name = decodeURI(self.name);

I already have <meta charset="utf-8"> and


text:
Q: sum corresponding rows from multiple csv into pandas dataframe i have 10 csv files which all have 1000 rows with data. i want to get the sum row 1 of all csv files and row 2 of all csv files and so on so in the result i have in the best case a pandas dataframe with 1000 rows which are the sum of each row in the csv files so i can get the average, min and max value of the 10 csvs combined. does that make sense?
my code:
import pandas as pd
import glob
import csv

testfiles= glob.glob('flasktests*.csv')
#print(testfiles)

for file in testfiles:
    with open(file, "r") as f:
        reader = csv.reader(f, delimiter="\t")
        next(reader)
        for i, line in enumerate(reader):
            print(file, line[0])
            #sum = int(line[0])+int(line[0])
            #print (sum)

df = pd.concat((pd.read_csv(file) for file in testfiles))

#with pd.option_context('display.max_rows', None, 'display.max_columns', None):  # more options can be specified also
print(df)

min = df["elapsedtime_ms"].min()
max = df["elapsedtime_ms"].max()
avg = df["elapsedtime_ms"].mean()

#print(df.columns.tolist())
print("fastest response time",min)
print("slowest response time",max)
print("average response time:",f"{avg: .3f}")

i tried it with variables but i didnt get any result.
the dataframe which is shown as "df" is showing the values of all csv files. so it contains 10000 rows.
any ideas?
thank you!


text:
Q: Value not getting removed from Firebase I'm trying to remove some value stored at a particular reference on Firebase. Here's how I have stored it:
mDatabase.child("users").child(uid).child("followersUID").child(itemIDFU).setValue(MainActivity.uid);

Here's how I'm trying to remove it:
mDatabase.child("users").child(uid).child("followersUID").child(itemIDFU).child(MainActivity.uid).removeValue();

itemIDFU has been generated in onCreate() using this code:
itemIDFU = mDatabase.child("users").child(uid).push().getKey();

The problem is that it is getting stored successfully, but not getting removed. What's going wrong here? Please let me know.

A: It looks like when you set the value, you set the key itemIDFU to equal whatever value is in MainActivity.uid
However, when you delete the data, you are trying to get the child of itemIDFU, which doesn't exist.
You didn't add MainActivity.uid as the child of itemIDFU, you added it as the value.
You have two possible solutions:
Try this if you want to remove the value, but leave the itemIDFU key there empty:
mDatabase.child("users").child(uid).child("followersUID").child(itemIDFU).setValue(null);

Try this if you want to completely remove the key and value:
mDatabase.child("users").child(uid).child("followersUID").child(itemIDFU).removeValue();

Here is a picture to help illustrate the data and the problem:

One more picture to explain

A: You can remove values in these two ways:
//first way to remove a value
mDatabase.child("users").child(uid).child("followersUID").child(itemIDFU).setValue(null);

//or try this
mDatabase.child("users").child(uid).child("followersUID").child(itemIDFU).removeValue();

I feel that the value is not getting removed as you are adding .removeValue() on value of child rather than child itself.


text:
Q: Respect\rest nao funciona ao tentar implementar no meu projecto Estou testando uma aplicacao web, mas preciso implentar o uso de routas e achei melhor trabalhar com Respect\rest. Segui todas as instrucoes de uso da class, mas nao consigo imprimir se quer um Ola mundo na tela, o que sera que esta errado?
Arquivo index.php
  use Respect\Rest\Router;
  chdir( __DIR__ . '/..');
  require 'vendor/autoload.php';

  $router = new Router();
  $router->get('/','Hello World');

Fiz a instalacao da class Respect\Rest via composer, mas estou testando faz tempo nada acontece.
Aqui esta o meu composer.json
  {

    "autoload": {
       "psr-4": {
         "App\\": "src/App"
       }
    },
    "require": {

    "respect/rest": "^0.6.0"
    }
  }

A: Acredito que o problema esteja na inclusão do autoload.php, que por sua vez inclui todas as dependências no seu projeto.
Eu faria da seguinte maneira:
require_once(__DIR__ . '/vendor/autoload.php');

use Respect\Rest\Router;

$router = new Router();
$router->any('/', function() {
    return 'Funcionou.';
});

PS: essa é a estrutura de diretórios com a qual trabalhei:
.
├── composer.json
├── composer.lock
├── index.php
└── vendor
    ├── autoload.php
    ├── composer
    └── respect


text:
Q: Change datetime format on a column of a dataframe Lets say I have a dataframe with only one column A below, rows under A are string as below.
           A
0 15/01/2022
1 16/01/2022
2 17/01/2022
3 18/01/2022
4 19/01/2022
5 20/01/2022

How can I convert them into string format like "2022-01-15"?


text:
Q: Combing "click" and "hover" permanently? I want to have the click and drag functionality that Raphael.js provides, an example here: https://qiao.github.io/PathFinding.js/visual/.
The way you add and remove obstacles is great, it's essentially combining mousedown event and hover. But how on earth is that done? Any help please?
The closest I have is: https://codepen.io/ProgrammingKea/pen/ZowWJx
The salient bit is
  div.addEventListener("mousedown", function(ev){
     this.classList.add("obstacle");
     });
     div.addEventListener("mousemove", function(ev){
     this.classList.add("obstacle");
     });
     div.addEventListener("mouseup", function(ev){
     this.classList.add("obstacle");
     });

If you press large, then hover over the grid, that's the closest I've got.
But my issue is that its only hover here, I don't have the click functionality the above link does
Please post answers containing only vanilla JS

A: You can use something like:
["mousedown", "mousemove", "mouseup"]
  .forEach(function (eve) {
    div.addEventListener(eve, function(ev){
      this.classList.add("obstacle");
    });
  });

A: It maybe feels a bit clunky putting a handler on every element. I'd be tempted to put a handler on the main container and then check from there...
Maybe first add a bit of code to check if mouse is down.
var main = document.getElementById('main')

var mouseDown = 0;
main.onmousedown = function() {
  mouseDown=1;
}
main.onmouseup = function() {
  mouseDown=0;
}

Then we can check if a mouse is down or over event...
main.addEventListener('mouseover', mousecheck)
main.addEventListener('mousedown', mousecheck)

Then we preventDefault (stop a drag).
If the mouse is down, and the element being acted on is a box, then we'll change it's colour.
function mousecheck( ev ) {
  ev.preventDefault();
  if( mouseDown && ev.target.className.startsWith( 'box') ) {
    ev.target.style.backgroundColor = ev.target.style.backgroundColor == "red" ? 'white' : 'red';
  }
}

Codepen


text:
Q: mod_rewrite: Different rules on different domains, same www-root I have 8 domainnames that point to the same www-root. If the main domain is accessed, you are pointed to index.php, and from there on, the URL's are like: index.php?p=contact etc. If, however, you access one of the other 7 domains, that point to different units, you are initially pointed to: index_local.php, and from there on it goes like: index_local.php?p=contact etc.
As you may see these URL's are very ugly, can I use mod_rewrite in this scenario to make it so that index.php AND index_local.php never show up in URL? Is there any better way to do this than the way I'm pointing the user now with multiple domains in the same www-root?

A: Something like this should help hide the index* URLs:
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond    %{HTTP_HOST}    ^domainname1.com
RewriteRule    ^/(.*)$    index.php?p=$1 [L]

RewriteRule    ^/(.*)$    index_local.php?p=$1 [L]
</IfModule>

There are other ways to do this cleanly, if your willing to change some code, but this should work with the code you have.


text:
Q: How to get the duration inside the rolling window from he DatetimeIndex in Pandas I am trying to calculate time duration inside of each sliding window for this data:
                                ID
    DATE
    2017-05-17 15:49:51         2
    2017-05-17 15:49:52         5
    2017-05-17 15:49:55         2
    2017-05-17 15:49:56         3
    2017-05-17 15:49:58         5
    2017-05-17 15:49:59         5

In this example DATE is the index, and I am trying to get the duration inside rolling window of size 3 which overlap each other. Answer should be like this:
                                ID      duration
    DATE
    2017-05-17 15:49:51         2        4
    2017-05-17 15:49:52         5        4
    2017-05-17 15:49:55         2        3
    2017-05-17 15:49:56         3        3
    2017-05-17 15:49:58         5        NaN
    2017-05-17 15:49:59         5        NaN

I tried:
df['duration'] = df.rolling(window=3).apply(df.index.max()-df.index.min())

But I got this error:
TypeError: 'DatetimeIndex' object is not callable

A: df.reset_index(inplace=True)
df['PREVIOUS_TIME']= df.DATE.shift(-2)
df['duration']=(df.PREVIOUS_TIME-df.DATE)/np.timedelta64(1,'s')
df.drop('PREVIOUS_TIME',axis=1,inplace=True)
df.set_index('DATE',inplace=True)

Assuming that 'DATE' is a datetime.

A: def timediff(time_window: pd.Series) -> float:
    duration = time_window.index.max() - time_window.index.min()
    return duration.total_seconds()

df['duration'] = np.nan
df['duration'] = df.duration.rolling(window=3).apply(func=timediff, raw=False)

I've just stumbled across this question and wanted to provide a solution using the rolling window approach:
with raw=False (default) you provide a Series to the function, so you can use index.max() - index.min() or index[-1] - index[0]
The only problem is that you need to return a number and not a timedelta object.


text:
Q: Realization of iterative root-finding algorithm I need realize algorithm for finding roots with specified precision by iterative method. Main idea of this method is Cn=f(Cn-1); C0=(A+B)/2; where a,b-boundary of interval comprising roots. I wrote this code(in Delphi7)
program iter;

{$APPTYPE CONSOLE}

uses
  SysUtils,Math;

function GetCn(Cn1:Double):Double;
begin
   Result:=Cn1+sin(1/Cn1);
end;

var
  a,b:Double;
  Cn,Cn1:Double;
  eps,eps1:Double;

begin
  a:=1.2;b:=2;
  Cn:=(a+b)/2;
  Write('Input precision ');Readln(eps);
  eps1:=Abs(Cn-Cn1);
  While eps1>eps do
  begin
    Cn1:=Cn;
    Cn:=GetCn(Cn);
    eps1:=Abs(Cn-Cn1);
  end;
  Writeln(Cn);
  Readln;
end.

In test data f(x)=x-2+sin(1/x); a:=1.2 b:=2.0 eps:=0.001 my programm give answer  1.00000143538244E+0003, but in set of problems is answer 1,3077
Why is it so? Where do i error? How to correct?
P.S Sorry fo my English

A: Your algorithm is not a root finder. To recap, your recursive step is
Cn = f(Cn-1)
and you terminate when Cn equals Cn-1 up to tolerance.
That algorithm may find fixed points, but it won't find roots. To find roots you need something like Newton's method, bisection, secant method, etc.
Even as a fixed point finder, your code is broken. The first time the code performs the termination test, it reads the value of Cn1 before initializing it.

In the comments you tell us that you asked the wrong question, and that you are trying to find fixed points. In which case you just need to modify the code to avoid reading variables before they are initialised:
begin
  a:=1.2;b:=2;
  Cn:=(a+b)/2;
  Write('Input precision ');Readln(eps);
  repeat
    Cn1:=Cn;
    Cn:=GetCn(Cn);
    eps1:=Abs(Cn-Cn1);
  until eps1<=eps;
  Writeln(Cn);
  Readln;
end.

Also the function in your code doesn't match the one in the question. I don't know which one is right.


text:
Q: Installed PHP on CentOS, some features not working I followed this guide to install PHP 5.3 on my CentOS 5 server:
http://www.webtatic.com/packages/php53/
I have phpMyAdmin extracted in a directory but it says it can't find the mysql extension. Moreover, I know I'll need the mysqli extension for other programs such as Drupal. The guide I followed says that those extensions come with it. When I run php -m it shows both mysql and mysqli though - that's where I'm puzzled.
I restarted apache and still no go. Where do you think my next step is?
phpinfo say my ini is in /etc/php.ini - should I be looking in there for something?
Thanks so much.

A:
I have phpMyAdmin extracted in a directory but it says it can't find
  the mysql extension.

Make sure that php-mysql is installed:
# yum --enablerepo=webtatic install php-mysql

Don't forget to restart the Apache after that.

A: Check /etc/php.d for mysql.ini and mysqli.ini as well


text:
Q: Can data.table's fread accept connections? I have an executable that I can call using the system() command. This executable will print some data which I can pipe into R using:
read.csv(pipe(command))

fread has amazing performance which I would like to take advantage of bringing the data in, but I cannot use fread(pipe(command)). The alternative is to use the executable and dump its output to a file first, then read it in using fread. Doing so requires writing intermediate data to disk, and also adds overhead by introducing that intermediate step. Is there a way to wrap or use fread with my executable?

A: fread can't take connections for now and the feature has been requested in 2015: https://github.com/Rdatatable/data.table/issues/561
Even though Maksim's comment would be valid, it would not work on a windows machine.  Which, in some cases can be troublesome.


text:
Q: How do I force Eclipse to rebuild if files in another project change (any change)? I've got an Eclipse (Galileo) project (called ProguardBuilder) that runs Proguard over a set of class files in other projects and produces a jar file.
I'd like to have the ProguardBuilder project get rebuilt any time any class file in the other projects changes.  AutoBuild doesn't do that; presumably it's smart enough to recognize and ignore any changes that don't affect anything externally visible.
My problem is that I don't care whether or not the change is visible, since I need to completely rebuild ProguardBuilder any time the class files it depends on change at all.
How do I tell Eclipse to do this sort of rebuild?

A: You might have to use an external builder. Check the documentation, because I've never done this. But the place to start is the "Builders" section of the project properties dialogue.


text:
Q: phpmyadmin El servidor MySQL no autorizó su acceso en Mac Big Sur MySQL 8.0.30 Tengo el siguiente error si pongo la contraseña a root 1234 me dice
mysqli::real_connect(): (HY000/2002): No such file or directory

Si quito la contraseña a root me dice
 El inicio de sesión sin contraseña está prohibido por la configuración (ver AllowNoPassword)

He intentado todo lo que dice en el foro, por ejemplo
ALTER USER 'userdb'@'localhost' IDENTIFIED WITH mysql_native_password BY 'userdbpassword';
ALTER USER 'userdb'@'%' IDENTIFIED WITH mysql_native_password BY 'userdbpassword';

Y reemplazando userdb por root y userdbpassword por 1234 y nada Persiste el error, no puedo ingresar con phpmyadmin.
Tambien me he dado cuenta que al reiniciar el sistema, si vuelvo abrir la terminal no puedo ejecutar mysql desde el terminal, para ejecutarlo debo escribir el PATCH para comenzar a usar el comando mysql por ejemplo:
export PATH=${PATH}:/usr/local/mysql/bin

A que se debe esto?


text:
Q: How to force a submit button in iframe to open in parent window I have a page being embedded into iframe.
The iframe contains a form and submit button.
I am trying to make the submit button then load result into the parent (not the iframe).
I have tried base=parent in head and also in the button/form target but it does not work.
URL inside iframe : https://www.purelocal.com.au/search-iframe
When the 1st form is submitted - it does load in parent.
When the 1st and 2nd form are submitted - it DOES NOT load in parent.

A: The quick and dirty way of doing this is to add the following to the top of the results page, this will force it to reload where you want it.
if(window.top!==window.self) {
  window.top.location=window.self.location
}

The perhaps better way would be to read in all the data on your form, then use JS to recreate the form on the parent page and submit it from there.


text:
Q: Resistor simplification I am trying to simplify the following portion of a circuit for analysis.  I am not sure if it would simply be shown as 2 resistors in parallel or something else as the nodes are connected.   I do not have the resistor values currently, so I need to derive an equation for the resistance at a,b, and c.
Edit: I am looking for the resistance between a-b and b-c.

Thanks

A: The equivalent resistance (aka impedance) that can replace resistors in parallel can be written like this:
\$R_{parallel} = \frac{1}{\frac{1}{R_1}+\frac{1}{R_2}+..}Ω\$
This means that if \$R_1 = 53Ω\$ and \$R_2= 205Ω\$ then you can replace both of those two with one resistor that has the value \$\frac{1}{\frac{1}{53}+\frac{1}{205}}=42.1Ω\$
Or it can be written like this if it's just two resistors in parallel.
\$R_{parallel} = \frac{R_1×R_2}{R_1+R_2}\$
With the same example numbers as above, \$\frac{53×205}{53+205}=42.1Ω\$
For 3 resistors in parallel it's not \$\frac{R_1×R_2×R_3}{R_1+R_2+R_3}\$, it's \$\frac{R_1×R_2×R_3}{R_1×R_2+R_2×R_3+R_1×R_3}\$.
I derived this expression from the first equation above (\$\frac{1}{...}\$).
The equivalent resistance that can replace resistors in series can be written like this:
\$R_{series} = R_1+R_2+...\$
When I write "..." I mean that the terms can be repeated if you have more resistors.

With the information above together with the schematic we can arrive to the conclusion:
The resistance between a and rotated b is equal to \$\frac{R_1×R_2}{R_1+R_2}\$
The resistance between rotated b and c is equal to \$\frac{R_3×R_4}{R_3+R_4}\$
The resistance between a and c is equal to \$\frac{R_1×R_2}{R_1+R_2}\$+\$\frac{R_3×R_4}{R_3+R_4}\$


text:
Q: Orientation and simplicial homology I'm reading Chapter 2 of Hatcher's Algebraic Topology, and I just can't figure out the computations of the boundary homomorphism for the examples provided. To provide some context, reproduced the figure for the torus from the book below:

As I understand it, to compute $\partial U$ we follow the faces (which are edges) counter-clockwise, negating an edge if the oriented arrow is "facing us." But starting in the top right corner and working around U results in $\partial U = (-1)^0 (-b) + (-1)^1 (-a) + (-1)^2 c = a - b + c$, which contrasts with the book's result of $\partial U = a + b - c$. I seem to be making some critically flawed assumptions. What am I not understanding?

A: I don't understand your description of the boundary map, or your explicit calculation.  Here is how the calculation goes:
Imagine that you are standing in $U$, making a counterclockwise pivot, and looking at the boundary (in the naive sense) as you do so.  Let's begin facing the top right corner.  As we turn, our field of vision sweeps out $b$, but in the opposite direction to its arrow (we sweep out $b$ from right to left, while the arrow points from left to right), then $a$, again in the opposite direction to its arrow, and finally $c$, in the same direction as its arrow.
So $\partial U = -b - a + c$.  (If the text instead writes it as $a + b - c$, it must use the opposite orientation on $U$, i.e. a clockwise, rather than counterclockwise, orientation.)
The same procedure applied in $L$, starting by facing the lower right corner, yields $\partial L = a - c + b$, which is $- \partial U$, as one would expect.  (When you glue the $U$ and $L$ into a torus, the boundaries get glued to together, and so "cancel" one another.)


text:
Q: Parsing a binary Redis key I wrote a 16-byte binary key to Redis. When I query the key, it comes back in the following format:
\xc9;\xfd5\x80\x00\xa9Z\xc9\x0fb\xef\x7f\xd6V]

What format is this string? It looks like it ought to be hex (\x) but there are other characters in there that aren't valid hex characters.
How do I convert this string back into my original byte array byte[] (using C#)?

A: It seems that you write a byte array byte[] but read it as a string. Some codes like 0x35 correspond to valid ASCII characters ('5'), some codes like  0x00 are not and thus represented as \x00 and so you have a strange looking string.
Let's try to parse the composed string back to original byte[].
First, let's get rid of \x.. format and have a valid string with a help of regular expressions:
  using System.Text.RegularExpressions;

  ...

  string source = @"\xc9;\xfd5\x80\x00\xa9Z\xc9\x0fb\xef\x7f\xd6V]";

  string result = Regex.Replace(
    source,
   @"\\x[0-9A-Fa-f]{2}",
    m => ((char)Convert.ToInt32(m.Value.Substring(2), 16)).ToString());

Second, let's get byte[] from the string, assuming that all characters are ASCII:
  byte[] array = result
    .Select(c => (byte)c)
    .ToArray();

Let's have a look at the array:
  Console.Write(string.Join(", ", array.Select(x => $"{x:x2}")));

Outcome:
  c9, 3b, fd, 35, 80, 00, a9, 5a, c9, 0f, 62, ef, 7f, d6, 56, 5d


text: Q: Prediction Intervals in Ridge Regression? For some reason, I can't seem to find the formula for prediction intervals in ridge regression anywhere.  I know that the coefficient estimates are biased, but are the predictions (dependent variable) biased as well?


text:
Q: Log4j2: Logs not sent to Console where as logs to file works fine I am a newbie to log4j. My log4j configuration is not writing logs to Console where as the logs to File is working fine. I am not able to troubleshoot this issue inspite of refering earlier posts.
I have two appenders - one for Console and the other for File. I intend to write ERROR and FATAL to file hence using level=ERROR. I intend to write all logs to console hence using level=TRACE for Console.
My code contains just one package named 'parallel', has one class named ClassA with one method that logs all types of logs.
If I specify both Console and File appenders within Root tag then my expectations are met. If I move the File appender outside Root and mention it under Logger tag then only File appender works where as Console appender does not work. Is it mandatory that all appenders be placed under Root tag?
package parallel;
public class ClassA {
private final   Logger log = LogManager.getLogger(ClassA.class);
@Test
public void testLogs() {
    log.info("info");
    log.debug("debug");
    log.warn("warn");
    log.error("error");
    log.fatal("fatal");
    log.trace("trace");
}

}
<Configuration status="INFO">
<Properties>
   <Property name="basePath" value="./logs" />
</Properties>
<Appenders>
  <Console name="console" target="SYSTEM_OUT">
    <PatternLayout>
     <Pattern>
     [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
     </Pattern>
    </PatternLayout>
  </Console>
  <File name="fileLogger" fileName="${basePath}/error.log">
    <PatternLayout>
    <Pattern>
     [%-5level] %d{yyyy-MM-dd HH:mm:ss} [%t] %c{1} - %msg%n
    </Pattern>
    </PatternLayout>
  </File>
</Appenders>
<Loggers>
   <Root name="parallel">
     <AppenderRef ref="console" level="trace" />
   </Root>
   <Logger name="parallel" level="warn" additivity="false">
      <AppenderRef ref="fileLogger" />
   </Logger>
</Loggers>

A: As I understand it, your goal is to accomplish these items:

I intend to write ERROR and FATAL to file hence using level=ERROR.  I
  intend to write all logs to console hence using level=TRACE for
  Console.

Please read the entire answer before making a final choice regarding what you will implement in your code.
You could do this by configuring your loggers as follows:
<Loggers>
    <Root>
        <AppenderRef ref="console"/>
    </Root>
    <Logger name="parallel" level="ALL" additivity="true">
        <AppenderRef ref="fileLogger" level="ERROR"/>
    </Logger>
</Loggers>

Log events will be accepted by each logger based on logger name and the level of the event. If you call log.error(...) for example an ERROR level event is generated. If log was obtained through LogManager.getLogger(ClassA.class) then log4j will search its configuration for a logger called "parallel.ClassA". If it does not find such a logger it will go up the hierarchy to a less specific logger - "parallel". If this logger does not exist it will go to the root logger.
Once the logger is identified log4j must determine if the event is accecpted by that logger. This is based on the level setting for the logger. Since the "parallel" logger is set to a level of ALL it will accept events of any level.
After the logger accepts an event, its appenders must also accept the event. The level associated with file appender of the "parallel" logger is ERROR so this appender will only accept events that are ERROR and FATAL level.
Since additivity is true for "parallel" logger whenever it accepts an event it will pass that event to the appenders of all of its parent loggers as well (unless one of them breaks the chain by specifying additivity false - see log4j2 architecture page for details). So any events accepted by "parallel" will go to the console appender associated with root logger.
There is a problem with this approach in that if a log event reached the root logger with a level of ERROR or FATAL it would not be written to your log file. The logs would "leak" to the console. This can happen if you accidentally write some bad code or if you accidentally forget to update your configuration file after adding some new code.
Here's some sample code to illustrate the problem:
package parallel;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ClassA {
    private static final Logger log = LogManager.getLogger(ClassA.class);

    public static void main(String[] args) {
        log.info("info");
        log.debug("debug");
        log.warn("warn");
        log.error("error");
        log.fatal("fatal");
        log.trace("trace");

        // See the mistake here?
        // The wrong logger name was used in the code,
        // now the error event goes to the root logger!
        final Logger log2 = LogManager.getLogger("foo");
        log2.error("Woops an error!");
    }
}

The console output for the above using the configuration from the beginning of the answer is:
[INFO ] 2019-05-05 12:48:31.410 [main] ClassA - info
[DEBUG] 2019-05-05 12:48:31.411 [main] ClassA - debug
[WARN ] 2019-05-05 12:48:31.411 [main] ClassA - warn
[ERROR] 2019-05-05 12:48:31.411 [main] ClassA - error
[FATAL] 2019-05-05 12:48:31.412 [main] ClassA - fatal
[TRACE] 2019-05-05 12:48:31.412 [main] ClassA - trace
[ERROR] 2019-05-05 12:48:31.413 [main] foo - Woops an error!

The error log file only shows:
[ERROR] 2019-05-05 12:48:31 [main] ClassA - error
[FATAL] 2019-05-05 12:48:31 [main] ClassA - fatal

The simplest fix is to just move all of your appenders to the root logger as shown below:
<Loggers>
    <Root level="ALL">
        <AppenderRef ref="console"/>
        <AppenderRef ref="fileLogger" level="ERROR"/>
    </Root>
</Loggers>

Now all events are accepted by root logger and console appender but only ERROR and FATAL events are accepted by the file appender. Now even with incorrect code the log events will go to the right place.
Console ouput:
[INFO ] 2019-05-05 12:59:32.419 [main] ClassA - info
[DEBUG] 2019-05-05 12:59:32.421 [main] ClassA - debug
[WARN ] 2019-05-05 12:59:32.421 [main] ClassA - warn
[ERROR] 2019-05-05 12:59:32.421 [main] ClassA - error
[FATAL] 2019-05-05 12:59:32.421 [main] ClassA - fatal
[TRACE] 2019-05-05 12:59:32.421 [main] ClassA - trace
[ERROR] 2019-05-05 12:59:32.422 [main] foo - Woops an error!

Error log file:
[ERROR] 2019-05-05 12:59:32 [main] ClassA - error
[FATAL] 2019-05-05 12:59:32 [main] ClassA - fatal
[ERROR] 2019-05-05 12:59:32 [main] foo - Woops an error!

Other Possibly Helpful Links:
https://stackoverflow.com/a/51567436/3284624
I hope this helps you!

A: Partially solved.....
I added Additivity="true" in the Logger tag and this made the logs print in both Console and File. However the log level of ERROR was being applied to both Console and File. My actual requirement is Console to have TRACE and File to have ERROR level.
I am not able to understand the concept of Additivity from log4j2 official doc. Anyone who could explain this concept would be of great help.


text:
Q: How can I align ,, text, input fields, a real button, and a " link button" properly and with the same font? MY PROBLEM (brief):
I would like the text Username, the text you type for the Username, the Real Button Text the "or" and the Link Button Text to be exactly the same size and on the same "line" - they don't line up smoothly...
HAVE I TRIED FIXING THIS MYSELF?  OTHER PROBLEMS WITH ZOOMING
I've spent considerable time trying to get this aligned as close to perfect as I can get however, with my knowledge I can never get it lined up to satisfaction.  I gave up for many months while I worked on other parts of the website but it's a thorn in my mind that it SHOULD be possible.  I also had problems when I used scaling - in some zooms it looked so close to perfect I figured "That's as good as I can get it!".
I cut this out of my website to make the code as small as possible.  If you look at the result - the Username (the username you type), the "Real Button" and the "or" and the "Link Button" are all different heights... it doesn't seem to flow nicely.
Also, if you put the 2 buttons on top of each other the word SIGN is different widths.  If I'm using the same font, same size, same everything, why would 1 be wider than the other?  Different letter spacing?
While I did give up on this, recently I saw another fiddle from Stack that kinda solved the problem but without labels and without lining everything up.  THIS code is based on that code.  I figure, if this can be fixed, I'll re-work it into my website with all the responsive design etc...
PREVIOUS PARTIAL SOLUTIONS:
In the past I used tables and things seemed to line up better but I was trying not to use tables for this as you shouldn't have to create a table for such a short simple line of HTML.
JSFIDDLE:
I created a JSFiddle so you can see.
http://jsfiddle.net/PerryCS/7zc2vjmx/2/
HTML CODE:
    <form id="loginForm1" name="loginForm1?callingPage=validateForm" method="post" action="index.php" accept-charset="utf-8">

In order to access some areas of the website, save estimates.

    Username
    <input type="text" id="username" name="username">

    Password
    <input type="password" id="pword" name="pword">

    <input class="button" type="button" name="buttonSignIn" value="SIGN IN"> or
    SIGN UP

</form>

CSS CODE
body {
  font-size: 1em;
  font-family: Verdana, Arial, Helvetica, sans-serif;
}

input.button {
  height: 28px;
  font-size: 1em;
  color: white;
  font-weight: normal;
  font-style: normal;
  background: #4D28B2;
  border: 1px solid gray;
  vertical-align: middle;
  padding: 0px 5px;
}

a.button {
  display: inline-block;
  height: 28px;
  font-size: 1em;
  color: white;
  text-decoration: none;
  font-weight: normal;
  font-style: normal;
  text-align: left;
  background-color: #4D28B2;
  border: 1px solid gray;
  vertical-align: middle;
  line-height: 28px;
  padding: 0px 5px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
}

input {
  height: 28px;
  font-size: 1em;
  text-decoration: none;
  font-weight: normal;
  font-style: normal;
  text-align: left;
  background-color: #4D28B2;
  border: 1px solid gray;
  vertical-align: middle;
  line-height: 28px;
  padding: 0px 5px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
}

.mydiv {
  display: inline-block;
}

MY THANKS FOR YOUR TIME
I thank you in advance for your time in helping me grow these past few years.  You guys/gals have helped me solve some problems and your help is much appreciated.  :)

A: create a CSS rule for all these elements with identical settings and also add vertical-align: baseline. This should line up all text at the same baseline, and if the font-family, font-size, font-weight, font-variation etc. are the same, it should look as you want it.
For my fork of your fiddle I just added this (affecting all elements inside .mydiv):
.mydiv * {
  display: inline-block;
  vertical-align: baseline;
  font-family: Arial sans-serif !important;
  font-size: 1em !important;
}

Here's the link to the fiddle: http://jsfiddle.net/f03jvuqb/

A: After fiddling with this and not being 100% happy with it... I looked into Flex Box which is quite popular now-a-days in most browsers.  Using Flex Box worked like a charm and the code was way cleaner.  Everything lined up beautifully and I was quite pleased with the results.  I learned a lot during all this tinkering.   I'll post the Flex Box code another day when I have more time.


text: Q: Google Merchant Center transfer in Bigquery doesn't return data for yesterday but 2 days ago I schedule the transfer to run at around 4 am every day and it usually returns data with product_data_timestamp for the day before. However, today it only returns data with  product_data_timestamp for 2 days ago. I've tried to run the transfer again at 11 am and create a new transfer at 2 pm but it still doesn't return product_data_timestamp for yesterday but 2 days ago. I have never seen this happen before. Do you have any idea why and how to solve this? Thanks in advance.


text:
Q: Android: opening and closing SQLite database I'm developing and android application in which I often use access the local database. This database can be accessed from differents therads, so I have a coordination problem for the database. I use the following open() and close() method.
public void open(){
    mDb=mDbHelper.getWritableDatabase();
}

public void close(){
        mDb.close();
}

So, usually, when I need to access the db for some operations I open the database, then I perform some operation, and finally I close the database. The code I typically use for this purpose is the following:
    try {
        dbManager.open();
                    // database operation
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        try {
            dbManager.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

But, if for this piece of code is used from differnts threads (supposing thread A and thread B) the following situation may occurs:
A thread: performs open()
B thread: perfroms open()
A thread: perfroms some operation
A thread: performs close()
B thread: try to perform some operation but it fails!

So, the only solution I can guess I to perform open() when my application starts and close() when my application is stopped. I'm not sure that this can be this a good solution?
In effect, the documentation of getWritableDatabase() method (called from my open()) says:
Make sure to call close() when you no longer need the database

So, anyone can suggest me an alternative solution?

A: You can use the singletone instance and gennerally you can do not close database (but keep transaction closed). There is some information:
Android SQLite DB When to Close

A: Create a wrapper class, add an atomic integer member and every time you open the database, increment the member, when you close it, decrement the member and if the member is zero, actually close the db.


text:
Q: Get HTML element CSS Rules server side I want to load a URL like this (for ex. bootstarp) and than point to some element- let's say by a selector ".bs-docs-featurette" and get all it's CSS rules like displayed in FireFox (element inspector F12 >  Rules).
element {
}
@media....
.bs-docs-featurette {
    padding-top: 100px;
    padding-bottom: 100px;
}
.bs-docs-featurette {
    padding-top: 40px;
    padding-bottom: 40px;
    font-size: 16px;
    line-height: 1.5;
    color: rgb(85, 85, 85);
    text-align: center;
    background-color: rgb(255, 255, 255);
    border-bottom: 1px solid rgb(229, 229, 229);
}

All in a logical (priority) order, etc.
ComputedStyle is not a option for for me, becouse I lose @media properties, etc.
I have looked into Python's WebDriver (Selenium) and "lxml.cssselect", but non of them gives me a simple solution to my goal.
I prefer stick to Python, but if it's easier in other programming languages, it's OK to shift.
Any good ideas will be appreciated.


text:
Q: jQuery parsing of server JSON (String) I've been at this for a while and can't seem to nail it down, your help is much appreciated.
Challenge:
Unable to identify how to properly use JQUERY to parse the following JSON (String?) response from the server:
{"d":"{\"NewDataSet\":{\"Table\":{\"EMPLOYEE_NO\":\"3605\",\"NAME\":\"Last, First\",\"STAFF\":\"CSR\",\"USERNAME\":\"lis\",\"PIN\":\"somepassword\"}}}"}

Tried:
Many things, such as...
var dtObj = jQuery.parseJSON(data);
$.each(dtObj, function (i, val) {
.. do some stuff
});

Requirement:
Need to get the EMPLOYEE_NO, NAME, STAFF, USERNAME, AND PING values.
Thanks!

A: Your JSON id nested, so you'll have to parse twice and the object that holds the data you want is some levels deep.
var Obj1 = jQuery.parseJSON(data);
var Obj2 = jQuery.parseJSON(Obj1.d);
var dtObj = Obj2.NewDataSet.Table;
// now you can use dtObj to access EMPLOYEE_NO, NAME, STAFF, USERNAME, AND PING properties.

jsFiddle

A: First make sure, your json is valid. Use this tool http://jsonlint.com/
var data={
    "d": {
        "NewDataSet": {
            "Table": {
                "EMPLOYEE_NO": "3605",
                "NAME": "Last,First",
                "STAFF": "CSR",
                "USERNAME": "lis",
                "PIN": "somepassword"
            }
        }
    }
};
alert(data.d.NewDataSet.Table.NAME);

http://jsfiddle.net/tariqulazam/rBfLw/


text:
Q: Count results generated by case statement I'm working on a query that analyzes two records and checks whether one record matches the second record. If record 1 column matches record 2 column then there's no error. If record 1 column does not match record 2 column then there's an error. I want to be able to count the errors per YPID. For the life of me... I can't figure it out. Help!
Here's my query:
select r1.ypid, r1.business_name as Base_Listed_Name, r1.street_address as Base_Listed_Address, r1.city as Base_Listed_City, r1.state as Base_Listed_State, r1.zip5 as Base_Listed_Zip, rmve1.value as Base_URL,
r2.business_name as Google_Scanned_Listed_Name, r2.street_address as Google_Scanned_Listed_Address, r2.city as Google_Scanned_Listed_City, r2.state as Google_Scanned_Listed_City, r2.zip5 as Google_Scanned_Listed_Zip, rmve2.value as Google_Scanned_URL,
ls.presence_score, ls.listing_score,
case
when r1.business_name = r2.business_name then 'no_error'
else 'error'
end Business_Name_Status,
case
when r1.latitude = r2.latitude then  'no_error'
when r1.longitude = r2.longitude then  'no_error'
when r1.latitude is null or r1.latitude in ('0') then (case when r1.street_address = r2.street_address then 'no_error' else 'error' end)
else 'error'
end Street_Address_Status,
case
when r1.city = r2.city then 'no_error'
else 'error'
end City_Status,
case
when r1.state = r2.state then 'no_error'
else 'error'
end State_Status,
case
when r1.zip5 = r2.zip5 then 'no_error'
else 'error'
end Zip_Status,
case
when lower(replace(replace(replace(replace(replace(replace(rmve1.value, 'http://www.', null), 'www.', null), 'https://www.', null), 'http://', null), 'https://', null), 'wwww.', null))
= lower(replace(replace(replace(replace(replace(replace(rmve2.value, 'http://www.', null), 'www.', null), 'https://www.', null), 'http://', null), 'https://', null), 'wwww.', null)) then 'no_error'
else 'error'
end URL_Status
from mdm2.records r1 join mdm2.records r2 on r1.ypid = r2.ypid join mdm2.presence_listing_statuses ls on r1.ypid = ls.ypid
left outer join mdm2.record_mult_val_exts rmve1 on r1.id = rmve1.record_id and rmve1.extension_type = 'urls' and rmve1.value_type = 'primary'
left outer join mdm2.record_mult_val_exts rmve2 on r2.id = rmve2.record_id and rmve2.extension_type = 'urls' and rmve2.value_type = 'primary'
where r1.ypid in ('5625222','13846403','21974776','22806234','30303664','453728041')
and r1.source_code = 'PPA'
and r2.source_code = 'GOOG';

results
|YPID|BASE_LISTED_NAME|BASE_LISTED_ADDRESS|BASE_LISTED_CITY|BASE_LISTED_STATE|BASE_LISTED_ZIP|BASE_URL|GOOGLE_SCANNED_LISTED_NAME|GOOGLE_SCANNED_LISTED_ADDRESS|GOOGLE_SCANNED_LISTED_CITY|GOOGLE_SCANNED_LISTED_CITY_1|GOOGLE_SCANNED_LISTED_ZIP|GOOGLE_SCANNED_URL|PRESENCE_SCORE|LISTING_SCORE|BUSINESS_NAME_STATUS|STREET_ADDRESS_STATUS|CITY_STATUS|STATE_STATUS|ZIP_STATUS|URL_STATUS|
|5625222|Affinity Insurance Agency|5702 S Staples St Suite G|Corpus Christi|TX|78413|http://affinityia.com|Affinity Insurance Agency|5702 S Staples St Suite G|Corpus Christi|TX|78413|http://corpuschristiinsuranceprovider.com|90|97|no_error|no_error|no_error|no_error|no_error|error|
|13846403|Party Bazaar|4435 Lovers Ln|Dallas|TX|75225|www.partybazaardallas.com|Party Bazaar|4435 Lovers Ln|Dallas|TX|75225|http://partybazaardallas.com|93|100|no_error|no_error|no_error|no_error|no_error|no_error|
|21974776|Alterations To Go|2100 Arden Way Ste 150|Sacramento|CA|95825|http://www.alterationstogosacramento.com|Alterations To Go|2100 Arden Way # 150|Sacramento|CA|95825|http://alterations-togo.com|91|99|no_error|no_error|no_error|no_error|no_error|error|
|22806234|RV America|3640 Chambers Rd|Aurora|CO|80011|http://www.rvamericainc.com/pages/rv%20financing|RV America|3640 Chambers Rd|Aurora|CO|80011|http://rvamericainc.com|83|91|no_error|no_error|no_error|no_error|no_error|error|
|30303664|Sorelli Hair Studio & Spa|400 Saint Andrews Blvd|Melbourne|FL|32940|http://sorellihairstudio.com|Sorelli Hair Studio & Spa|400 Saint Andrews Blvd|Melbourne|FL|32940|http://sorellihairstudio.com|91|99|no_error|no_error|no_error|no_error|no_error|no_error|
|453728041|Carolina Driving School|534 Walkertown Guthrie Rd|Winston Salem|NC|27101|http://www.carolinadriving.com|Carolina Driving School|534 Walkertown Guthrie Rd|Winston Salem|NC|27101|http://carolinadrivingschool.com|87|97|no_error|no_error|no_error|no_error|no_error|error|

A: i guess you need to use LEAD , LAG function .
check this link http://oracle-base.com/articles/misc/lag-lead-analytic-functions.php
LAG function is used to access data from a previous row
LEAD function is used to return data from the next row.
by this you can compare 1st row with 2nd row


text:
Q: Catch proxy errors on requests python I'm new on python so I'm having some trouble. I'm trying to build a tool that posts data to an external server with proxy. I have it working, but the problem is I don't know how to catch the proxy connection error and print something else. The code I wrote is:
import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11",
    "Content-Type": "application/json"
}
proxies = {
    "https": "https://244.324.324.32:8081",
}
data = {"test": "test"}
r = requests.post("https://example.com/page", proxies=proxies, json=data, headers=headers)
print(r.text)

How can I print, for example "Proxy Connection Error", when the proxy is dead (not connecting/working) or something like this. This is my first time using python so I'm having trouble.
Thank You

A: The accepted answer didn't work for me.
I had to use requests.exceptions.ProxyError, i.e.:
try:
    req = requests.post(...)
except requests.exceptions.ProxyError as err:
    print("Proxy Error", err)

A: İf you dont know the exception error, You can do run this first
try:
    req = requests.post(...)
except requests.exceptions.ProxyError as err:
    print(sys.exc_info()[0])

This gives you the error name, and then you can add your code this err.
(Sometimes you need to import the exception error.)

A: You can use a try/except block to catch a connection error:
try:
  r = requests.post("https://example.com/page", proxies=proxies, json=data, headers=headers)
except requests.exceptions.ConnectionError:
  print "Proxy Connection Error"
print(r.text)

In the code above, if requests.post raises a ConnectionError, the except block will catch it and print out the Proxy Connection Error message.


text:
Q: new table and association has been added as icollection not ienuremable, how can i iterate through results? ive added a new table to my entity and created an association. my new code is as below.
as you can see all previously added tables just go in with a get/set this table has got in as an icollection and in my razor view i cannot do the following anymore. how can i get the results into this view?
Thanks
Razor that no longer works
    @Html.DisplayFor(modelItem => item.NetInfo.Username)
Error
 'System.Collections.Generic.ICollection<ITAPP.Models.tblNetworkInfo>' does not contain a definition for 'Username' and no extension method 'Username' accepting a first argument of type 'System.Collections.Generic.ICollection<ITAPP.Models.tblNetworkInfo>' could be found (are you missing a using directive or an assembly reference?)

Class
    public partial class tblEquipment
    {
        public tblEquipment()
        {
            this.NetInfo = new HashSet();
        }
    public int ID { get; set; }
    public Nullable<int> UserID { get; set; }
    public Nullable<int> PreviousUserID { get; set; }
    public Nullable<int> ChangeID { get; set; }
    public Nullable<int> RequestedBy { get; set; }
    public string MachineName { get; set; }
    public bool Stock { get; set; }
    public string Vendor { get; set; }
    public string Model { get; set; }
    public string Supplier { get; set; }

    public virtual tblUser User { get; set; }
    public virtual tblChangeLog ChangeLog { get; set; }
    public virtual tblAssetType AssetType { get; set; }
    public virtual ICollection<tblNetworkInfo> NetInfo { get; set; }

A: Since NetInfo is a collection you have to loop through it:
This is one option:
@foreach(var netInfo in Model.NetInfo)
{
    @Html.DisplayFor(m => netInfo.Username)
}

Another option is:
@Html.DisplayFor(m => m.NetInfo)

Then if you create a Display Template for the tblNetworkInfo model you can display whatever you need in it:
tblNetworkInfo.cshtml
----
@model tblNetworkInfo

@Html.DisplayFor(m => m.Username)

DisplayFor is smart enough to work on collections and output a display template for each item in the collection.


text:
Q: Is there a way to download a csv file of the data from a SQL Server database table on button click in Angular I need to get all of the data in my SQL Server database table into a .csv file when I click a button in a front end Angular web page.
I have already written a Web API in C# to access all the data from the SQL Server table and display it in my web page. I need to be able to download a .csv file when I click a button with all that data in the table displayed on my page.
export class EmployeeService {

  url = 'https://localhost:44395/Api/Employee';
  constructor(private http: HttpClient) { }

  getAllEmployee(): Observable<Employee[]> {
    return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');
  }
}

Save

A: Since you  have to display the data in your angular application the best solution is to send the data as json and the use the following npm package : https://www.npmjs.com/package/xlsx to convert the json to xlsx file or csv
Here is a sample service i have written for the same, just create this service and call the function where you need it :
excel.service.ts
import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';

@Injectable({
  providedIn: 'root'
})

export class ExcelService {

  constructor() { }

  jsonToExcelSheet(data: any[], file_name = 'temp.xlsx') {

    const workBook = XLSX.utils.book_new(); // create a new blank book
    const workSheet = XLSX.utils.json_to_sheet(data);
    let wscols = [{ wpx: 150 }, { wpx: 200 }, { wpx: 150 }, { wpx: 150 }];
    workSheet['!cols'] = wscols; // set cell width
    XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
    return XLSX.writeFile(workBook, file_name); // initiate a file download in browser

  }

  jsonToCSV(data: any[], file_name = 'temp') {

    const workBook = XLSX.utils.book_new(); // create a new blank book
    const workSheet = XLSX.utils.json_to_sheet(data);

    XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
    return XLSX.writeFile(workBook, `${file_name}.csv`); // initiate a file download in browser

  }

}

Now if you want to use this service just import it in the desired component.ts
import { ExcelService } from 'src/services/excel.service';

constructor(private _excelService: ExcelService){}

async downloadWorksheet() {

   let downloadData = {} // load your data here

   // export the json as excelsheet
   await this._excelService.jsonToExcelSheet(downloadData);
}

A: You can use the package, file-saver for downloading files from blob. Load the data and generate a CSV string which can be converted into a blob object.

npm i file-saver
npm i @types/file-saver

app.component.ts :
import { saveAs } from 'file-saver'

download(){
    // Variable to store data as CSV string
    let csvStr = '';
    // Fetch data from service
    this.employeeService.getAllEmployee().subscribe(
        response => {
            // Manipulate data to generate CSV string
        },error => {}
    );

    // Convert string to blob
    var csvBlob = new Blob([csvStr], {
      type: 'text/plain'
    });
    // Download
    saveAs(csvBlob,'data.csv')
}

Demo : https://stackblitz.com/edit/angular-zhqbgp


text:
Q: Where should PHP write sessions to? Just installed PHP 5.4 on Centos 6.4 with Apache 2.2 VPS, and received an error that permission is denied to open session.  php.ini shows session.save_path = "/var/lib/php/session".  Do I make /var/lib/php/session permission 0777?  Or maybe make Apache run as a given user, and then give that user rights to /var/lib/php/session.  I recall in the past changing session path to /tmp, and wonder if that is a better strategy.  Where should I set PHP to write sessions to?

A: In terms of flexibility and - even more importantly - security, you should configure the Apache to run the scripts (read: php-processes) as another, unprivileged user per vhost using suEXEC + FCGId or something similar. Then you can assign a own php.ini for every user and set the session path to a user-only writable path (for example in the users /home directory). There're plenty of tutorials for this common setup, just search for "centos apache suexec php"
This might be the most complex solution to your problem, but it also takes security and some flexibility for the future into account.

A: Make Apache run as user/group apache/apache.  CentOS will automatically have permissions set correctly for /var/lib/php/session.

A: If you have mod_fcgid then the apache user won't be usable as a /var/lib/php/session user/group owner.

A: Sessions should be stored with Memcached.
session.save_handler = memcached
session.save_path = "localhost:11211"


text:
Q: How to find levels in a hierarchy by dates using SQLite Problem
How to find a level for every individual in a hierarchy, by dates, using SQLite with recursive expression.
Details
I have found the following post detailing the use of recursive queries for doing computation on hierarchical data in SQLite and that one on StackOverflow for basic recursive queries on SQLite3.
Now, there is a good detailed example on the documentation of SQLite about how to approach computation for hierarchical data from a single employee perspective (example at part 3.2).
What have I managed to do?
Well, so far I know how to compute the levels for a selected individual (woohoo), but I can't bridge the gap and make this query apply to all the individuals by dates.
Here is my partial query that does the job for 1 individual:
WITH RECURSIVE supervisor_of(id, boss_id, date_interest) AS (
        SELECT org_1.id, org_1.boss_id, org_1.date_interest
        FROM org org_1
        WHERE id = 4 -- Here is the input for the individual
    UNION
        SELECT org_1.id, org_1.boss_id, org_1.date_interest
        FROM org org_1
        JOIN supervisor_of so
            ON so.boss_id = org_1.id
            AND so.date_interest = org_1.date_interest
)
SELECT *,
    COUNT(id) AS level
FROM supervisor_of
GROUP BY date_interest
ORDER BY date_interest

And the output:
| id   | boss_id | date_interest | level |
| ---- | ------- | ------------- | ----- |
| 4    | 2       | 2             | 3     |
| 4    | 2       | 3             | 3     |

But I can't manage to wrap around my head to get this result:
| id   | boss_id | date_interest | level |
| ---- | ------- | ------------- | ----- |
| 1    |         | 1             | 1     |
| 2    | 1       | 1             | 2     |
| 3    | 1       | 1             | 2     |
| 1    |         | 2             | 1     |
| 2    | 1       | 2             | 2     |
| 3    | 1       | 2             | 2     |
| 4    | 2       | 2             | 3     |
| 1    |         | 3             | 1     |
| 2    | 1       | 3             | 2     |
| 3    | 1       | 3             | 2     |
| 4    | 2       | 3             | 3     |
| 5    | 4       | 3             | 4     |

Here is how to load the data for making this test:
CREATE TABLE org(
  id TEXT,
  boss_id TEXT,
  date_interest TEXT
);
-- 1st Date
INSERT INTO org (id, boss_id, date_interest) VALUES(1, NULL, 1);
INSERT INTO org (id, boss_id, date_interest) VALUES(2, 1, 1);
INSERT INTO org (id, boss_id, date_interest) VALUES(3, 1, 1);
-- 2nd Date
INSERT INTO org (id, boss_id, date_interest) VALUES(1, NULL, 2);
INSERT INTO org (id, boss_id, date_interest) VALUES(2, 1, 2);
INSERT INTO org (id, boss_id, date_interest) VALUES(3, 1, 2);
INSERT INTO org (id, boss_id, date_interest) VALUES(4, 2, 2);
-- 3rd Date
INSERT INTO org (id, boss_id, date_interest) VALUES(1, NULL, 3);
INSERT INTO org (id, boss_id, date_interest) VALUES(2, 1, 3);
INSERT INTO org (id, boss_id, date_interest) VALUES(3, 1, 3);
INSERT INTO org (id, boss_id, date_interest) VALUES(4, 2, 3);
INSERT INTO org (id, boss_id, date_interest) VALUES(5, 4, 3);

A: Remove the WHERE clause from your code so that you query for all ids and in the 2nd part of the recursive CTE select supervisor_of.id and not org_1.id.
Finally you must group by id also:
WITH RECURSIVE supervisor_of(id, boss_id, date_interest) AS (
  SELECT org_1.id, org_1.boss_id, org_1.date_interest
  FROM org org_1
  UNION
  SELECT so.id, org_1.boss_id, org_1.date_interest
  FROM org org_1 JOIN supervisor_of so
  ON so.boss_id = org_1.id AND so.date_interest = org_1.date_interest
)
SELECT *, COUNT(*) AS level
FROM supervisor_of
GROUP BY date_interest, id
ORDER BY date_interest, id

See the demo.
Results:

id
boss_id
date_interest
level

1
null
1
1

2
1
1
2

3
1
1
2

1
null
2
1

2
1
2
2

3
1
2
2

4
2
2
3

1
null
3
1

2
1
3
2

3
1
3
2

4
2
3
3

5
4
3
4


text:
Q: ValueError: 'DateFormatter found a value of x=0, which is an illegal date' I have lists of time in seconds. e.g.:
[0, 15, 30, .... 18615, 18630, 18645]

and I want to plot it as hour:min:sec against an equally long list of values.
I have tried using date formatter but I get the following error:
ValueError: DateFormatter found a value of x=0, which is an illegal date.  This usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()

I have already implemented the ax.xaxis_date() so that shouldn't be the problem. Hope you can help me get the x-axis to show time in hours instead of seconds.
The relevant code:
self.samp_freq = 15
self.noise_samp = np.arange(0, self.time_total, self.samp_freq)
self.random_noise = np.random.normal(0, 10, len(self.noise_samp))

self.noi_ax.xaxis.set_major_locator(mticker.MaxNLocator(5))
self.noi_ax.xaxis_date()
self.noi_ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))

self.noi_ax.plot(self.noise_samp, self.scaled_random_noise)[0]
self.noi_ax.set_xlabel('time (sec)')
self.noi_ax.set_ylabel('noise (uGal')


text:
Q: jPlayer mp3 not loading After further investigation, I've realized it's to do with the flash plugin not working, but again only in XP. You can see the code here: http://tarsusempire.co.uk/test/test.html
It works fine in OSX, but not XP. Both browsers are same version and so is flash. I've tried it in FF, Chrome and Safari on OSX, but not at all on XP.

A: It turned out to be my flash plugin had upgraded itself and then needed for a simple computer reboot. So yes, turning it off and on again resolved this :)


text:
Q: TabItem templates I have a tab control defined as this:
<TabControl Grid.Row="1" ItemsSource="{Binding Path=Documents}">
      <TabControl.ItemTemplate>
          <DataTemplate>
              <TabItem>
                  <Button Content="Test button"/>
              </TabItem>
          </DataTemplate>
      </TabControl.ItemTemplate>
</TabControl>

I know that the Documents collection in the ViewModel is updated properly since I can see an empty tab header when I run my application, thus tab items are being created by the control. But for some reason there is no button in the tab item. Any ideas why this is happening?

A: Remove TabItem from your DataTemplate as at the moment you put TabItem within TabItem.
<TabControl Grid.Row="1" ItemsSource="{Binding Path=Documents}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <Button Content="Test button"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

also if you want to your Button to appear in Content part and not in the Header then instead of ItemTemplate use ContentTemplate


text:
Q: Creating instance of model in controller returns nil for id and timestamp Rails 6 I'm currently trying to create a photo in the controller. However, the instance is not being saved. I'm passing the correct parameters but not sure why is not being saved.
 18: def create
    19:   @photo = Photo.new(photo_params)
 => 20:   binding.pry
    21:   if @photo.save
    22:     redirect_to @photo
    23:   else
    24:     render "new"
    25:   end
    26: end

[1] pry(#<PhotosController>)> Photo.new(photo_params)
=> #<Photo:0x00007fefafb9b058 id: nil, user_id: nil, location: "New York", description: "something somethings", created_at: nil, updated_at: nil>

As you can see above the parameters are being passed but not the id and the user_id is nil as well, is it because of the association that is not being built?
class PhotosController < ApplicationController
  def index
    @photos = Photo.all
  end

  def show
    @photo = Photo.find(params[:id])
  end

  def new
    @photo = Photo.new
  end

  def edit
    @photo = Photo.find(params[:id])
  end

  def create
    @photo = Photo.new(photo_params)
    if @photo.save
      redirect_to @photo
    else
      render "new"
    end
  end

  def update
    @photo = Photo.find(params[:id])
    respond_to do |format|
      if @photo.update(photo_params)
        format
          .html { redirect_to @photo, notice: 'Post was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  private

  def photo_params
    params.require(:photo).permit(
      :location,
      :description,
      :image,
    )
  end
end

Here is the controller for Photos. Here I have new and create. In create I'm passing the params to create the photo. I wonder if I should pass this from the current user due to the following association.
class Photo < ApplicationRecord
  has_one_attached :image
  belongs_to :user
end

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :photos
  has_one :profile
  accepts_nested_attributes_for :profile
end

Here I have that the following models. A user has many photos and a photo belongs to the user.
class CreatePhotos < ActiveRecord::Migration[5.2]
  def change
    create_table :photos do |t|
      t.references :user, foreign_key: true
      t.string :location
      t.string :description

      t.timestamps
    end
  end
end

As far as the migration for photos goes. I don't think I have to add :image to the table since ActiveStorage takes care of that by the has_one_attached method. Not sure what the issue is?

A: Your photo_params contains only three values:
    params.require(:photo).permit(
      :location,
      :description,
      :image,
    )

Those are the only values you're passing to Photo.new, so those are the only fields that are being populated. It's unclear why you would expect the user_id to be set, but the id and created_at fields are populated automatically when you save the record. Put your binding.pry after your save call.

A: In the default options of
belongs_to :user

require the user_id to be set in current versions of Rails. Because you do not assign a user to the new photo the photo cannot be saved.
To assign the current user to a new photo just change this line
@photo = Photo.new(photo_params)

in your create method in the controller to
@photo = current_user.photos.build(photo_params)

I advise reading the docs about the has_many association in the Rails Guides.


text:
Q: Gerar email aleatorios Estou fazendo um exercício que estou quebrando cabeça, tenho que criar email aleatórios a partir de  array de objetos com dados de clientes fictícios, usando uma parte do nome e do cpf e não estou conseguindo, alguém poderia me explica uma forma de fazer.
let clientes = [
    { nome: 'Kelvin Silva Sena', cpf: '10286741474', email: 'user@email.com.br', senha: 'passw:Abcd1234' },
    { nome: 'Amyson Jhonata Da Silva', cpf: '10287054411', email: 'user@email.com.br', senha: 'passw:Abcd1234' },
    { nome: 'Matheus Correa Da Silva', cpf: '10287259498', email: 'user@email.com.br', senha: 'passw:Abcd1234' },
    { nome: 'Janekely Batista Dos Santos', cpf: '10288003470', email: 'user@email.com.br', senha: 'passw:Abcd1234' },
    { nome: 'Luan Marcondes Alves De Souza', cpf: '10288469402', email: 'user@email.com.br', senha: 'passw:Abcd1234' },
    { nome: 'Neidi Lucia Ignacio', cpf: '35331701949 ', email: 'user@email.com.br', senha: 'passw:Abcd1234' },
    { nome: 'Neidi Lucia Ignacio ', cpf: '35331701949', email: 'user@email.com.br', senha: 'passw:Abcd1234' },
    { nome: 'Neidi Lucia Ignacio', cpf: '35331701949', email: 'user@email.com.br', senha: 'passw:Abcd1234' },
]

//preciso criar uma função

function gerarEmail() {
    let dominios= ['@gmail.com', '@outlook.com', '@bol.com.br']
    //funcao para gerar email aleatorio com partes do nome + cpf
    //examplo linha 1: marl_102813arauj@outloo.com

}

A: seguindo pelo seu array de clientes...
function gerarEmail() {
    let dominios= ['@gmail.com', '@outlook.com', '@bol.com.br']
    for(var i=0;i<clientes.length;i++){
        let label   = clientes[i].nome.split(' ');
        let email   = label[0]+clientes[i].cpf+dominios[Math.floor(Math.random() *
       dominios.length)];
        document.write(email+"<br/>");
    }
 }

 gerarEmail();

Montei um loop FOR para iterar sobre cada cliente de sua listagem, em seguida usei o split do javascript quebrando a string de nome de cada cliente entre espaços, gerando um array que aqui foi nomeado como label. Concatenei a primeira posição desse array, que compreende como o primeiro nome de cada cliente com o cpf inteiro. Em seguida apenas gerei um número randômico que comprende de zero até o total de itens de seu array domínios, concatenando na variavel string email. Por último eu mandei imprimir quebrando uma linha.


text:
Q: PostgreSQL function returns one column instead of 4 columns I have a PostgreSQL function that returns one column instead of 4 columns like it should. Moreover, all four data points are nested within one column and the updates were not performed. Can you please review my code and offer suggestions?

code:
-- FUNCTION: public.update_funcnull()

-- DROP FUNCTION IF EXISTS public.update_funcnull();

CREATE OR REPLACE FUNCTION public.update_funcnull(
    )
    RETURNS TABLE(ride_id text, duration interval, lat_change real, long_change real)
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN
    UPDATE bikeshare3 SET duration = NULL;
    UPDATE bikeshare3 SET lat_change = NULL;
    UPDATE bikeshare3 SET long_change = NULL;
    RETURN QUERY SELECT ride_id, duration, lat_change, long_change FROM bikeshare3 LIMIT 5;
END;
$BODY$;

ALTER FUNCTION public.update_funcnull()
    OWNER TO postgres;

A: You should to call function with "tabular context":
SELECT * FROM public.update_funcnull();

Tabular functions (or Set Returning functions in PostgreSQL terminology) returns composite values in "scalar context".
CREATE OR REPLACE FUNCTION public.foo()
 RETURNS TABLE(a integer, b integer)
 LANGUAGE plpgsql
AS $function$
BEGIN
  a := 1; b := 2;
  RETURN NEXT;
  RETURN NEXT;
END;
$function$;

(2022-04-18 05:55:32) postgres=# SELECT foo();
┌───────┐
│  foo  │
╞═══════╡
│ (1,2) │
│ (1,2) │
└───────┘
(2 rows)

(2022-04-18 05:55:37) postgres=# SELECT * FROM foo();
┌───┬───┐
│ a │ b │
╞═══╪═══╡
│ 1 │ 2 │
│ 1 │ 2 │
└───┴───┘
(2 rows)

Composite value can be unpacked, but packing to composite and unpacking has some performance impact:
(2022-04-18 05:55:43) postgres=# SELECT (foo()).*;
┌───┬───┐
│ a │ b │
╞═══╪═══╡
│ 1 │ 2 │
│ 1 │ 2 │
└───┴───┘
(2 rows)


text:
Q: Angular 2 Bind Component HTML Markup from Variable similar to innerHTML I'd like to generically render previews based on templates saved in a database within an angular 2 component.
The idea is to save a dynamic html sub part of an ng2 components HTML within the database and bind/insert it within the component.html similar to [innerHTML]=variable but instead of plain HTML bind ng2 markup. So the template can access specific variables available in the component.
I'd like to avoid to write a template parser myself.
Can I bind ng2 markup with any directive similar to [innerHTML]?


text:
Q: how to create a JWT token with a role of a user ( Spatie JWT web token) I want to pass the role of a user with a token after login. Instead of passing like below
 return response()->json([
            'success' => true,
            'access_token' => $token,
            'token_type' => 'bearer',
             'role' => auth('api')->user()->getRoleNames()
            /* 'expires_in' => auth('api')->factory()->getTTL() * 60 */
  ]);

I want to encode a role of a user with a JWT token. what I have tried
 public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->guard('api')->attempt($credentials)) {
            return response()->json(['errors' => 'In-valid username and Password'], 401);
        }
        return $this->respondWithToken($token);
    }

  protected function respondWithToken($token)
    {

        $role =auth('api')->user()->getRoleNames();
        $payload = JWTFactory::make($role);
        $token = JWTAuth::encode($payload);

        return response()->json([
            'success' => true,
            'access_token' => $token,
            'token_type' => 'bearer',
        ]);
    }

when I tried this I am not getting a token. I have seen this  documentation https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens to do this.
Thank you

A: Here we need to create our own  token with user role.The code which work for me and it may help to others.
 public function login()
    {
        $credentials = request(['email', 'password']);

        if (!auth()->guard('api')->claims(['role' => 'bar'])->attempt($credentials)) {
            return response()->json(['errors' => 'In-valid username and Password'], 401);
        }

        $token = auth('api')->claims(['role' => str_replace(['["', '"]', '/', '*'], '',auth('api')->user()->getRoleNames())])->attempt($credentials);
        return $this->respondWithToken($token);

    }

 protected function respondWithToken($token)
    {
        auth('api')->payload($token);
        return response()->json([
            'success' => true,
            'access_token' => $token,
            'token_type' => 'bearer',
        ]);
    }


text:
Q: reactjs: simple form/crud operations I have a component which are just 2 simple forms with crud operations. I've noticed that occassionally when I try to submit the form which calls my postData and updateData functions with the form fields the data will not be posted or updated to my mock api server. Currently, I don't see whats preventing the occasional request from being posted, what could be the reason?
import React,{useState,useEffect} from 'react';
import { Table, Button} from 'semantic-ui-react'
import axios from 'axios';
import './App.css';

function App() {
  /*Form input information*/
  const [first,setFirst] = useState('')
  const [last,setLast] = useState('')
  const [email,setEmail] = useState('')
  const [password,setPassword] = useState('')
  const [APIData, setAPIData] = useState([]);
  const [id,setID] = useState(null);
  const [display,setDisplay] = useState(false);

  const postData = () => {
    axios.post(`https://62a54643b9b74f766a3760d6.mockapi.io/fakeData`, {
      first,
      last,
      email,
      password
    })
  }

  useEffect(() => {
    axios.get(`https://62a54643b9b74f766a3760d6.mockapi.io/fakeData`)
        .then((response) => {
            setAPIData(response.data);
        })
  }, [])

  const getData = () => {
    axios.get(`https://62a54643b9b74f766a3760d6.mockapi.io/fakeData`)
        .then((response) => {
            setAPIData(response.data);
        })
  }

  const updateData = () => {
    axios.put(`https://62a54643b9b74f766a3760d6.mockapi.io/fakeData/${id}`, {
      first,
      last,
      email,
      password
    })
  }

  const onDelete = (id) => {
    axios.delete(`https://62a54643b9b74f766a3760d6.mockapi.io/fakeData/${id}`).then(() => getData())
  }

  return (

Sign Up Form

      <form >
        First:
        <input type="text" placeholder="First Name" onChange={ (e) => setFirst(e.target.value)}/>
        Last:
        <input type="text" placeholder="Last Name" onChange={ (e) => setLast(e.target.value)}/>
        Email:
        <input type="text" placeholder="Email" onChange={ (e) => setEmail(e.target.value)}/>
        Password:
        <input type="text" placeholder="Password" onChange={ (e) => setPassword(e.target.value)}/>
        <input type="submit" onClick={postData} value="Submit" style={{fontSize: '20px', padding: '11px', margin: '30px'}}/>
      </form>
      {display && (

Update Form ID: {id}

      <form >
      First:
      <input type="text" placeholder="First Name"  onChange={ (e) => setFirst(e.target.value)}/>
      Last:
      <input type="text" placeholder="Last Name" onChange={ (e) => setLast(e.target.value)}/>
      Email:
      <input type="text" placeholder="Email" onChange={ (e) => setEmail(e.target.value)}/>
      Password:
      <input type="text" placeholder="Password" onChange={ (e) => setPassword(e.target.value)}/>
      <input type="submit" onClick={updateData} value="Update here" style={{fontSize: '20px', padding: '11px', margin: '30px'}}/>
    </form>

      )
      }

First Name

Last Name

Email

Password

Update

Delete

          {APIData.map((data, index) => {
            return (

{data.first}

{data.last}

{data.email}

{data.password}

                  <Button onClick={()=>{setDisplay(!display)
                                        setID(data.id)}}>
                  Update</Button>

                  <Button onClick={() => onDelete(data.id)}>Delete</Button>

            )})}

  );
}

export default App;


text:
Q: C array segmentation fault Sometimes you will not get a runtime error when you access your array out of range in C code. such as:
char array[1024];
char* ptr = array;
*(ptr-10) = 'a';

//or

*(ptr-4096) = 'a';

Assuming the array is on the stack, I am curious about what is the MIN SIZE that will let *(ptr-SIZE) = 'a' throw a segmentation fault in any situation?
for example:
*(ptr-4096*1024) = 'a' // this will always throw a segmentation fault
*(ptr-4096*8) = 'a' // sometimes this will not throw a segmentation fault

2017/1/10, new added:
I feel sorry for not stating the question clearly. : (
What I want to know is not just a ambiguous UNDEFINED. Assuming the stack is high, and heap is low. So the memory layout will be:
high *********
     * stack *  <-  my array goes here
     *********
     *       *
     *       *  <-  ptr may be here
     *       *
     *********
     * heap  *
     *********
     * ???   *  <- ptr may be here
     *********

Of course I know that

The problem is that C/C++ doesn't actually do any boundary checking with regards to arrays. It depends on the OS to ensure that you are accessing valid memory

So, the code above will cause the OS kernel invoke do_page_fault, and will try to find vma of the address, and check if the vma->vm_start < address.
Now, let's come back to the question I asked: the MIN SIZE that will let *(ptr-SIZE) = 'a' throw a segmentation fault in any situation. In other word, I want to know the SIZE that the do_page_fault can afford. It is nothing about the C compiler, but how your OS protects your memory.

A: A C standard compliant compiler reserves the right to do anything if you index array[i] where i is less than 0 or greater than 1023.
The behaviour in such cases is said to be undefined.
Attempting to second-guess what will happen is futile. But you could always check the generated assembly if you're curious.


text:
Q: on flag click get series (graph) it's on highstock? I have several flags series, each of these series belongs to different graphs (i use onSeries prop). I want to know on which graph the flag is on when i click on it, so that when i use the click event in plotOptions.series.point.events.click i could get the graph point and not the flag point.
plotOptions.series.point.events.click = function(){console.log(this)}

i have tried to pass the event param in to the callback but there is nothing conserning the graph it's on

A: You should have a look at the this.options array. The onSeries option is available with this.options.onSeries.
Here is a quick example: http://jsfiddle.net/yP5z3/1/


text:
Q: Input variable box is not appearing and asking for input value and loop is not working write a program that repeatedly read numbers until the user enters "done". Once "done" is entered, print out the total, count, and average numbers. if the user enters anything other than number, detect their mistake using try and except and print an error message and skip to the next number.
Enter a number: 4 Enter a number: 5 Enter a number: bad data Invalid input Enter a number: 7 Enter a number: done
""" """Approach1 """
Number = input(Enter a number: )
count = 0
total = 0
average = 0
try:
    number = float(Number)
except ValueError:
    print('Invalid input')
    quit()
while True:                               # Stays in loop until break
    number = input('Enter a number: ')
    if number == 'done':
        break                             # Exits the while loop

    number = check_for_float(input_number)
for a number in Number:
    count = count + 1
    total = total + 1
    average = number / count
    print("Total:", total , "Count:", count, "Average: ", average)

After running this program, I was expecting an input box to pop and ask for input value which is not happening. Please advise.


text:
Q: Mobile database synchronization I have to write an app running on Android, iOS and desktops (I will probably use Titanium). This app has to maintain a database that is constantly synchronized between all devices and desktop (and maybe the web in the future).
Is there any tool/service allowing to do database synchronization very easily?
I want something where I write data locally on any device and data is automatically synchronized and merged using to all devices using the cloud.

A: CouchDB is the way to go.  I'm working on a similar project right now.  iOS, Android, web client - they all need synchronization.  CouchDB has fantastic replication support that is all done over HTTP.  It's a thing of beauty.  Couchbase Mobile is still very much in a "developer preview" state, but progressing nicely.
You will have to handle potential update conflicts (CouchDB returns an HTTP 409 status code so you can handle it appropriately - based on your business requirements).
My only complaints so far is the boot up time of the CouchDB service and the size of the dependencies. If you can work around those problems, it might be a good solution for you.
Checkout more here: http://www.couchbase.com/products-and-services/couchbase-mobile
Good luck!

A: You can use Mobeelizer. It is a solution, which offers you the complete sync infrastructure for mobile apps and allows you easily synchronize data between mobile and web or desktop application. There is also Titanium SDK for you. Here you can find more information http://docs.mobeelizer.com/display/doc/Titanium+References


text:
Q: Placeholder Color Change in Bootstrap How can I change the Placeholder Color in Bootstrap?
The following code, which I tried, doesn't work.
input::-webkit-input-placeholder {
        color: red;
}

input:-moz-placeholder {
        color: red;
}

A: In Bootstrap 4 you change it like this:
.form-control::-webkit-input-placeholder {
  color: red;
}

A: .form-control::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
            color: red;
            opacity: 1; /* Firefox */
}

.form-control:-ms-input-placeholder { /* Internet Explorer 10-11 */
            color: red;
}

.form-control::-ms-input-placeholder { /* Microsoft Edge */
            color: red;
 }

The following is the reference link.
https://www.w3schools.com/howto/howto_css_placeholder.asp

A:
try this "!important" keyword

.input::placeholder {
 color: red !important;
 opacity: 1;
 }

A: For Bootstrap 4, if you're using SCSS, just override variable $input-placeholder-color before you import bootstrap.
// variable overrides
$input-placeholder-color: red;

// Bootstrap and its default variables
@import "../node_modules/bootstrap/scss/bootstrap";


text:
Q: Form input values not remain after flash error message How to solve above issue? I want to keep test even after a validation failure in the submission. But after session error message is passed all the entered data will be gone.

A: To re-fill the form with the input data again, check the input validation then if validation fails, redirect the user back along with his input data and validation errors.
$validator = Validator::make($request->all(), [
        // your validation rules.
        'name' => 'required',
    ]);
if ($validator->fails()) {
    return redirect()->back()->withErrors($validator)->withInput();
}
// Continue your app logic.

You'll find more information in Laravel validation docs

A: You should send back the input also to the view.
Like Sameh Salama already mentioned, use the following code:
function () {
    return redirect()->back()->withErrors($validator)->withInput();
}

Notice the withInput() function, it returns the old input.
Use it in the View as
<input type="something" value="{{$input->first_something}}" />