text:
Q: Using operators in Parameters.AddWithValue I was trying to use an operator in Parameters.AddWithValue for my login form, But it throws an error with username must be not null, How should I use an operator in Parameters.AddWithValue? Here's my recent work:
public JsonResult Loginzxc(string email, string username, string password)
        {
            using (SqlConnection con = new SqlConnection(constring))
            {
                string status;
                string user_type;
                string reg_no;

                string access = "select reg_no, username, status, user_type, password from accounts " +
                    "union select reg_no, username, status, user_type, password from admin_accounts where username = @user or email = @email";

                string pass1;

                //if(username == null)
                //{
                //    return Json("wrong_username");
                //} else
                if(password == null)
                {
                    return Json("wrong_password");
                }

                pass1 = ComputeSha256Hash(password);

                using (SqlCommand com = new SqlCommand(access, con))
                {
                    com.Parameters.AddWithValue("@user", username); //Trying to merge @email and username
                    com.Parameters.AddWithValue("@email", email); //Trying to merge @email and username
                    com.CommandTimeout = 60;
                    SqlDataReader rreader;
                    using(con)
                    {
                        con.Open();
                        rreader = com.ExecuteReader();
                        if(rreader.HasRows == true)
                        {
                            while(rreader.Read())
                            {
                                string pass2 = rreader["password"].ToString();
                                status = rreader["status"].ToString();
                                user_type = rreader["user_type"].ToString();
                                reg_no = rreader["reg_no"].ToString();

                                if(user_type == "0")
                                {
                                    user_type = "ADMIN";
                                } else if(user_type == "1")
                                {
                                    user_type = "MEMBER";
                                }

                                if(pass2 != pass1)
                                {
                                    return Json("wrong_password");
                                }

                                if (status == "INACTIVE")
                                {
                                    return Json("INACTIVE");
                                }
                                else if (status == "BLOCKED")
                                {
                                    return Json("BLOCKED");
                                } else if(status == "ACTIVE")
                                {
                                    HttpContext.Session.SetString("username", username);
                                    HttpContext.Session.SetString("reg_no", reg_no);
                                    HttpContext.Session.SetString("user_type", user_type);

                                    if (user_type == "ADMIN")
                                    {
                                        return Json(new { redirectUrl = Url.Action("Index", "Admin", new { id = "DSA" + reg_no }) });

                                    } else if(user_type == "MEMBER")
                                    {
                                        return Json(new { redirectUrl = Url.Action("Index", "Home", new { id = "DSA" + reg_no }) });
                                    }
                                } else
                                {
                                    return Json("error");
                                }
                            }
                        }
                        con.Close();
                    }
                    ViewBag.notfound = "login";
                    return Json("no record");
                }
            }
           // return Json("");
        }

A: If you're trying to convert null values to an empty string try:
com.Parameters.AddWithValue("@user", username ?? string.Empty); //Trying to merge @email and username
com.Parameters.AddWithValue("@email", email ?? string.Empty); //Trying to merge @email and username

?? is the Null Coalescing Operator, that takes the first non-null value it finds. It can also be chained like variable1 ?? variable2 ?? "bob" , that will return "bob" if the preceding two variables are null.

A: I forgot about using if else statement to set null to ""
if (username == null)
   {
       username = "";
   } else if (email == null) {
       email = "";
   } else if (password == null)
   {
       return Json("wrong_password");
   }


text:
Q: Charts Swift 4.0 Viewport compile error I added Charts through pods in a new project, and it compiles fine.
But in the project where I actually need it, I get the attached errors during compilation.
Swift Language is set to Swift 4.0 in Build Settings.
Deployment Target is 9.0
There is currently no code using the Library, the error occurs after adding the Pod and trying to compile the existing project.
Are there any other settings I have to check regarding these errors?

@objc open lazy var rightYAxisRenderer = YAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: rightAxis, transformer: _rightAxisTransformer)

@objc open lazy var leftYAxisRenderer = YAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: leftAxis, transformer: _leftAxisTransformer)

@objc open lazy var xAxisRenderer = XAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer)

Cannot use instance member '_viewPortHandler' within property initializer; property initializers run before 'self' is available

ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: color])
Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font'

Definition of variables
internal var _viewPortHandler: ViewPortHandler

@objc public init(viewPortHandler: ViewPortHandler)
{
   _viewPortHandler = viewPortHandler
}

A: This process worked out for me

*

*Removed the Charts pod of older version (3.0.3).

*Installed the new version(3.1.x) of Charts through pods.

*Changed the Charts Swift Compiler language to 4.1 version

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to update OpenGL to 4.x from 3.3 The output of glxinfo | grep "OpenGL" is as follows:
OpenGL vendor string: X.Org
OpenGL renderer string: AMD TURKS (DRM 2.49.0 / 4.10.0-38-generic, LLVM 6.0.0)
OpenGL core profile version string: 3.3 (Core Profile) Mesa 18.1.0-devel
OpenGL core profile shading language version string: 3.30
OpenGL core profile context flags: (none)
OpenGL core profile profile mask: core profile
OpenGL core profile extensions:
OpenGL version string: 3.0 Mesa 18.1.0-devel
OpenGL shading language version string: 1.30
OpenGL context flags: (none)
OpenGL extensions:
OpenGL ES profile version string: OpenGL ES 3.1 Mesa 18.1.0-devel
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.10
OpenGL ES profile extensions:

I have tried all these ppas: ppa:oibaf/graphics-drivers, ppa:eek:ibaf/graphics-drivers, ppa:ubuntu-x-swat/updates but still my core profile version is at 3.3. All these help in updating the Mesa version which I know is the latest one currently, however the core profile version is stuck at 3.3 awfully!
My graphics card is AMD/ATI Turks XT Radeon HD 6670/7670 which as per Wikipedia page should support OpenGL 4.5.
I have read many askubuntu posts and other webpages none of them helped surprisingly given that it is a very old issue. I am also surprised how difficult it is to update drivers in case of linux! Please help!

A: As per the Radeon Feature page, the HD 6670/7670 is still only supported with OpenGL 3.3, as it is the Turks chip, and not one of Cypress, Cayman, or Aruba. Therefore you will not be able to enable newer versions of OpenGL on the card at this time, with a software upgrade.

A: I'm with the same problem, I have the following hybrid Intel/AMD configuration:
00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)
01:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Whistler [Radeon HD 6730M/6770M/7690M XT]
And I'm stuck in OpenGL 3.3 since Ubuntu 16.04, in Ubuntu 15.10 I had the possibility to use the private fglrx driver which updates the OpenGL to the version 4.1
Using the last Kernel and the last Mesa Drivers (Padoka) I don't see any improvement :(
OpenGL renderer string: AMD TURKS (DRM 2.50.0 / 4.18.5-041805-generic, LLVM 8.0.0)
OpenGL core profile version string: 3.3 (Core Profile) Mesa 18.3.0-devel - padoka PPA

The main Point here is, what I understand from this Web RadeonFeature is our Graphic Card is included under R600/700, although should be as Northern Islands, which supports OpenGL 4.x :(

Why is this happening?


text:
Q: 2 condition in pandas dataFrame indexes I have this rows filtering:
idx = dataset.data.groupby(['a', 'b'])['c'].transform(max) == dataset.data['c']
dataset.data = dataset.data[idx]

For this dataset:
a | b | c | d
0 | 0 | 1 | True
0 | 0 | 2 | True
0 | 1 | 3 | True
0 | 2 | 4 | False
0 | 2 | 5 | False

I'll get:
a | b | c | d
0 | 0 | 1 | True
0 | 1 | 3 | True
0 | 2 | 5 | False

I want to add for this condition that removes only rows that their field 'd' is false, so in the above example I'll get:
a | b | c | d
0 | 0 | 1 | True
0 | 0 | 2 | True
0 | 1 | 3 | True
0 | 2 | 5 | False

Can someone help me add it, please?
Thanks!

A: IIUC, keep rows where 'c' is the max or d is True:
import pandas as pd

df = pd.DataFrame({
    'a': [0, 0, 0, 0, 0],
    'b': [0, 0, 1, 2, 2],
    'c': [1, 2, 3, 4, 5],
    'd': [True, True, True, False, False]
})

# Max value of C
c1 = df.groupby(['a', 'b'])['c'].transform(max) == df['c']
# D is True
c2 = df.d
# Or together
idx = c1 | c2

print(df[idx])

df[idx]:
   a  b  c      d
0  0  0  1   True
1  0  0  2   True
2  0  1  3   True
4  0  2  5  False

The one-liner:
df[df.groupby(['a', 'b'])['c'].transform(max).eq(df['c']) | df['d']]


text:
Q: Laravel - Filter using Between Dates and a Dropdown I am combining two tables to generate a report that will be exported to excel. It should be filtered using between dates and parameter in dropdownlist
I have created the model, query in the controller and also the view. I can export the report to excel, but don't know how to filter it in the controller and view. The two tables are:

*

*users (User: id,name,username)

*played_game (PlayedGame: id, user_id, game, created_at)

Controller
public function playersPerGame()//public function playersPerGame(Request $request)
    {
        $games = DB::table('played_game')
                     ->select(DB::raw('count(*) as no_of_players, game'))
                     ->groupBy('game')
                     ->get();
         return view('report.playersPerGame', compact('games'));
    }
     public function playersExport() {

     $players = PlayedGame::select(
               "game",
               \DB::raw("SUM(count(*)) as `no_of_players`"))
               //->groupBy("game")
               ->get();
     // Initialize the array which will be passed into the Excel
     // generator.
     $playersArray = [];

     // Define the Excel spreadsheet headers
     $playersArray[] = ['Games', 'No. of Players'];

     // Convert each member of the returned collection into an array,
     // and append it to the payments array.
     foreach ($players as $player) {
          $playersArray[] = $player->toArray();
     }

route
    Route::get('/report/players-per-game', ['as' => 'playersPerGame', 'uses' => 'ReportController@playersPerGame']);
    Route::get('/report/players-export', 'ReportController@playersExport')->name('players-export');

view

         Excel

            #
            Player
            No. of Games

        @foreach($players as $key => $player)

                {{ ++$key }}
                {{ $player->name }}
                {{ $player->no_game }}

        @endforeach

When I get to the view page:

*

*I want to filter using between dates (played_game.created_at), dropdownlists (users.name and played_game.game) before exporting to excel


text:
Q: How to remove cross-validation with train_test_split? My code:
X = data['text_with_tokeniz_lemmatiz']
y = data['toxic']
X_train, X_tmp, y_train, y_tmp = train_test_split(X, y, train_size=0.8, test_size=0.2, shuffle=False, random_state=12345)
X_valid, X_test, y_valid, y_test = train_test_split(X_tmp, y_tmp, test_size=0.5, shuffle=False, random_state=12345)
The inspector wrote to me: "You use both validation sampling and cross-validation at the same time. It would be better to transfer the entire project to cross-validation and increase the amount of data in training."
How to fix it?
i dont know(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((

A: When using a validation dataset, we usually train a model on the training data and evaluate its performance on the validation data.
Cross-validation is essentially the same thing, but done multiple times, with different splits.
As your inspector suggests, it is not necessary to split the validation data yourself, as this is already done during cross-validation.
It is hard to say how you can fix it when we don't see how you use the validation data in the code. From what I see, you first need to get rid of the validation data entirely, so the code would look like:
X = data['text_with_tokeniz_lemmatiz']
y = data['toxic']
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.9, test_size=0.1, shuffle=False, random_state=12345)

If latter in the code you use validation data to measure the performance of your learning algorithm, you can replace that with cross-validation, for instance using Scikit Learn's cross_val_score.


text:
Q: HTML: How to limit file upload to be only images? With HTML, how do I limit what kind of filetypes can be uploaded?
To easy the user experience, I want to limit file uploads to be only images (jpeg, gif, png).
<form method="post" action="..." enctype="multipart/form-data">
Photo
<input name="image" type="file" />
</form>

A: Edited
If things were as they SHOULD be, you could do this via the "Accept" attribute.
http://www.webmasterworld.com/forum21/6310.htm
However, browsers pretty much ignore this, so this is irrelavant.  The short answer is, i don't think there is a way to do it in HTML.  You'd have to check it server-side instead.
The following older post has some information that could help you  with alternatives.
File input 'accept' attribute - is it useful?

A: Here is the HTML for image upload. By default it will show image files only in the browsing window because we have put accept="image/*". But we can still change it from the dropdown and it will show all files. So the Javascript part validates whether or not the selected file is an actual image.

     <input name="image3" type="file" accept="image/*" id="menu_images"/>

     <input type="submit" value="Submit" />

Here on the change event we first check the size of the image. And in the second if condition we check whether or not it is an image file.
this.files[0].type.indexOf("image") will be -1 if it is not an image file.
document.getElementById("menu_images").onchange = function () {
    var reader = new FileReader();
    if(this.files[0].size>528385){
        alert("Image Size should not be greater than 500Kb");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();
        return false;
    }
    if(this.files[0].type.indexOf("image")==-1){
        alert("Invalid Type");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();
        return false;
    }
    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("menu_image").src = e.target.result;
        $("#menu_image").show();
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};

A: This is what I have been using successfully:
...

    <input type="file" class="custom-file-input image-gallery" id="image-gallery" name="image-gallery[]" multiple accept="image/*">
   Upload Image(s)

...

It is always a good idea to check for the actual file type on the server-side as well.

A: HTML5 says <input type="file" accept="image/*">. Of course, never trust client-side validation: Always check again on the server-side...

A:

Now in the html part
<input type="file" onchange="chng()">

this code will check if the uploaded file is a jpg file or not and restricts the upload of other types

A: HTML5 File input has accept attribute and also multiple attribute. By using multiple attribute you can upload multiple images in an instance.
<input type="file" multiple accept="image/*">

You can also limit multiple mime types.
<input type="file" multiple accept="image/*,audio/*,video/*">

and another way of checking mime type using file object.
file object gives you name,size and type.
var files=e.target.files;

var mimeType=files[0].type; // You can get the mime type

You can also restrict the user for some file types to upload by the above code.

A: You can only do this securely on the server-side. Using the "accept" attribute is good, but must also be validated on the server side lest users be able to cURL to your script without that limitation.
I suggest that you: discard any non-image file, warn the user, and redisplay the form.

A: Because <input type="file" id="fileId" accept="image/*"> can't guarantee that someone will choose an image, you need some validation like this:
if(!(document.getElementById("fileId").files[0].type.match(/image.*/))){
                alert('You can\'t upload this type of file.');
                return;
}

A: Ultimately, the filter that is displayed in the Browse window is set by the browser. You can specify all of the filters you want in the Accept attribute, but you have no guarantee that your user's browser will adhere to it.
Your best bet is to do some kind of filtering in the back end on the server.

A: Checkout a project called Uploadify. http://www.uploadify.com/
It's a Flash + jQuery based file uploader. This uses Flash's file selection dialog, which gives you the ability to filter file types, select multiple files at the same time, etc.


text:
Q: How to debug issues when adding packages to a meteor project I installed meteor 1.8.1 yesterday.
And then i tried to install coffeescript.
just like this :
"meteor add coffeescript"
but error is like this :
Error: Could not get https://warehouse.meteor.com/builds/EXSxwGqYjjJKh3WMJ/1540998837302/9YEg39egQi/coffeescript-2.3.2_1-os+web.browser+web.browser.legacy+web.cordova.tgz; server returned [502]
Does any one solved this problem?
How would you go about debugging a problem like this?

A: Like @Jankapunkt suggested, I would start debugging this at the network level:

*

*verify that you can ping warehouse.meteor.com

*run

curl -i https://warehouse.meteor.com/builds/EXSxwGqYjjJKh3WMJ/1540998837302/9YEg39egQi/coffeescript-2.3.2_1-os+web.browser+web.browser.legacy+web.cordova.tgz

and check for errors. There might be a more elaborate error description you can get this way rather than just the error code (502 in your case).


text:
Q: Dependency Injection failing in ASP.NET Core MVC and Entity Framework Core I am using Entity Framework Core 2.1.11
I have just initialized a database I will be using in my Website.
I used the Scaffold-DbContext command successfully, and it has now created all the model classes and data context class.
In the StartUp.ConfigureServices I have the following:
public void ConfigureServices(IServiceCollection services)
{
    string connection = //correct connection string used in Scaffolding
    services.AddDbContext<Models.WebsiteContext>(options => options.UseSqlServer(connection));

    services.AddMvc();
}

In my view, I have the following simple thing to test to see if it is working correctly:
@page
@model IEnumerable<Website.Models.Levels>

  @foreach (var item in Model)
  {

      @item.Id

  }

But unfortunately I get a cryptic error message that I'm not sure what it means:

To further add: when I debug the project, the constructor of the context does not get hit. I'm not sure why

A: Dependency injection is a technique for achieving inversion of control it is majorly to inject a service into the constructor of the class where it will be used.
Basically, you inject a service from an interface it implements. for instance
If you have an interface
public interface IMyInterface
{
     void doMyWork();
}

And then you had a service that implements this interface
public class MyService : IMyInterface
{
    public void doMyWork() {
        //the work is done here
        //get to the db and fetch some good stuff the users needs
    }
}

An you want to use DI to call this service from your controller if you are using MVC
public class HomeController : Controller
{
    private readonly IMyInterface _myinterface;

    public HomeController(IMyInterface myinterface)
    {
        _myinterface = myinterface;
    }

    public IActionResult Index()
    {
         var theWork = _myinterface.doMyWork();
    }
}

So lets say you are using a db connection as in your case your startup config needs to bind the service and the interface services.AddSingleton
public void ConfigureServices(IServiceCollection services)
{
    string connection = //correct connection string used in Scaffolding
    services.AddDbContext<Models.WebsiteContext>(options => options.UseSqlServer(connection));

    services.AddSingleton<IMyInterface, MyService>();

    services.AddMvc()
}

for more on DI for ASP.NET Core see docs


text:
Q: How to force dbo schema name? I'm using "SQL SERVER PROJECT" in VS 2008 to create UDF in C#
Then I'm using DEPLOY command to publish DLL into MS SQL server 2005
All works well except all created UDFs are owned by me (as user)
But I wanted to keep dbo schema (eg: dbo.UDF_TEST - not jonny.UDF_TEST)
Any idea how to manage thar?

A: deploy the UDF from an account that is sysadmin, or dbo on the database.
You can build the dll and then manually deploy it  by logging into management studio as dbo to the database and running these commands:

CREATE ASSEMBLY Geocode FROM
'C:\PATH\YourUDF.dll' WITH
PERMISSION_SET = SAFE

or

*

*From within Visual Studio in the
solution explorer click on the UDF
project (not the solution).

*Go to properties.

*Click on the database tab.

*You can change the connection
string, and also change the assembly
owner here.

A: I've found another approach allowing do everything inside VS.
I've added to project SQL script named "postdeployscript.sql":
DECLARE @SQL NVARCHAR(200)
SET @SQL = 'alter schema dbo transfer ' + CURRENT_USER +'.[UDF_GET_AUDIT_VALUE]'
EXECUTE (@SQL)
GO
script is executed automaticcally by VS during depolyment process and changes schemas from current user to DBO.
Cons: you need to add each UDF/USP you are ceating manually
PS: Please note you can also use predeployscript.sql to execute some commmands before deployment


text:
Q: Neo4j long lasting query to be split/executed in smaller chunks? My import.csv creates many nodes and merging creates a huge cartesian product and runs in a transaction timeout since the data has grown so much. I've currently set the transaction timeout to 1 second because every other query is very quick and is not supposed to take any longer than one second to finish.
Is there a way to split or execute this specific query in smaller chunks to prevent a timeout?
Upping or disabling the transaction timeout in the neo4j.conf is not an option because the neo4j service needs a restart for every change made in the config.
The query hitting the timeout from my import script:
 MATCH (l:NameLabel)
 MATCH (m:Movie {id: l.id,somevalue: l.somevalue})
 MERGE (m)-[:LABEL {path: l.path}]->(l);

Nodecounts: 1000 Movie, 2500 Namelabel

A: You can try installing APOC Procedures and using the procedure apoc.periodic.commit.
call apoc.periodic.commit("
  MATCH (l:Namelabel)
  WHERE NOT (l)-[:LABEL]->(:Movie)
  WITH l LIMIT {limit}
  MATCH (m:Movie {id: l.id,somevalue: l.somevalue})
  MERGE (m)-[:LABEL {path: l.path}]->(l)
  RETURN count(*)
",{limit:1000})

The below query will be executed repeatedly in separate transactions until it returns 0.
You can change the value of {limit : 1000}.
Note: remember to install APOC Procedures according the version of Neo4j you are using. Take a look in the Version Compatibility Matrix.

A: The number of nodes and labels in your database suggest this is an indexing problem. Do you have constraints on both the Movie and Namelabel (which should be NameLabel since it is a node) nodes? The appropriate constraints should be in place and active.

Indexing and Performance
Make sure to have indexes and constraints declared and ONLINE for
entities you want to MATCH or MERGE on
Always MATCH and MERGE on a
single label and the indexed primary-key property
Prefix your load
statements with USING PERIODIC COMMIT 10000 If possible, separate node
creation from relationship creation into different statements
If your
import is slow or runs into memory issues, see Mark's blog post on
Eager loading.

If your Movie nodes have unique names then use the CREATE UNIQUE statement. - docs
If one of the nodes is not unique but will be used in a relationship definition then the CREATE INDEX ON statement. With such a small dataset it may not be readily apparent how inefficient your queries are. Try the PROFILE command and see how many nodes are being searched. Your MERGE statement should only check a couple nodes at each step.


text:
Q: How to add password to smtp settings without comprimizing account security I am trying to set up an email contact form on my Rails app, but I am having trouble figuring out how to get the settings in config/production to read my password, without comprising my account.
Here are a heroku configs:
Jillians-MacBook-Pro-2:noises3 Jillian$ heroku config
=== noises Config Vars
DATABASE_URL:             xxxdatabaseurlxxx
LANG:                     en_US.UTF-8
RACK_ENV:                 production
RAILS_ENV:                production
RAILS_SERVE_STATIC_FILES: enabled
S3_BUCKET:                muzack
SECRET_KEY_BASE:          xxxsecretxxx
gmail_password:           xxxmy_passwordxxx
gmail_username:           xxxmy_emailxxx

And my smtp settings, in config/production.rb:
  config.action_mailer.smtp_settings = {
    address:              'smtp.gmail.com',
    port:                 587,
    domain:               'gmail.com',
    user_name:            ENV['gmail_username'],
    password:             ENV['gmail_password'],
    authentication:       :plain
  }

And in config/initializers/smtp_settings.rb:
ActionMailer::Base.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => 587,
    :domain => "gmail.com",
    :user_name => "jho3292@gmail.com",
    :password => WHAT DO I DO HERE???
    :authentication => :plain,
    :enable_starttls_auto => true
}

Does anyone know how to do this correctly?


text:
Q: Aptana vs. Eclipse - pygame working only on Aptana? Have used Eclipse with PyDev for a while...without any problems. Recently I wanted to try out PyGame but the problem is that Eclipse gives errors when trying to do that:
Traceback (most recent call last):
File "C:\Users\Artur\workspace\miniprojekt\src\pygame.py", line 1, in <module>
import pygame
File "C:\Users\Artur\workspace\miniprojekt\src\pygame.py", line 2, in <module>
from pygame.locals import *
ImportError: No module named locals

Then after trying to find a solution for a few hours without luck... decided to try some other IDE programs and finally found Aptana Studio which is based on Eclipse if I'm not wrong. Aptana uses the same PyDev add-on but the difference is that the code works there without problems.
Then I decided to try Aptana plugin for eclipse, thinking that maybe it would make a differece. And again I get the same error as before.
The code works in Python IDLE and in Aptana Studio 3 with PyDev...
The code doesn't work on Eclipse SDK 3.7.1 with PyDev...
And now I'm having trouble understanding why PyGame works in Aptana and not in Eclipse, as they both apparently use PyDev?
Also all solutions for using PyGame in Eclipse are welcome...
(I'm using Python 3.2)

A: You are right in that Aptana Studio 3 uses the same PyDev you installed, so, it should be exactly the same thing... do the following:

*

*Update PyDev to the latest nightly build -- this is just to be sure you have the proper version.

*Rename your own module from pygame.py to something else... i.e.: mypygame.py (this should fix your problem, as what's probably happening is that when it's looking for pygame it's finding your version and not the pygame you really wanted).
Note: just to be in the safe side, you may want to clear all your .pyc files too (right click folder > pydev > remove *.pyc)


text:
Q: Cannot assign "(, True)" "Profile.user" must be a "User" instance i Use One-To-One Link With a User Model (Profile)
and i got this error when i try to make user registration
Cannot assign "(, True)": "Profile.user" must be a "User" instance.
and this is user_registration uses in my project
thanks for help
def user_registration(request):
    form = UserRegistrationForm()
      if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            structure= form.cleaned_data['structure'].id
            user = User.objects.get_or_create(username=username,  password=password)
            profile=Profile.objects.create(structure_id=structure,user=user)
            profile.save()
            messages.success(request,
            'Enregistrement avec succés {}'.format(user.username))
        return HttpResponseRedirect(reverse('compte:login'))
    else:
        form = UserRegistrationForm()
        return render(request,'compte/register.html',{'form':form})

this is my traceback :
[01/Aug/2019 22:01:13] "GET /compte/register/ HTTP/1.1" 200 2194
[01/Aug/2019 22:01:16] "GET /static/js/popper.min.js HTTP/1.1" 404 1773
[01/Aug/2019 22:01:16] "GET /static/js/jquery-3.3.1.slim.min.js HTTP/1.1" 404 1806
[01/Aug/2019 22:01:16] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 1782
[01/Aug/2019 22:01:16] "GET /compte/register/ HTTP/1.1" 200 2194
[01/Aug/2019 22:01:16] "GET /static/js/jquery-3.3.1.slim.min.js HTTP/1.1" 404 1806
[01/Aug/2019 22:01:16] "GET /static/js/popper.min.js HTTP/1.1" 404 1773
[01/Aug/2019 22:01:16] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 1782
Internal Server Error: /compte/register/
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/mac/Desktop/investissement/Invest_App/compte/views.py", line 38, in user_registration
    profile=Profile.objects.create(structure_id=structure,user=user)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 420, in create
    obj = self.model(**kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 483, in init
    _setattr(self, field.name, rel_obj)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 301, in set
    super().set(instance, value)
  File   "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-  packages/django/db/models/fields/related_descriptors.py", line 211, in    set
     self.field.remote_field.model._meta.object_name,
     ValueError: Cannot assign "(, True)": "Profile.user"   must be a "User" instance.
    [01/Aug/2019 22:01:25] "POST /compte/register/ HTTP/1.1" 500 91942

A: get_or_create returns a tuple of the item and a boolean indicating whether it was created. You should capture both:
user, created = User.objects.get_or_create(username=username,  password=password)
profile = Profile.objects.create(structure_id=structure,user=user)

However, you shouldn't do this either. By doing this you're ensuring that the password is saved without hashing; and in any case, username is a unique field, so the form will not be valid if the username already exists.
Call form.save directly:
user = form.save()

Note also, you don't need to call profile.save(), as create saves the item itself.

A: A .get_or_create(..) [Django-doc] will return a 2-tuple with the first item the object generated, and the second a boolean that specifies if it created a new object. You thus can use iterable unpacking here, to get access to the first element.
def user_registration(request):
    form = UserRegistrationForm()
      if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            structure = form.cleaned_data['structure'].id
            user, __ = User.objects.get_or_create(username=username,  password=password)
            profile = Profile.objects.create(structure_id=structure,user=user)
            profile.save()
            messages.success(request, 'Enregistrement avec succés {}'.format(user.username))
        return HttpResponseRedirect(reverse('compte:login'))
    else:
        form = UserRegistrationForm()
        return render(request,'compte/register.html',{'form':form})
That being said, the above will not work, since passwords are not saved as raw text in the database, but hashed. You this will need to set the password with .set_password(..) [Django-doc]. You might want to use .update_or_create(..) [Django-doc] for your Profile, to prevent errors in case the profile already exists for that user:
def user_registration(request):
    form = UserRegistrationForm()
      if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            structure = form.cleaned_data['structure'].id
            user, __ = User.objects.get_or_create(username=username)
            user.set_password(password)
            user.save()
            Profile.objects.update_or_create(
                user=user,
                defaults={'structure_id': structure}
            )
            messages.success(request, 'Enregistrement avec succés {}'.format(user.username))
        return redirect('compte:login')
    else:
        form = UserRegistrationForm()
        return render(request,'compte/register.html',{'form':form})


text:
Q: Authenticating Google Cloud Speech via GRPC on C# using an API key i want to implement streaming voice recognition on C# on GRPC, but only have an API KEY
this type of key --> https://cloud.google.com/docs/authentication/api-keys
i know by searching the web that in others languages (android, IOs) they can "intercept" and add a header with the key like:
Metadata.Key.of("x-goog-api-key", "value");
how can i make the same BUT in c#?
my code, if it is neccesary for any reason.
public static async Task<object> StreamingRecognizeAsync(Stream audio)
    {
        var speech = SpeechClient.Create();

        var streamingCall = speech.StreamingRecognize();

        // Write the initial request with the config.
        await streamingCall.WriteAsync(
            new StreamingRecognizeRequest()
            {
                StreamingConfig = new StreamingRecognitionConfig()
                {
                    Config = new RecognitionConfig()
                    {
                        Encoding =
                        RecognitionConfig.Types.AudioEncoding.Linear16,
                        SampleRateHertz = 16000,
                        LanguageCode = "en",
                    },
                    InterimResults = true,
                }
            });
        // Print responses as they arrive.
        Task printResponses = Task.Run(async () =>
        {
            while (await streamingCall.ResponseStream.MoveNext(
                default(CancellationToken)))
            {
                foreach (var result in streamingCall.ResponseStream
                    .Current.Results)
                {
                    foreach (var alternative in result.Alternatives)
                    {
                        Console.WriteLine(alternative.Transcript);
                    }
                }
            }
        });

        var buffer = new byte[32 * 1024];
        int bytesRead;

        while ((bytesRead = await audio.ReadAsync(
                buffer, 0, buffer.Length)) > 0)
        {
            await streamingCall.WriteAsync(
                new StreamingRecognizeRequest()
                {
                    AudioContent = Google.Protobuf.ByteString
                    .CopyFrom(buffer, 0, bytesRead),
                });
            await Task.Delay(500);
        };

        await streamingCall.WriteCompleteAsync();
        await printResponses;
        return 0;
    }

Thank you very much

A: gRPC allows passing additional settings per-call.
In your case, the following should do the trick:
speech.StreamingRecognize(Google.Api.Gax.Grpc.CallSettings.FromHeader("x-goog-api-key", YOUR_API_KEY));

(Note: are you sure it's x-goog-api-key and not simply x-api-key?)


text:
Q: How to get azure ad refresh token with react I am doing a project with React, msal-react, and msal-browser.
I can get an access token with functions provided with msal-react library, but I cannot get the refresh token manually.
I can see from the network that a token request is performed when user is logged in by redirect, and obviously returned both token and refresh token. However, the refresh token is very well protected and cannot be found under cookie, session storage, or the instance.
Is it possible for the frontend to get refresh token of azure ad?
sorry, I cannot post my code due to security requirements

A: Refresh tokens are intentionally not returned on the public API surface as MSAL will handle all required token refreshes under the hood when you call acquireTokenSilent. If the backend service needs its own access token it needs to use a server side library such as msal-node. We do not recommend or support obtaining tokens using the SPA library and passing them down to a backend as tokens should only be sent to the resource they are intended for.


text:
Q: CSRF token mismatch in iframe (The Good fix ?) Form submission in <iframe> using laravel throwing 419 CSRF token mismatch error
I came across couple of solutions but want's a secure one
Please assist which approach is better keeping good security

*

*Excluding URIs From CSRF Protection https://laravel.com/docs/8.x/csrf#csrf-excluding-uris

*Extend Cookie Support for SameSite=None, Secure https://laracasts.com/discuss/channels/laravel/embedding-laravel-form-in-iframe-shows-419-csrf-token-mismatch-error
Thanks

A: This solution is working for me
Yes, you can play with the config/session.php same_site value.
'same_site' => 'lax'

to
'same_site' => 'none',

add in your .env file
SESSION_SECURE_COOKIE=true


text:
Q: How to implement a factory pattern based on argument types? I have PhotoBase class
public abstract class PhotoBase
{
    public string Path { get; set; }
}

And I have multiple derived classes, for example the path may indicate a location in the file system or an external url.
public class FilePhoto : PhotoBase {}

public class ExternalPhoto : PhotoBase {}

I want to load these photos, I have a PhotoLoader class like below:
public class PhotoLoader
{
    public void Load(FilePhoto Photo)
    {
        // get the photo from file system
    }

    public void Load(ExternalPhoto Photo)
    {
        // download the photo from path
    }
}

Now I want to load these photos, so I have to do:
public class PhotoImporter
{
    private PhotoLoader _photoLoader;

    public PhotoImporter(PhotoLoader photoLoader)
    {
        _photoLoader = photoLoader;
    }

    public void ImportPhoto(PhotoBase photo)
    {
        if (photo is FilePhoto)
        {
            _photoLoader.Load(photo as FilePhoto);
        }

        if (photo is ExternalPhoto)
        {
            _photoLoader.Load(photo as ExternalPhoto);
        }
    }
}

I have several derived classes and I may add more photo types in the future. Is there a more elegant way that I could get rid of if conditions? Using factory pattern?

A: You can simplify your ImportPhotoby using pattern matching:
public void ImportPhoto(photoBase photo)
{
    switch(photo)
    {
        case FilePhoto filePhoto:
            loader.Load(filePhoto);
            break;
        case ExternalPhoto externalPhoto:
            loader.Load(externalPhoto);
            break;
    }
}

But this is only syntactic sugar and doesn't solve your real problem. What might help is a abstract Load method in your base class:
public abstract class PhotoBase
{
    public string Path { get; set; }

    public abstract void Load();
}

You have to implement this method in your child classes. If you call the method, the correct implementation will be chosen.
Online demo: https://dotnetfiddle.net/LfkxBQ

A: Another approach would be to have an abstract method Load on PhotoBase, that's then implemented by each subclass:
public abstract class PhotoBase
{
    public string Path { get; set; }
    public abstract void Load();
}

public class FilePhoto : PhotoBase
{
    public override void Load()
    {
         // load from file system
    }
}

public class ExternalPhoto : PhotoBase
{
    public override void Load()
    {
        // load from path
    }
}

That way, you can simply call the Load method on a PhotoBase:
public class PhotoImporter
{
  public void ImportPhoto(PhotoBase photo)
  {
    photo.Load();
  }
}

The main advantage is that each subclass implements the Load method, and therefore you can add as many subclasses as you want, without worrying about forgetting to implement it.
The main drawback to this implementation is that the Load methods can't depend on other dependencies. So for example, if one day you need to load a photo from a database, you can't pass the DBContext.

A: Proper to way to implement it which will make code easy to maintain is as follows:
public abstract class PhotoBase
{
    public string Path { get; set; }
    public abstract void Load();  // Have a abtract method
}

public class FilePhoto : PhotoBase {
    public override void Load() { // Implement the abtract method
        Console.WriteLine("FilePhoto");
    }
}

public class ExternalPhoto : PhotoBase {
    public override void Load() { // // Implement the abtract method
        Console.WriteLine("ExternalPhoto");
    }
}

public class PhotoLoader
{
    private PhotoBase _PhotoBase;
    public PhotoLoader(PhotoBase photoBase) { // Resolved by Dependency Injection
        _PhotoBase = photoBase;
    }
    public void Load()
    {
        _PhotoBase.Load();
    }
}

public class PhotoImporter
{
    private PhotoLoader _photoLoader;

    public PhotoImporter(PhotoLoader photoLoader) // Resolved by Dependency Injection
    {
        _photoLoader = photoLoader;
    }

    public void ImportPhoto()
    {
        _photoLoader.Load();
    }
}

You need to have Dependency Injection define so that specified implementation will get resolved and appropriate 'Load' method will be invoked.
void Main()
{
    // Following dependency should be resolved by Dependency Injection
    PhotoBase filePhotoBase = new FilePhoto();
    PhotoLoader filePhotoLoader = new PhotoLoader(filePhotoBase);
    PhotoImporter  filePhotoImporter = new PhotoImporter(filePhotoLoader);

    PhotoBase externalPhotoBase = new ExternalPhoto();
    PhotoLoader externalPhotoLoader = new PhotoLoader(externalPhotoBase);
    PhotoImporter  externalPhotoImporter = new PhotoImporter(externalPhotoLoader);

    filePhotoImporter.ImportPhoto(); // Shows output 'FilePhoto'

    externalPhotoImporter.ImportPhoto(); // Shows output 'ExternalPhoto'
}

You can have as much implementation as you want, but you need to have proper instance of PhotoImporter by Dependency Injection. Everything else will work smoothly.

A: This is how I could do this:
public class PhotoImporter
{
    private PhotoLoader _photoLoader;

    public PhotoImporter(PhotoLoader photoLoader)
    {
        _photoLoader = photoLoader;
    }

    public void ImportPhoto(PhotoBase photo)
    {
        var childType = photo.GetType();
        dynamic childPhoto = Convert.ChangeType(photo, childType);
        _photoLoader.Load(childPhoto);
    }
}


text:
Q: Progress SQL : Convert Julian Date into datetime I working for a client who uses PROGRESS database SQL (i didn't knew this kind of database, so it's my first time that i work on it).
My problem it's all the dates are in Julian-date, and i want to convert them into datetime. But i haven't found any document or help online that deals with this.
The only document i found it's:
https://knowledgebase.progress.com/articles/Article/How-to-Obtain-a-Julian-Date-in-Progress
But i want to do exactly the opposite.
For example in postgresql:
select to_timestamp(column1::text,'J')
from table1

But on PROGRESS it's harder and there is less information and examples than the others databases on the web
Thank you in advance for your help

A: Character
In case your Julian date is stored in a field with the character data type, you can use instr to pull it apart and then reassemble it into a timestamp:
select
  -- my character field containing 92182.3966
   descr,
   -- get the year
    floor( cast( left( descr, instr( descr, '.' ) - 1 ) as integer ) / 1000 ) as 'year',
    -- get the day
   mod( cast( left( descr, instr( descr, '.' ) - 1 ) as integer ), 1000 ) as 'day',
   -- get the time
   cast(
    '0' + right( descr, length( descr ) - instr( descr, '.' ) + 1 )
      as float
   ) as 'time',
   -- combine all to timestamp
   cast(
      -- get first day of year
      cast(
        to_char(
            floor( cast( left( descr, instr( descr, '.' ) - 1 ) as integer ) / 1000 )
            + 1900  -- !!! beware
        )
        + '-01-01'
        as date
      )
      -- add days
      + mod( cast( left( descr, instr( descr, '.' ) - 1 ) as integer ), 1000 )

        as timestamp
     )
     -- add milliseconds
     + cast(
        cast(
        '0' + right( descr, length( descr ) - instr( descr, '.' ) + 1 )
        as float
    ) * 86400 * 1000
    as integer
   ) as 'timestamp'

from pub.ddcapp
where application = 'JULIAN'

This reports that the time is 1992-07-01 09:31:06.24 which is 1 second later than what your link states it was translated from.
Decimal
If on the other hand your field is a decimal, it is a lot simpler:
select
  -- my decimal field containing 92182.3966
   open_bal,
   -- get the year
    floor( open_bal / 1000 ) as 'year',
    -- get the day
   mod( open_bal, 1000 ) as 'day',
   -- get the time
    open_bal - floor( open_bal ) as 'time',

   -- combine all to timestamp
   cast(
      cast(
        to_char(
            floor( open_bal / 1000 )
            + 1900  -- !!!
        )
        + '-01-01'
        as date
      )
      + mod( open_bal, 1000 )
        as timestamp
    )
    + ( open_bal - floor( open_bal ) ) * 86400 * 1000
     as 'timestamp'

from pub.ledbal
where adm_nr = 0


text:
Q: Validation of a custom directive (I want to make it required) in AngularJs I have a problem with validating a custom directive in a form with AngularJS. The directive that I created is called switcher, and it's put inside a form, ChoixController form.
The code is like this :
    <form id="choixContext"  name="choixContext" ng-submit="choixController.save(choixContext)">
Choice of Devis
 <switcher name="choixDevis" id="choixDevis" grid="'grid-3-small-3-tiny-1'" values="choixContextContrat" model="codeChoix"/>

            Erreur !

<button type="submit">Submit</button>
    </form>

How can I do this ? I want the directive to be required. The user has to choose to click on the directive before submitting.
Here's the HTML code of the directive :

        <input name="{{name}}" type="radio" value="{{item.code}}" ng-model="$parent.model">

        <input id="{{otherRadioId}}" name="{{name}}" type="radio" value="{{otherRadioValue}}" ng-model="$parent.model">

A: AS far as i know angular form will only add input select textarea to his validity system.
An easy way to get around this is to create an hidden input :
<input name="monChoix" type="hidden" ng-model="codeChoix" required />

        Erreur !

Also note that it's the input's name that must match in your ng-messages not the variable name where you store the value. THis is why i renamed it to monChoix so you'll see the link better.

A: A better option is use ng-message. And next you need do this on <switcher />:

*

*change model for ng-model

*add attribute required

Next, you need add ng-messages:

You did not enter a field

For more information:
https://docs.angularjs.org/api/ngMessages/directive/ngMessages
If you need more help, please, make a plunker.


text:
Q: jquery validation max not working Jquery validation max does not seem to work when I input the a number and its first digit is less than the first digit of the max
Example:
 $("#formPaymentModal").validate({
        rules: {
            payment: {
                digits: true,
                min: 1,
                max: 400
            }
        }
 });

When I type 1000, 2000, 3000+, there are no errors. but when I type 4000, 5000 and so on an error shows up.
Here's the HTML: I'm using Laravel

           Payment

                    ₱
                    {{ Form::text('payment', '', array('class' => 'form-control', 'id' => 'payment', 'placeholder' => '', 'required')); }}

A: i have created example for you on jsfiddle:-
$("#myform").validate({
    rules: {
        field: {
            required: true,

            digits: true,
            min: 1,
            max: 400
        }
    }
});

click here:http://jsfiddle.net/TnbYm/18/
thanks


text:
Q: Error Handling Selenium Python Automation I am creating an automation script with Selenium Python to be able to create user accounts on a website my company uses. The program pulls all the users information from active directory and passes the information through selenium to create the account. If a duplicate account is created the website throws an error. When it does this I am wanting selenium to recognize the error and add a number to the end of the username if it does not throw an error I want it to ignore and continue. I am trying to do this with a IF ELSE statement. The problem I am running in to is the HTML element that holds the error is always visible with only a small change in the HTML when the error is initialized. I tried writing the XPATH to catch the change but keep getting a TimeoutException error. I have added all of the script below along with both HTML elements showing before the error is thrown and after the error is thrown. If you have any suggestions on a better way to handle the error that will be greatly appreciated as well.
HTML of Error before being thrown

        <button class="close" ng-click="clearErrors()"></button>

Sorry, something unexpected happened. Please try again.

HTML of Error after being thrown

        <button class="close" ng-click="clearErrors()"></button>

Sorry, something unexpected happened. Please try again.

Code: 102000890

FaultCode: InvalidData

Error: 102000890 - Login Id is already in use. Please create a different login Id.

Details:

Full Script
import time
from hashlib import new
from multiprocessing.connection import wait
from select import select
from webbrowser import BaseBrowser, Chrome
from xml.etree.ElementPath import find

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait

import ADTest

driver = webdriver.Chrome()
driver.get('https://power.dat.com')

# chrome_optinons = webdriver.ChromeOptions()
# chrome_optinons.add_argument('--headless')
# chrome_optinons.add_argument('window-size=1920x1080')

#setup wait
wait = WebDriverWait(driver, 10)

username = driver.find_element(By.XPATH, '//*[@id="mat-input-1"]')
username.send_keys('')

password = driver.find_element(By.XPATH, '//*[@id="mat-input-0"]')
password.send_keys('')

loginbutton = driver.find_element(By.XPATH, '//*[@id="submit-button"]')
loginbutton.click()

(time.sleep(2))

profiledrop = driver.find_element(By.XPATH, '//*[@id="user-salutation"]')
profiledrop.click()

#store original window ID
windows_before = driver.current_window_handle

# #checks no other windows open
# assert len(driver.window_handles) == 1

Adminbutton = driver.find_element(By.CSS_SELECTOR, '#userPreferencesUl > li:nth-child(5) > a')
Adminbutton.click()

# driver.switch_to.window(driver.window_handles[1])

#Wait for new window Tab
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))

windows_after = driver.window_handles

new_window = [x for x in windows_after if x != windows_before][0]

driver.switch_to.window(new_window)

#Tells program to wait till new window confirmed
WebDriverWait(driver,20).until(EC.title_is("Admin"))

(time.sleep(5))

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.newUser.ng-scope[ng-if^='isTrustedAdmin'][ng-click^='onNewUser']"))).click()
#NewUsrBtn.click()

#User Name
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-pattern ng-valid-maxlength' and @name='loginId']"))).send_keys("TQL" + ADTest.DatUsrName)
#UsrNM.send_keys('justin')

#<input ng-required="true" ng-readonly="!hasPriviledgeToEdit(user)" ng-model="user.loginId" ng-pattern="/^[a-zA-Z0-9_]+$/" name="loginId" maxlength="16" class="ng-valid-pattern ng-valid-maxlength ng-dirty ng-valid-parse ng-valid ng-valid-required ng-touched" required="required">
#Password
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-pattern ng-valid-maxlength' and @name='password']"))).send_keys("total2")

#Confirm Password
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='confirmPassword']")))
element.send_keys("total2")
#State
state = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@class='ng-pristine ng-untouched ng-invalid ng-invalid-required' and @name='state']")))
selectState = Select(state)
selectState.select_by_value('string:' + ADTest.DATST)

#First Name
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-maxlength' and @name='firstName']"))).send_keys(ADTest.FirstN)

#Last Name
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-maxlength' and @name='lastName']"))).send_keys(ADTest.LastN)

#Workgroup ID
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-maxlength' and @name='initials']"))).send_keys(ADTest.DATint)

#Phone Number
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-pattern ng-valid-maxlength' and @name='primaryPhone']"))).send_keys("8005803101")

#Extension
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-untouched ng-valid ng-valid-pattern ng-valid-maxlength' and @name='primaryExtension']"))).send_keys(ADTest.ext)

#Email
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-untouched ng-valid-email ng-invalid ng-invalid-required ng-valid-maxlength' and @name='email']"))).send_keys(ADTest.email)

#National Account: Combo Premium Pooling Subscription
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[contains(text(),'National Account: Combo Premium Pooling Subscripti')]"))).click()

#National Account: Combo Premium Pooling Subscription
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[normalize-space()='National Account: DAT Connexion Subscription']"))).click()

#National Account: Combo Premium Pooling Subscription
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[normalize-space()='National Account: Power Broker Subscription']"))).click()

#Submit Button
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()

if WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@class= "error-section" and @id="data"]/div[1]'))):
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="data"]/div[3]/table/tbody[1]/tr/td[1]/ng-form/fieldset[1]/input'))).send_keys("1")

    # WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="data"]/div[3]/table/tbody[1]/tr/td[1]/ng-form/fieldset[1]/input'))).send_keys("1")
    # WebDriverWait(driver,20).until(EC.element_to_be_clickable(By.XPATH, '//*[@id="data"]/div[1]/button')).click()
else:
    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@class= "error-section ng-hide" and @id="data"]/div[1]')))

A: Instead of using presence_of_element_located expected condition you can use presence_of_all_elements_located so in case of no match found it will just return you an empty list interpreted by Python as a Boolean false. Also, seems you do not need to use WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@class= "error-section ng-hide" and @id="data"]/div[1]'))) in the else part since you already checked the existence of the error notification.
So, your code could be as following:
if WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class= "error-section"]//p[contains(.,"Sorry, something unexpected happened. Please try again.")]'))):
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="data"]/div[3]/table/tbody[1]/tr/td[1]/ng-form/fieldset[1]/input'))).send_keys("1")

else:
    # Do what you need to do here

Also, most locators you are using here, like //input[@class='ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-maxlength' and @name='lastName'] are bad and should be improved.

A: To handle the probable error message you can wrapup the click on the Close button within a try-except{} block inducing WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

*

*Using CSS_SELECTOR:
try:
  WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.close[ng-click^='clearErrors']"))).click()
  print("Closed error message")
except TimeoutException:
  print("No error message")

*Using XPATH:
try:
  WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='close' and starts-with(@ng-click, 'clearErrors')]"))).click()
  print("Closed error message")
except TimeoutException:
  print("No error message")


text:
Q: Executing stored procedure from sql developer vs executing from database server We are monitoring the performance of a stored procedure for experimental purpose.
This stored procedure read a single table and updates 5 table. While monitoring, I was expecting it to use network traffic. But to my surprise there were no network traffic.
The SQL developer is on my local machine. My assumption is it would use client service to connect to database and run the stored procedure on the database.
Kindly confirm my understanding and provide additional details.
Thanks.

A: Two things to consider...

*

*You mentioned that SQL Developer is on your local machine.  Is the database there too?

*SQL Server by default uses port 1433.  Are you watching that port?

*As commented below, If you're using Oracle, check port 1521.

*If you are using Oracle and TNS, check tnsnames.ora file to see if a port is specified there.


text:
Q: Evaluate the triple integral of $f(x,y,z)=\sin(x^2+y^2)$ Evaluate the triple integral of
$$f(x,y,z)=\sin(x^2+y^2)$$
over the the solid cylinder with height $4$ and with base of radius $1$ centered on the $z$-axis at $z=−3$.

A: In this case, the integral only depends on the cylindrical radial coordinate, so it easily becomes a single integral:
$$2 \pi 4 \int_0^1 dr \,r \sin{r^2} = 4 \pi \int_0^1 du \: \sin{u} = 4 \pi (1-\cos{1}) $$


text:
Q: Robustness vs Correctness Competition Reading "Code Complete 2" in a Quality of Requirements paragraph I found this:

Are acceptable trade-offs between competing attributes specified — for
  example, between robustness and correctness?

(this above is a point of a large checkbox list in order to check the quality of the requirements)
So, I found a lot of definitions of Robustness and Correctness, in the web, academic books, etc..
e.g. :
In the "Object Oriented Software Construction, 2nd Edition, Bertrand Meyer, Prentice-Hall, 1997" book:

*

*Correctness: The degree to which a system is free from [defects] in its specification, design, and implementation.

*Robustness: The degree to which a system continues to function in the presence of invalid inputs or stressful environmental conditions.

Despite this, it's not clear why and in which situations these two might be in conflict.
My question is: why are these two attributes in competition?

A: A practical example is XHTML vs. HTML.

*

*Browsers (in strict mode) reject XHTML that has syntax errors. This ensures that incorrect results are not displayed to the user, and aids in finding the errors.

*Browsers attempt to continue parsing HTML code even if it has very obvious problems. This often lets the user view the page, even if the contents are mangled a bit.

Thus XHTML aims for correctness, while HTML aims for robustness. Currently HTML seems more popular, but both sides have good arguments.

A: There are many situations in which these two might be in conflict. For instance, robustness can involve resilience under heavy load. If an approximate (i.e., incorrect) response to a request can be computed much faster than an exact (correct) response, it's important to know whether the system should deliver an approximate result, or fail delivering altogether.

A: These two are just examples as you said. In fact, all non-functional requirments of that sort can potentially conflict with each other. In the book "Building Evolutionary Architectures" there is a table of roughly a hundred of these "-ilities" (as they are also often called).
It is sort of an exercise for software architects to consider the potential conflict between any two of these. You can basically decide on which of these are important to your projects, then keep track of these conflicts.
To get back to your precise example and take a look at the definition of the term robustness in Wikipedia:

In computer science, robustness is the ability of a computer system to cope with errors during execution[1][2] and cope with erroneous input.

As you can see from the definition, robustness involves errors. On the other hand, you want to have correctness, which basically means the absence of errors.
To make the conflict more apparent, let's consider a simple input field. From the correctness requirement it's easiest for any erroneous input made by the user to be rejected. But robustness requires you to be able to work with this input, which may not be entirely correct.
To bring it all around to your book: what is the acceptable trade-off now? Let's say you write a scientific application in which the user can input a voltage amount, including the magnitude. So correct inputs would be something like "10 kV" or "200 mV". Acceptable trade-offs may include allowing inputs like "10kV", "10kVolt", or even just "10" and for the sake of correctness map these to a valid voltage value. Note that this is still a trade-off and not a "best-of-both-worlds" thing. Consider upper-case vs lower-case: "10 kV" and "10 KV" might be fine, but "10 mV" and "10 MV" may not be. Correctness becomes questionable as you are not sure if it's milli or mega now, but if you insist on the right upper/lower-casing you lose out on robustness again, because some erroneous inputs won't work.


text:
Q: Ruby: =~ symbol - what does it mean What does =~ in ruby mean?
I tried to get help on codementor.io recently and the change made to this tutorial:
http://sourcey.com/rails-4-omniauth-using-devise-with-twitter-facebook-and-linkedin/
was to replace this line:
self.email && self.email !~ TEMP_EMAIL_REGEX

with this line:
self.email && TEMP_EMAIL_REGEX =~ self.email

What does =~ mean?


text:
Q: When are referenced Assemblies loaded? I wrote a program that makes a reference to Microsoft.Web.Administration.dll,
which is not present on Windows Server 2003.
The program checks for the os and does not reference the dll if the os is 2003.
if(OSVersion == WindowsServer2003)
    //do the job without referencing the Microsoft.Web.Administration.

else if(OSVersion == WindowsServer2008)
   //reference the Microsoft.Web.Administration.dll file.

When I tested this program on Windows Server 2003, an error occured telling me it couldn't locate the Microsoft.Web.Administration.dll.
But when I separated the if-else block into 2 different methods as below, and the error did not occur.
if(OSVersion == WindowsServer2003)
   //do the job without referencing the Microsoft.Web.Administration.

else if(OSVersion == WindowsServer2008)
   //DoIt2008Style();

So I wanted to know about reference file loading time in more detail.
could you point me to some resources?

A: When you enter a method that references a type in another assembly. Here is an example when trying to delay load x86 and x64 assemblies.


text:
Q: How to set Layout properly when using Transitions on Android I am playing with Transitions on Android. I believe I am setting my layout wrong.
First, when you arrive I have this kind of layout:

Everything is extended from View class.
For now I don't put the code, it is 300 lines.
Then, when you click on a circle, the given elements (the orange one for example) goes to the top of the screen, using animations:

Every other shape goes off the screen, and the circle goes to the left.
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:transitionOrdering="together">

<slide android:duration="2000" android:slideEdge="start">
    <targets>
        <target android:targetId="@id/relativeFragmentBLUE" />
    </targets>
</slide>

<slide android:duration="2000" android:slideEdge="end">
    <targets>
        <target android:targetId="@id/relativeFragmentGREEN" />
        <target android:targetId="@id/relativeFragmentRED" />
    </targets>
</slide>

<changeBounds android:duration="2000">
    <targets>
        <target android:targetId="@id/relativeFragmentORANGE" />
        <target android:targetId="@id/circleORANGE" />
    </targets>
</changeBounds>

</transitionSet>

The result scene is here:

But Animations are not really working.
When I go back from any scene to the Menu, it work perfectly!
1) To get Transition working nicely, the "orange scene layout" has all the other shapes defined, set to invisible. Is it what I'm supposed to do?
2) There are many layouts inside layouts inside layouts (like 8 times). I believe stacking many layouts are breaking the Transitions?
3) To make this work, I had to set empty blocks, and stack 2 layouts. This is where I fail. How can u make a layout like that? (I'm using weight and alignParent, it works but maybe not done well.)

4) I made an animation on the circles before starting the Transition, but it doesn't execute. I believe you can't stack an Animation and a Transition? (even with startDelay)
I repeat, the Transitions are perfect from any scene to the Menu.
So the problems comes from my scenes layouts.

A: Problem solved.
First i made a different layout file for each colors, to make it clear.
Then i had to set clipChildren to false. (allows children layouts to go outside their parents bounds)
i used an empty RootScene.To finish, i made two different TransitionSet for each colors (in & out)
Its works fine now, but I would like to create 10 layouts and 8 Transitions for one activity.


text:
Q: how to resolve race conditions in webdriver I have an app that uses a mixture of angular and asp.net. My issue is that the home page is redirected by setting window.location and then the required data and page is requested form the server.
Previously this was not the case and all routing was done via the angular app. However due to requirements the applications routing had to be changed to what it is now.
Now because the application requires a server side request/response (I believe) this is causing a race condition in my tests as I only receive the expected result once in every 5 tests.
At present I am not able to provide code to explain my situation. However, I will be albe to provide some code in a edit later today.
The only code I can provide for now would be the test that is being run. Although I do not believe this would help without the code running the application.

A: Recent frameworks have this feature where it sets the document.readState of browser to complete and the content is loaded afterwards. Due to this the test may fails as we will be expecting an element to be present.
For such conditions you have to use explicit wait for the element to be present for which you want to take an action after the page is loaded or changed.

A: Here is an example how we wait for elements in our project (The application is also angularjs, we use Java for webdriver):
In our Webdriver implementation we added:
private WebDriverWait iWait(int timeoutInSeconds) {
    return new WebDriverWait(webDriver, timeoutInSeconds);
}

we want to wait for an element to be visible ("Visibility means that the element is not only displayed but also has a height and width that is greater than 0"):
public void waitForElementToAppear(By by, int timeoutInSeconds) {
    iWait(timeoutInSeconds).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.visibilityOfElementLocated(by));
}

the ExpectedConditions class provides many other out of the box condition, here are some:

*

*elementToBeClickable

*textToBePresentInElement

*titleContains

*elementSelectionStateToBe

for more, please look at the ExpectedConditions Javadoc
if you need to create your own conditions, you can use ExoectedCondition (no 's') class
ExpectedCondition Javadoc


text:
Q: reliable/robust way for error handling while re-loading firewall rules using iptables/ipfilter I need a robust/reliable/elegant way to handle any error conditions while re-loading firewall rules, some background:

*

*our servers are using whitelist mechanism, which means there should be a large volume of rules if some server need to talk many different destinations.

*we have another tool to generate a firewall rule file, which will feed to iptables/ipfilter, with very rare chance that the file may be malformed.

*since the firewall rule number could be very huge, iptables/ipfilter may fail to load the firewall rule file due to resource limitation on some of our legacy hardware, for example, the memory may be not enough under some cases while reloading more then 20k rules altogether.

so my questions are:

*

*Are there any existing tools that can be used to check the syntax of the firewall rules before actually loading them?

*Are there any ways to make the reloading process atomic, say, it either reloads the new rules successfully or just reserve the previous healthy rule set?

*How can we make sure given the current running environment and the rule set, the reloading will be sure to success? Or are there any tools to give me some estimation that the reload is likely to success/fail?
Any suggestions are warmly welcome. Thanks in advance.

A: It's been said that iptables-restore is atomic. I cannot confirm that, but assuming that were true, then it would seems like a sensible approach.

*

*On a test machine, flush all rules then apply your generated rules to validate them.

*Once validated, use iptables-save to dump out the rule-set.
[root@testmachine]$ iptables-save > new_rules.iptables

*Double check the rule-set on your production machine using iptables-restore -t:
[root@production]$ iptables-restore --test < new_rules.iptables

*Load in the new rule-set on your production machine.
[root@production]$ iptables-restore < new_rules.iptables


text:
Q: strip html of each child element let say i have dirty html like so...
let dirty = `

    pre tag with html

    another pre tag with html

`

i need to strip html from each child of pre tag...
im doing this...
let $ = cheerio.load(dirty)
$('pre').each(function() {
    let text = $(this).text()
    console.warn(text) // html are stripped
    return `<pre>${text}</pre>`
});
console.log($.html()) // html are not stripped

what i missed..??

A: Firstly, note that while you technically can delimit multi-line strings with backticks, it's completely unsupported in IE, so cannot reliably be used. You need to use quotes (') or double quotes (") instead.
The issue with your logic is that you define the text varaiable in the each loop, but do nothing with it, as returning from each() is redundant.
To fix the problem you can simply use the text() method to strip out any child HTML from the given element. Try this:

let dirty = '
pre tag with html

another pre tag with html
';

$('body').append(dirty);
$('pre').text(function(i, t) {
  return t;
});

A:

$('pre').each(function() {
    let text = $(this).text()
    // You need to inject cleaned string into the DOM
    $(this).html(text)
});

console.log($('div').html())

    pre tag with html

    another pre tag with html

A: You need to actually assign the new html, right now you don't set the html to something else. Below will work
const cheerio = require("cheerio");
let dirty = `

    pre tag with html

    another pre tag with html

`;
let $ = cheerio.load(dirty);
$("pre").each(function() {
    $(this).html($(this).text());
});
console.log($.html());


text:
Q: bpopup jQuery is not working I'm trying to use one of bpopup examples in my xhtml page, and I have tried everything I can think of but it's not working.
bpopup (jQuery plugin),code example
here is my try so far..
HTML:

<h:head>
<title>Calendar</title>

  <link rel="stylesheet" href="http://dinbror.dk/bpopup/assets/style.min.css" media="screen" type="text/css"/>

</h:head>
<h:body>

        <button id="#my-button">POP IT UP</button>

Content of popup

</h:body>

js:
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {

 // DOM Ready
$(function() {

    // Binding a click event
    // From jQuery v.1.7.0 use .on() instead of .bind()
    $('#my-button').bind('click', function(e) {

        // Prevents the default action to be triggered.
        e.preventDefault();

        // Triggering bPopup when click event is fired
        $('#element_to_pop_up').bPopup({
    content:'iframe', //'ajax', 'iframe' or 'image'
    contentContainer:'.content',
    loadUrl:'http://dinbror.dk/search' //Uses jQuery.load()
});

    });

});

})(jQuery);

Any help will be appreciated!

A: Found it!
I just deleted # in button id  and in element_to_pop_up

        <button id="my-button">POP IT UP</button

 hello

and use this css file instead :
 #element_to_pop_up, .bMulti {
background-color: #FFF;
border-radius: 10px 10px 10px 10px;
box-shadow: 0 0 25px 5px #999;
color: #111;
display: none;
min-width: 450px;
min-height: 250px;
padding: 25px;
}

#element_to_pop_up .logo {
color: #2B91AF;
font: bold 325% 'Petrona',sans;
}

.button.b-close, .button.bClose {
border-radius: 7px 7px 7px 7px;
box-shadow: none;
font: bold 131% sans-serif;
padding: 0 6px 2px;
position: absolute;
right: -7px;
top: -7px;
 }

.button {
background-color: #2B91AF;
border-radius: 10px;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.3);
color: #FFF;
cursor: pointer;
display: inline-block;
padding: 10px 20px;
text-align: center;
text-decoration: none;
}


text:
Q: Neo4j 2.1.2: Unable to delete nodes using Cypher query that worked with Neo4j 2.0.1 I recently upgraded to Neo4j 2.1.2 from Neo4j 2.0.1 and started receiving a new error when attempting to delete nodes.
This code works in 2.0.1 to delete a node that is connecting two other nodes and replaces it with a bidirectional relationship.
MATCH (a:node {id: 1})
WITH a

MATCH (b1:node)-[:rel]->(a)<-[:rel]-(b2:node)
CREATE UNIQUE (b1)-[:rel]->(b2), (b2)-[:rel]->(b1)
WITH a

OPTIONAL MATCH (a)-[r]-()
DELETE a, r

But produces the following error in 2.1.2:
{Code:"Neo.DatabaseError.Statement.ExecutionFailure", Message:"Node 4746 has been deleted"}

I tried changing it to this:
MATCH (b1:node)-[r1:rel]->(a)<-[r2:rel]-(b2:node)
CREATE UNIQUE (b1)-[:rel]->(b2), (b2)-[:rel]->(b1)
DELETE r1, r2, a

But am still receiving the same error message. I also tried putting the DELETE within a different statement within the same transaction and that failed as well. I checked the Cypher for all the statements within the transaction and a, r1 and r2 are never accessed again post the delete. Removing the DELETE in this statement causes the transaction to succeed.
What's the right way to delete nodes as part of a transaction?
UPDATE
I can't get a solid repro of this bug but there is definitely something wrong. Everything will be working fine and then suddenly I will start getting error messages about Nodes being deleted or relationships not being found.
I've narrowed it down to the following query:
  MATCH (a:activity {id: { param0 } }), (i:file {id: { param1 } })
  CREATE (i)-[:HISTORY {id: i.id}]->(a)
  WITH a, i

  MATCH (i)-[r:HISTORY {id: i.id}]->(ph:activity)
  WHERE ph.id <> a.id
  CREATE (a)-[:HISTORY {id: i.id}]->(ph)
  DELETE r

I issue this as part of a larger transaction, but removing the DELETE r results in the error messages never being produced. Otherwise I randomly get:
ErrorCode: "",
Raw:       &errors.errorString{s:"Neo4j returned Unable to load RELATIONSHIP with id 2397. ( Neo.ClientError.Statement.EntityNotFound)"},
The odd part is that the transaction succeeds and is not rolled back even though it produces an error. At this point I believe that it is a timing issue and that's why I can't get a solid repro for it. Is there additional debugging that I can enable to help track down the problem when it occurs?


text:
Q: Gmail API - How to set from name (PHP) I need to set From name on GMAIL API.
When i use the following condition client receives only the first name before "@";
$message = $serviceGmail->users_messages->send('me', $message);

Eg.: If my mail is test@email.com, the mailbox receive on "from name" only "test"
I already setted on smtpmailer fromName but it does not work.

A: Try using your email address instead of 'me'. That'll fix it.


text:
Q: ConcurrentDictionary with "expensive" value I have a multi-threaded application that implements async methods. The application communicates over RabbitMq and at times needs to do a costly operation (BasicConsume on an IModel). I have a ConcurrentDictionary where I keep IModel (key) and it's IBasicConsumer (value) in order to avoid additional round-trips to the message broker.
On start-up, multiple executions reach the same section of the code where it looks if the consumer (value) exists. In the first ~40 cases the answer is no, but I don't want to do 40 BasicConsume, only one or perhaps two depending on the IModel (key) provided.
Using a lock statement introduces a performance hit that is not acceptable.
Currently, I'm solving the problem as follows
var consumerTcs = new TaskCompletionSouce<IBasicConsumer>();
if (_consumerDictionary.TryAdd(channel, consumerTcs))
{
    var newConsumer = new EventingBasicConsumer(channel);
    newConsumer.Model.BasicConsume(queue, false, newConsumer)
    consumerTcs.TrySetResult(newConsumer);
    return consumerTcs.Task;
}
else
{
    return _consumerDictionary[channel].Task;
}

That is

*

*Use a TaskCompletionSource (non-expencive) as the value of the dictionary

*Use TryAdd, and if successful do the expensive operation

*If unsuccessful, assume that the key exists and return the TaskCompletionSource.Task
However, I still create TaskCompletionSources that I don't use, which feels a bit ugly to me. Any suggestions to how I might solve this problem without the performance hit of a lock and without wasting clock cycles on creating objects that is not used?


text:
Q: How to parse the content from response using Gist API? I am trying to display some data in my application that I am fetching from the Github Gist API. I am getting a response, but I cannot access below a certain level of my response object. How do I access the "content" under "forgeLikeServerSetup.md"?
Here is my fetch function:
fetch('https://api.github.com/gists/53e1780a5a68fe9281cfbbc9820d381f')
  .then(results => {
    return results.json();
  })
  .then(data => {
    console.log(data.files);
  });

And here is my response:
{
  "url": "see_above",
  "forks_url": "https://api.github.com/gists/53e1780a5a68fe9281cfbbc9820d381f/forks",
  "commits_url": "https://api.github.com/gists/53e1780a5a68fe9281cfbbc9820d381f/commits",
  "id": "53e1780a5a68fe9281cfbbc9820d381f",
  "git_pull_url": "https://gist.github.com/53e1780a5a68fe9281cfbbc9820d381f.git",
  "git_push_url": "https://gist.github.com/53e1780a5a68fe9281cfbbc9820d381f.git",
  "html_url": "https://gist.github.com/53e1780a5a68fe9281cfbbc9820d381f",
  "files": {
    "forgeLikeServerSetup.md": {
      "filename": "forgeLikeServerSetup.md",
      "type": "text/plain",
      "language": "Markdown",
      "raw_url": "https://gist.githubusercontent.com/m1guelpf/53e1780a5a68fe9281cfbbc9820d381f/raw/a74da413bd8ad348523b4535053687533cc10485/forgeLikeServerSetup.md",
      "size": 7434,
      "truncated": false,
      "content": "### Let's Log in!\n- Create ssh pair for login on a fresh DO droplet.\n- ssh into the server\n- `apt-get update` It updates server's knowledgeable packages. Not technically updates any software.\n\n### Alright, let's start installing our stuff boys!\n- `apt-get install -y git tmux vim curl wget zip unzip htop` -y flag to say yes to all prompts\n- Adding additional repositories so that we can get latest version of the softwares from this respective repositories of them:\n- For NGINX: `add-apt-repository -y ppa:nginx/development` (Development branch of nginx repo is actually what they consider stable because its stable + bug-fixes, its not exactly the dev branch)\n- For PHP: `add-apt-repository -y ppa:ondrej/php`\n- Now after adding the repos we need to tell the server to suck in & update its cache of available packages: `apt-get update`\n- `apt-get install -y nginx`\n- `curl localhost` , also we can type in the IP in the browser & confirm the nginx default landing page shows up\n- `apt-get install -y php7.1-fpm php7.1-cli php7.1-mcrypt php7.1-gd php7.1-mysql php7.1-pgsql php7.1-imap php7.1-memcached php7.1-mbstring php7.1-xml php7.1-curl php7.1-bcmath php7.1-sqlite3 php7.1-xdebug`\n- `ps aux | grep php` To check the php fpm process is running\n- `php -v` to check we got the latest PHP installed\n- Install Composer: `php -r \"readfile('http://getcomposer.org/installer');\" | sudo php -- --install-dir=/usr/bin/ --filename=composer`\n- `which composer` to check it was installed in the given directory.\n- `composer -v` to check composer is working\n\n### Let's get NGINX configured to use PHP\n- `cd /var/www/html/`\n- `vim index.php` Just dump phpinfo() in that file for time being\n- Hit IP/index.php in the browser. It will download the file at this moment because PHP isn't working\n- `cd /etc/nginx/`\n- `sites-available` has all the configurations. `sites-enabled` have the symlinks to the configs in the `sites-available` which we want to be enabled.\n- `sudo vim sites-enabled/default`\n- Configure the server block in that default file. To get a basic understanding of the default file watch [this part of the video](https://youtu.be/VQNrsMYCOFg?t=13m43s) again.\n- `sudo nginx -t` To test the nginx config and show errors if any\n- `sudo service nginx configtest` will ONLY tell you if things are ok or not. So the previous one is better \n- `sudo service nginx reload`\n- Refresh the IP in the browser & now you should see the output of the phpinfo() from our index.php file\n- Done!\n\n### Making a Laravel app\n- `cd /var/www`\n- `composer create-project laravel/laravel:dev-develop myapp` dev-develop will pull in the latest under development unreleased laravel version\n- `sudo vim /etc/nginx/sites-available/default`\n- Change the root to the new laravel app's public directory path like in this case: `root /var/www/myapp/public;`\n- `nginx -t`\n- `sudo service nginx reload`\n- cd into myapp/public directory\n- Refresh browser and you will see the permission denied to write into the log file.\n- If we do `ps aux | grep php` we see that the \"php-fpm\" which is running our web requests, which is running our php is owned by user & group `www-data`.\n- That means this processes of php are running as user `www-data`\n- But if you run `ll` you will see that all the files in our app/public directory (in which we currently are) are owned by user `root`\n- So the `www-data` cannot write into the storage directory & the bootstrap/cache directory as they are owned by user & group `root` which in a laravel app should be writable by the `www-data`\n- To solve this do the following:\n- `cd ..` so we are out of the public directory\n- Then run `sudo chown -R www-data: storage/ bootstrap/`\n- Solved!\n\n### Wait Bro!\n- But now we will probably be pushing our code as some user so the permissions will again override for the storage & bootstrap directory\n- What Forge does is it uses PHP as user forge and uploads/pushes the code as user forge as well so the permissions remain at level\n- So let's do that!\n\n### Solving the above problem (wow what a heading! I know, thanks.)\n- `cd ~`\n- `adduser forge`\n- Enter the password for the user forge\n- `ll /home/`\n- A directory called `forge` have been created in the home directory for the user forge we just created\n- `cd ~`\n- `cd /var/www`\n- `mv myapp/ /home/forge/` We moved this application into the user forge's home directory\n- `cd /home/forge/`\n- `ll`\n- `chown -R forge: myapp/`\n- So now our web root is `/home/forge/myapp/public`\n- So lets edit the nginx config to replace the above path as the root\n- `vim /etc/nginx/sites-available/default`\n- Update the root directive\n\n- WAIT! PHP & NGINX ARE RUNNING AS `www-data` BUT ALL THE FILES & DIRECTORIES IN OUR myapp/ directory ARE OWNED BY USER `forge`. So....again the same problem, Laravel could not write to the storage directory and so in the browser we again get the 'permission denied' error.\n- So instead to change to files get owned by `www-data` it makes sense to change PHP to change what user PHP would run as.\n- `cd /etc/php/7.1/fpm/`\n- `cd pool.d/`\n- `vim www.conf` This file determines how PHP-fpm runs & how it manages the processes like how many processes it spins up to handle requests.\n- In the file there will be:\nuser = www-data\ngroup = www-data\n- Change both to forge\n- `:wq`\n- `sudo service php7.1-fpm reload`\n- `ps aux | grep php` to check the php-fpm is now running as user & group `forge`\n- So now the permissions line up as both our code & PHP are running as user & group `forge`.\n- Refresh the browser & you will see the laravel landing page.\n- Good Job Chris!\n\n### Allowing user forge to use sudo\n- `usermod -aG sudo forge`\n- We can check it worked by running `groups forge`\n- Now everytime we push our code and since we will be pushing code from the user forge we need to sudo php fpm reload. But that will everytime ask for the user forge's password.\n- So we want to make sure that for only that command we do not have to enter the password\n- `visudo -f /etc/sudoers.d/php-fpm`\n- Add the following in it:\n`forge ALL=NOPASSWD: /usr/sbin/service php7.1-fpm reload`\n- This means \"user forge from all/any host can run sudo commands with No password but only the following commands\" that is the commands after the colon.\n- Let's test this!\n- Exit to clear the cached password & login back\n- `sudo su forge`\n- Run `sudo service php7.1-fpm reload`\n- And voila! It didn't asked for the password. So now we have 1 less barrier in our goal of automated deployment.\n\n> **We reload php-fpm mainly to clear the opcache so our new code is reflected. Even if we not have opcache it's better to reload php-fpm as some php process might be stuck in the old code might be, not sure! so it's a good practice & doesn't hurts too**\n\n### Here comes the MySQL!\n- `sudo apt-get install -y mysql-server`\n- Enter the password for the new `root` user\n- **You can automate this without prompts. Chris has videos on how to do that on serversforhackers.com**\n- Check by running `sudo service mysql status`\n- `mysql_secure_installation`\n- Remove anonymous users\n- Disallow root logins remotely\n- Remove test databases\n- Reload privileges\n- login to mysql by: `mysql -u root -p`\n- `create database myapp charset utf8mb4`\n- `create user myuser@localhost identified by 'secret'`\n- `grant all privileges on myapp.* to myuser@localhost;`\n- `flush privileges;` to burst the privileges cache\n- exit;\n- Update the .env file in the laravel app and we are done!\n"
    }
  },
  "public": false,
  "created_at": "2017-07-13T19:01:10Z",
  "updated_at": "2017-07-13T19:01:10Z",
  "description": "Personally written version of Chris Fidao's video on setting up a Forge like server:  ",
  "comments": 0,
  "user": null,
  "comments_url": "comments_url",
  "owner": {
    "login": "m1guelpf",
    "id": 23558090,
    "avatar_url": "avatar,"
    "gravatar_id": "",
    "url": "url_test",
    "html_url": "h",
    "followers_url": "followers",
    "following_url": "/users/m1guelpf/following{/other_user}",
    "gists_url": "/m1guelpf/gists{/gist_id}",
    "starred_url": "/users/m1guelpf/starred{/owner}{/repo}",
    "subscriptions_url": "/m1guelpf/subscriptions",
    "organizations_url": "/m1guelpf/orgs",
    "repos_url": "users/m1guelpf/repos",
    "events_url": "/m1guelpf/events{/privacy}",
    "received_events_url": "/m1guelpf/received_events",
    "type": "User",
    "site_admin": false
  },
  "fork_of": null,
  "forks": [

  ],
  "truncated": false
}

What goes after data.files in my fetch function?

A: You can access that like this:
fetch('https://api.github.com/gists/53e1780a5a68fe9281cfbbc9820d381f')
  .then(results => {
    return results.json();
  })
  .then(data => {
    console.log(data.files["forgeLikeServerSetup.md"].content);
  });

It is slightly complicated by the fact that the title "forgeLikeServerSetup.md" includes a '.', so you have to use the bracket notation rather than the dot notation, but it works just the same.

A: This saves all(one or more) files in a particular gist.

const downloadGist = async (gistUrl) => {
  const response = await fetch(gistUrl);
  const data = await response.json();

  // Loop through files
  const fileNames = Object.keys(data.files);
  for (let i = 0; i < fileNames.length; i++) {
    var fileName = fileNames[i];
    var blob = new Blob([data.files[fileName].content]);
    saveBlob(blob, fileName);
  }
}

   const saveBlob = (blob, filename) => {
  var url = URL.createObjectURL(blob);
  var a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
   }

downloadGist('https://api.github.com/gists/53e1780a5a68fe9281cfbbc9820d381f')


text:
Q: Blockwise diagonal matrix inversion I have a blockwise-diagonal matrix (not sure how to call it). It basically has square blocks of non-zero elements on the diagonal, and zeros everywhere else. The matrix takes the following form:
$$
M = \begin{bmatrix}
M_1 & 0 & \dots & 0 \\
0 & M_2 & \dots & 0 \\
0 & 0 & \dots & M_n
\end{bmatrix}
$$
Now I know that the inverse of a general two by two blockwise matrix can be expressed like so:
$$
Z = \begin{bmatrix}
A & B \\
C & D
\end{bmatrix}
$$
$$
Z^{-1} = \begin{bmatrix}
(A-BD^{-1}C)^{-1} & -(A-BD^{-1}C)^{-1}BD^{-1} \\
-D^{-1}C(A-BD^{-1}C)^{-1} & D^{-1}+D^{-1}C(A-BD^{-1}C)^{-1}BD^{-1}
\end{bmatrix}
$$
If I replace B's and C's by 0, I get the following (to me logical) invert:
$$
Z^{-1} = \begin{bmatrix}
A^{-1} & 0 \\
0 & D^{-1}
\end{bmatrix}
$$
My question is, does this stand for a blockwise matrix that has more than two by two blocks? Is the following true?
$$
M^{-1} = \begin{bmatrix}
M_1^{-1} & 0 & \dots & 0 \\
0 & M_2^{-1} & \dots & 0 \\
0 & 0 & \dots & M_n^{-1}
\end{bmatrix}
$$

A: Hint: consider
$$ M = \pmatrix{ A & 0 & 0 \\ 0 & B & 0 \\ 0 & 0 & C} = \pmatrix{ \pmatrix{ A & 0 \\ 0 & B} & 0 \\ 0 & C}$$

A: I ended up figuring it out in the direction proposed by Bernard. Here's the development.
Given the matrix we are trying to invert, $M$, the product of this matrix by its invert should give an identity diagonal matrix, like so:
$$
M = \begin{bmatrix}
A_{11} & 0 & \dots & 0 \\
0 & A_{22} & \dots & 0 \\
\dots & \dots & \dots & \dots \\
0 & 0 & \dots & A_{nn} \\
\end{bmatrix}
$$
$$
MM^{-1}= \begin{bmatrix} I & 0 & \dots & 0 \\
0 & I & \dots & 0 \\
\dots & \dots & \dots & \dots \\
0 & 0 & \dots & I \\
\end{bmatrix}
$$.
If we assign block matrix variables to $M^{-1}$, we'll get a series of equation to solve:
$$
M^{-1} = \begin{bmatrix}
W_{11} & W_{12} & \dots & W_{1n} \\
W_{21} & W_{22} & \dots & W_{2n} \\
\dots & \dots & \dots & \dots \\
W_{n1} & W_{n2} & \dots & W_{nn} \\
\end{bmatrix}
$$
These equations essentially boil down to two forms, one items which will be on the diagonal of the resulting matrix (product of line=column=i):
$$
A_{1i}W_{i1} + A_{2i}W_{i2} + \dots + A_{ni}W_{in} = I \\
A_{ii}W_{ii} = I \\
W_{ii} = A_{ii}^{-1}
$$
Since all $A_{ij}$ where $i \neq j$ is zero, we get the second line of the previous equation. The other form is items which will be off the diagonal, or the product of line i with column j:
$$
A_{1i}W_{j1} + A_{2i}W_{j2} + \dots + A_{ni}W_{jn} = 0 \\
A_{ii}W_{ji} = 0 \\
W_{ji} = 0
$$
So we end up with the desired form.