text:
Q: The "ListFormWebPart" Web Part appears to be causing a problem I have a list for events in which I have placed content editor web part in "NewForm.aspx", "EditForm.aspx" and "DispForm.aspx". to hide recurrence field using JavaScript
The field is hidden successfully using JavaScript but when I click on the event and click on View Event from ribbon the following error occurs:
The "ListFormWebPart" Web Part appears to be causing a problem
The JavaScript code in the above mentioned forms is as below:
<script type="text/javascript">
var TDs = document.getElementsByTagName("TD");
var i=0;
var tagContent = "";
while (i < TDs.length)
{
try
{
tagContent = TDs[i].innerText || TDs[i].textContent;
if (tagContent.indexOf("Recurrence") == 0 || tagContent.indexOf("Recurrence") == 3)
{
TDs[i+1].parentNode.removeChild(TDs[i+1]);
TDs[i].parentNode.removeChild(TDs[i]);
}
}
catch(err){}
i=i+1;
}
    </script>

One more thing I would like to clear is, when I manually go to the list's form it redirects me to the page, i.e. when I type URL of display form the page is redirected successfully.
What am I missing?

A: After searching the internet, I found an answer.
I had to increase the limit for resource throttling in Central Administration for my web application and after that it worked perfectly.


text:
Q: DeprecationWarning: distutils Version classes are deprecated while starting odoo15 on local I installed odoo 15 on my local and installed all the dependances, but when i start my server it shows me a py warning and i am unable to solve this issue, any help will be much appreciated, the warning i am getting in my local is below:

2022-01-11 10:26:54,032 8202 WARNING ? py.warnings:
/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/ir_actions_report.py:68:
DeprecationWarning: distutils Version classes are deprecated. Use
packaging.version instead.
File "core/odoo-bin", line 8, in
odoo.cli.main()   File "/home/itachi/Workspace/odoo_15/core/odoo/cli/command.py", line 61, in
main
o.run(args)
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/server.py", line 176, in
run
main(args)
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/server.py", line 170, in
main
rc = odoo.service.server.start(preload=preload, stop=stop)
File "/home/itachi/Workspace/odoo_15/core/odoo/service/server.py", line
1286, in start
load_server_wide_modules()
File "/home/itachi/Workspace/odoo_15/core/odoo/service/server.py", line
1196, in load_server_wide_modules
odoo.modules.module.load_openerp_module(m)
File "/home/itachi/Workspace/odoo_15/core/odoo/modules/module.py", line
396, in load_openerp_module
import('odoo.addons.' + module_name)
File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/init.py",
line 5, in
from . import models   File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/init.py",
line 13, in
from . import ir_actions_report
File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/ir_actions_report.py",
line 68, in
if LooseVersion(version) < LooseVersion('0.12.0'):
2022-01-11 10:26:54,033 8202 WARNING ? py.warnings:
/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/ir_actions_report.py:73:
DeprecationWarning: distutils Version classes are deprecated. Use
packaging.version instead.   File "core/odoo-bin", line 8, in
odoo.cli.main()
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/command.py", line 61, in
main
o.run(args)
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/server.py", line 176, in
run
main(args)
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/server.py", line 170, in
main
rc = odoo.service.server.start(preload=preload, stop=stop)
File "/home/itachi/Workspace/odoo_15/core/odoo/service/server.py", line
1286, in start
load_server_wide_modules()   File "/home/itachi/Workspace/odoo_15/core/odoo/service/server.py", line
1196, in load_server_wide_modules
odoo.modules.module.load_openerp_module(m)   File "/home/itachi/Workspace/odoo_15/core/odoo/modules/module.py", line
396, in load_openerp_module
import('odoo.addons.' + module_name)   File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/init.py",
line 5, in
from . import models   File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/init.py",
line 13, in
from . import ir_actions_report   File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/ir_actions_report.py",
line 73, in
if LooseVersion(version) >= LooseVersion('0.12.2'):
2022-01-11 10:26:54,154 8202 WARNING ? odoo.addons.base.models.res_currency: The
num2words python library is not installed, amount-to-text features
won't be fully available.  2022-01-11 10:26:54,181 8202 INFO ?
odoo.service.server: HTTP service (werkzeug) running on
Uchiha-Madara:8069

A: This issue has been fixed in this pull request and you need yo update your Odoo to latest version to fix it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: andengine tilemap respawn i'm starting to developt a android game using AndEngine gles2, it's a really good game engine and i found a lots of example of how use it. My game is a kind of RPG traditional game using tiled maps, sprite, etc.: my issue is how i can set a mounster respawn area(like the long grass areas on pokemon games) i read a lots of tile map example but in no one appears examples about this, i using a tiled map editor and there i can set properties to the layers and especify there if is a mounster respawn area or not, if can someone tell me how can i do this i will appreaciate so much.

A: Are you using the tilemapeditor found here:
http://www.mapeditor.org/
(note, you need to save it with the correct compression type or otherwise andengine will not parse it correctly, cant remember which one I got working but it takes a few minutes to try out).
Then you can rightclick on a specific tile and add properties to it such as:
IsMonsterSpawnArea value = true
Then you can check for "collision" with
if(pTMXTileProperties.containsTMXProperty("IsMonsterSpawnArea ", "true")) {
    // SPAWN BIG UGLY MONSTER(or initiate fight!)
}

Check out the andengine TMX examples found in the andengine source, they can really help you get started.


text:
Q: Python 2.7 to exe using py2exe issue I successfully created an .exe using py2exe with a simple test script I found on a tutorials website.  The script I am using, however, does not seem to work.  My code uses the csv module and dict reader with two .csv inputs.
I run the python setup.py p2exe command, and I get a flash of a command prompt, but that disappears before I can read anything on it.  And once it disappears, I do not have the correct .csv file output that I would get if I just ran the script in python.
Can anyone offer any advice or things to try?  Or is there a way I could get that pesky cmd window to stay open long enough for me to see what it says?
Thanks.  My script is below.
import csv

def main():
iFileName = 'DonorsPlayTesting.csv'
oFileName = iFileName[:-4] + '-Output' + iFileName[-4:]
iFile = csv.DictReader(open(iFileName))
oFile = csv.writer(open(oFileName, 'w'), lineterminator = '\n')

iDirectory = csv.DictReader(open("DonorsDirectory.csv"))
oNames = {}
directory = {}
for line in iDirectory:
   directory[line['Number']] = line['Name']

for key in directory.keys():
    oNames[directory[key]] = 0

out_header = ['Name', 'Plays']
oFile.writerow(out_header)

for line in iFile:
    if line['Type'] == "Test Completion":
        if line['Number'] in directory:
            oNames[directory[line['Number']]] += 1
        elif line['Number'] not in directory:
            oNames[line['Number']] = 'Need Name'

oFile.writerows(oNames.items())

main()


text:
Q: Lifecycle when calling the fragment replace or open new activity? The is an fragment that display the video.
This fragment can either
1) open a new activity on click button
2) replace with another fragment by calling
fragmentManager.beginTransaction().replace(R.id.container, f).addToBackStack(tag).commit();

for the 1) case , I would like to call player.stopPlayBack() to stop the video playing at backing
And for the 2) case , I would like to call player.stopPlayBack() and player.release() to terminate the player
The problem is , what event I should call for the case 1) and 2)? I try using onPause or onStop but both of them seems has not fired.
How to fix it?
Thanks a lot for helping.

Updated:

Video fragment code
public class Video extends Fragment implements MediaPlayer.OnPreparedListener {
    @Bind(R.id.player) EMVideoView player;
    @Bind(R.id.full_screen) ImageView full_screen;
    Context ctx;
    MyApp app;
    String video_url;
    int intent_code = 5545;
    int pos;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.video, container, false);
        ButterKnife.bind(this, view);

        Bundle bundle = this.getArguments();
        video_url = bundle.getString("video_url");
        String id = bundle.getString("id");

        app = (MyApp) getActivity().getApplicationContext();
        app.record_view(id);

        Main m = (Main)getActivity();
        m.toggle_upload_btn(false);

        pos = 0;

        full_screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), VideoFullScreen.class);
                i.putExtra("video_url", video_url);
                i.putExtra("time", (int) player.getCurrentPosition());
                startActivityForResult(i, intent_code); //random intent number
            }
        });

        return view;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        player.seekTo(pos);
        player.start();
    }

    @Override
    public void onResume() {
        super.onResume();
        player.setOnPreparedListener(this);
        player.setVideoURI(Uri.parse(video_url));
    }

    @Override
    public void onStop() {
        super.onStop();
        player.stopPlayback();
        //player.release();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == intent_code) {
            if(resultCode == Activity.RESULT_OK){
                pos = data.getIntExtra("time", 0);
            }
        }
    }

A: When the fragment is added to the backstack, and then getting replaced or removed - it will go like this:
onPause() -> onSaveInstanceState() -> onStop() -> onDestroyView()

If the fragment is removed, or replaced without getting added to the back stack, then following happens:
onPause() -> onSaveInstanceState() -> onStop() -> onDestroyView()  -> onDestroy() -> onDetach() -> Fragment is destroyed.

And when a activity starts another activity (source):

The order of lifecycle callbacks is well defined, particularly when
  the two activities are in the same process and one is starting the
  other. Here's the order of operations that occur when Activity A
  starts Acivity B:
Activity A's onPause() method executes. Activity B's onCreate(),
  onStart(), and onResume() methods execute in sequence. (Activity B now
  has user focus.) Then, if Activity A is no longer visible on screen,
  its onStop() method executes.

Because you need to call on your activity where your fragment is existing, to start a new activity.


text:
Q: Why my interstitial ads always load/show on app i had success Implementation interstitial ads admob but i have 1 problem, why interstitial ads always show every second on my app, so i cannot play my app because this interstitial ads
any want help me how to make interstitial ads show only 1 interstitial ads every app lauch
here my code on my app Activity :
public class Activity extends Activity implements AdListener {
    WebView mWebView;
    private InterstitialAd interstitial;

    .......

    interstitial = new InterstitialAd(this, "a15xxxxxxxxxx");
    AdRequest adRequest = new AdRequest();
    interstitial.loadAd(adRequest);
    interstitial.setAdListener(this);

    .......

    public void onReceiveAd(Ad ad) {
          Log.d("OK", "Received ad");
          if(interstitial.isReady()) {
             interstitial.show();
          }
    }

A: Migrate from AdMob to google-play-services, AdMob is deprecated
You should show your ad if .isLoaded()
if (interstitial.isLoaded()) {
  interstitial.show();
} else {
  Log.d(LOG_TAG, "Interstitial ad was not ready to be shown.");
}

Here is an example for Interstitial ads

A: Your problem may well be caused by you showing your ad as soon as it is received (ie onAdReceived). For interstitials you should show the ad at a natural break point in your app instead.


text:
Q: Is there a time limit for recording audio on a PowerPoint slide? I'm recording audio files in a PowerPoint presentation (Slide Show / Record Slide Show). Some of the longer narrations truncate. Does anyone know if there is a time limit per slide?
If so, can it be increased?

A: There's no MS-documented time limit, but in practice, users do find that some versions of PPT do truncate audio. As it happens, I've been looking into this a bit and have been collecting reports from users who run into the problem. So far 40 seconds seems to be the magic number.  Narration shorter than that doesn't seem to get cut off.  It appears to be more a bug in how PPT "reads" the length of the audio file than an actual limit, so there's no fix until MS comes up with one.  I suspect you could work around the problem by keeping your narrations down to say 35 or 30 seconds per slide; for slides that require longer narration, add a second duplicate slide to add the remainder of the narration to and then set the transition to the duplicate slide to automatic.

A: My workflow for the independent recording of narrations for Windows 7 and PowerPoint 2013 is the following (for a single slide).

*

*Set your mic up at the Recording tab of the in the standard Sound application

*Open the standard Windows Sound Recorder, record narration for Slide 01, and save it in WMA format with the name "Slide 01.wma" in the target folder.

*Open the target slide in PowerPoint and drag the WMA file and drop it to the slide.

*Select the grey speaker icon, move it in white space of the slide, go to PLAYBACK ribbon, tick Hide During Show, and use Trim Audio to crop the track as required, etc.

*Go to ANIMATIONS ribbon, in Timing group: in Reorder Animation push Move Earlier (turns to grey), in Start: set With Previous. This makes the narration track start playing when the slide appears on the screen.

*Go to SLIDE SHOW ribbon and call Record Slide Show Start Recording from Current Slide, then clear tick from Slide and animation timings.

*The slide appears, and the narration track starts playing. Listen to the narration and, at the right time, use Laser Pointer (Ctrl + left mouse click) if needed. Once done, push the Escape button on the keyboard.

*Notice that another (dummy) grey speaker icon appears at the bottom left of the slide. This is a dummy track (up to 5 sec) that PowerPoint recorded at the previous step. Select it and simply delete it (push the Del button on the keyboard).

*Go to SLIDE SHOW ribbon and call From Current Slide at the Start Slide Show group to check that everything is well done.

I hope this would help you in making excellent recordings.

A: I have PPT version 2111.  I not only find that it truncates my audio, but it truncates my entire presentation.  It won't let me record past slide 26 of a 60 slide deck.  The current file size is just under 32 GB.  And PPT suggests that what is recorded is just over 18 minutes.
To address the truncation, I added an invisible shape (an oval with both outline and fill set to none) and added it at the end of the animation with enough delay that it plays back my full slide narration.
I haven't overcome the appraent size limit on the overall recording.


text:
Q: Can we sketch $\mathbf{Set}^{\mathrm{op}}$? Is there a large limit sketch whose category of models is equivalent to $\mathbf{Set}^{\mathrm{op}}$?
Is there perhaps even a large limit sketch $\mathscr{S}$ generated by powers of an object $X$ such that the forgetful functor $\mathbf{Mod}(\mathscr{S}) \to \mathbf{Set}$ is equivalent to $\mathrm{Hom}(-,2) : \mathbf{Set}^{\mathrm{op}} \to \mathbf{Set}$?
(There cannot be a small limit sketch because $\mathbf{Set}^{\mathrm{op}}$ is not locally presentable.)

A: A fundamental theorem of elementary topos theory is that the contravariant powerobject functor $\Omega^{(-)} : \mathcal{E}^\textrm{op} \to \mathcal{E}$ is monadic for any elementary topos $\mathcal{E}$.
In particular, $2^{(-)} : \textbf{Set}^\textrm{op} \to \textbf{Set}$ is monadic.
It is also known that if $U : \mathcal{A} \to \textbf{Set}$ is monadic, then $\mathcal{A}$ is equivalent to the category of models of a (large infinitary) Lawvere theory $\mathcal{T}$, namely the opposite of the Kleisli category of the monad, hence also equivalent to the category of models of a (large infinitary) product sketch.
Let me be more precise about the second part.
We may assume without loss of generality that $U : \mathcal{A} \to \textbf{Set}$ is the forgetful functor from the Eilenberg–Moore category of a monad $(T, \eta, \mu)$ on $\textbf{Set}$.
Given an algebra $(A, \alpha)$, the functor $\mathcal{A} ({-}, (A, \alpha))$ defines a product-preserving functor $\mathcal{T} \to \textbf{Set}$, i.e. a model of $\mathcal{T}$, and it is easy to check that we get a fully faithful embedding $\mathcal{A} \to \textbf{Mod} (\mathcal{T})$.
On the other hand, suppose we have a product-preserving functor $M : \mathcal{T} \to \textbf{Set}$.
Let $F^{(-)} : \textbf{Set}^\textrm{op} \to \mathcal{T}$ be (the opposite of) the free algebra functor.
Then $M (F^{(-)}) : \textbf{Set}^\textrm{op} \to \textbf{Set}$ preserves products, hence is represented by some set $A$ and some $m \in M (F^A)$.
We may assume w.l.o.g. that $A = M (F^1)$.
Let $f \in T A$.
This determines a morphism $F^A \to F^1$ in $\mathcal{T}$, hence induces a map $f : M (F^A) \to M (F^1)$.
Define $\alpha : T A \to A$ by $\alpha (f) = f (m)$.
You can then verify that $(A, \alpha)$ is an algebra and that $M$ is isomorphic to the restriction of the functor represented by $(A, \alpha)$.
Thus $\mathcal{A} \to \textbf{Mod} (\mathcal{T})$ is also essentially surjective on objects, so we indeed have an equivalence of categories.


text:
Q: Add body to ClientRequest on Electron I would like to use ClientRequest with Electron. I want to add a body to my request, but I see no information about body in the documentation.
My request object:
  const requestApi = {
    method,
    headers,
    protocol: process.env.API_PROTOCOL,
    hostname: process.env.API_HOSTNAME,
    port: process.env.API_PORT,
    path: `${process.env.API_PATH}${slug}`,
    body,
  };

And my request:
request.on('response', data => {
  console.log('---------------------');
  console.log(data);

  data.on('data', chunk => {
    console.log(chunk);
  });
  data.on('end', () => {
    console.log('No more data in response.');
  });

  if (data.statusCode === 200) {
    event.sender.send('api-response');
  }
});

request.end();

When I console.log(data), the data is an empty array data: [].
Can anyone help me ? :)
Thank you!

A: ClientRequest is a Writable Stream. The way to send body data to a Writable Stream is to use .write() and .end(). You can see these functions in the API documentation: ClientRequest.write() and ClientRequest.end(). The argument chunk is where your data should go.
In your example, that might look like this:
const requestApi = {
  method,
  headers,
  protocol: process.env.API_PROTOCOL,
  hostname: process.env.API_HOSTNAME,
  port: process.env.API_PORT,
  path: `${process.env.API_PATH}${slug}`,
};

const request = new ClientRequest(requestApi);

request.on('response', data => { /* ... */ });

request.end(body);


text:
Q: Load a specific viewController on push notification Swift 2 AppDelegate I want to open a specific view controller (a hidden one, because it's only accessible when receiving a certain push notification (it's not accessible through the tab bar)) and I've been able to do this but I'm facing a problem..
My app has a custom Tab Bar controller called RootViewController. When you click on a notification with the special value it shows an alert view asking whether the user wants to open the notification or not.
The notification triggers bringing a specific view controller to the front but
the problem is that I don't have access to the tab bar anymore.
I don't know how to achieve this.
This is my code in AppDelegate.m:
var presentedVC = self.window?.rootViewController as? UINavigationController
while (presentedVC!.navigationController != nil)  {
    presentedVC = presentedVC!.navigationController
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewControllerWithIdentifier("PushNotificationView") as? NotTestViewController

destinationViewController?.url = self.url!
presentedVC?.presentViewController(destinationViewController!, animated: true, completion: nil)

})
)
alertCtrl.addAction(UIAlertAction(title: "Cancelar", style: .Destructive, handler: nil))

This code works but not with the desired behaviour.
Any ideas what I am missing?
Thank you so much
EDIT
I've changed the RAMTabBarAnimationController to TabBarController because RAMTabBarAnimationController does not inherit from TabBarController. But I still see the same behaviour.

A: I want to respond to my own question because I think maybe someone is facing the same situation, I have to say thanks to @Muneeba
Well, first of all you have to know if your remote push notification needs to do a background fetch, this is important because if so the didReceiveRemoteNotification is called twice (first when you click on the notification alert, seconds when it opens the app), so you have to be aware of this.
In my case I didn't do a background fetch, so my content-available:false flag was set to false.
Next thing to do is add you desire ["key":value] to the notification payload to know whether you want to open a specific view controller or not.
Manage whether open a view controller or not.
In my app I want to open a alert control pop up always showing the body of the push notification (with a OK button) and only when certain value is set open a alert control with a question to the user whether or not he wants to open the new content that arrives (normally this content is a web based content that open a webview embedded in a view controller)
In the didReceiveRemoteNotification:
if let mensaje = userInfo["m"] as? String {
// Here is where I know if the value is set in the notification payload
 let alertCtrl = UIAlertController(title: titulo, message: mensaje as String, preferredStyle: UIAlertControllerStyle.Alert)
 if url == nil {
   alertCtrl.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
 } else {
 alertCtrl.addAction(UIAlertAction(title: "Ver receta", style: .Default, handler: {
  action in

      let storyboard = UIStoryboard(name: "Main", bundle: nil)
      //self.window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("TabbedController") as! UITabBarController
      let navigationController = storyboard.instantiateViewControllerWithIdentifier("pushNotificationNavigation") as! UINavigationController
      let dVC:NotTestViewController = navigationController.topViewController as! NotTestViewController
      // This is for passing the URL to the view Controller
      dVC.url = self.url!
      self.window?.rootViewController?.presentViewController(navigationController, animated: true, completion: {})

      })
      )
      alertCtrl.addAction(UIAlertAction(title: "Cancelar", style: .Destructive, handler: nil))
   }
   // Find the presented VC...
   var presentedVC = self.window?.rootViewController
   while (presentedVC!.presentedViewController != nil)  {
      presentedVC = presentedVC!.presentedViewController
      }
      presentedVC!.presentViewController(alertCtrl, animated: true, completion: nil)

      handler(UIBackgroundFetchResult.NoData)
 }

A: Your RAMAnimatedTabBarController inherits which class? if it inherits UIViewController/UITabbarController then take a UINavigationController and set its rootViewController to  your RAMAnimatedTabBarController instance and then assign it as window's rootViewController and set the navigationBar hidden for this UINavigationController and when you want to push to specific Controller do like this
var presentedVC = self.window?.rootViewController as? UINavigationController
presentedVC(yourdesiredController, animated: true)


text:
Q: create db and user mysql and set privileges php Is there a way to create a new MySQL database, a new MySQL user and give the new user privileges on the new database all using PHP?

A: Yes, as all these actions can be performed by regular SQL queries.
However, I'd refrain from running PHP scripts with database connection from root user.

A: If you are hosting your project on CPanel, then the mysql_query method will not work to create databases, users, and to grant permissions.
You have to use the XML Api for CPanel.
<?php
include("xmlapi.php");

$db_host = 'yourdomain.com';
$cpaneluser = 'your cpanel username';
$cpanelpass = 'your cpanel password';

$databasename = 'testdb';
$databaseuser = 'test'; // Warning: in most of cases this can't be longer than 8 characters
$databasepass = 'dbpass'; // Warning: be sure the password is strong enough, else the CPanel will reject it

$xmlapi = new xmlapi($db_host);
$xmlapi->password_auth("".$cpaneluser."","".$cpanelpass."");
$xmlapi->set_port(2082);
$xmlapi->set_debug(1);//output actions in the error log 1 for true and 0 false
$xmlapi->set_output('array');//set this for browser output
//create database
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));
//create user
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));
 //add user
$addusr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduserdb", array("".$cpaneluser."_".$databasename."", "".$cpaneluser."_".$databaseuser."", 'all'));
?>

Download xmlapi.php from here, or simply search on google for it.
This is what worked for me perfectly.

A: You could do something like this:
mysql_connect('localhost','user',password);
mysql_query("CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';");
mysql_query("GRANT ALL ON db1.* TO 'username'@'localhost'");
mysql_query("CREATE DATABASE newdatabase");
mysql_close();

You may look at the MySQL documentation on GRANT and CREATE USER

A: i will suggest you to use phpmyadmin.
you need to do steps:

*

*open phpmyadmin

*go to admin section

*hit on add user account

*put user name and password

*set privileges

*hit the [ go ]button

that's all
see in action on youtube [ click here  ]
in case if you want to know more about phpMyadmin go with official
but if there is any special reason to do so with php the here is the sql commend
CREATE USER 'tesrytss'@'%'//user name
IDENTIFIED VIA mysql_native_password USING '***';.//set pass
GRANT SELECT, INSERT, UPDATE, DELETE, FILE ON *.* TO 'tesrytss'@'%' // previlages and username and location
REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; //other requerment

A:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="en-gb" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Create Database</title>

Create Database

<form action="<?php $currentFile = $_SERVER["PHP_SELF"];$parts = Explode('/', $currentFile);echo $parts[count($parts) - 1];?>" method="post">

Database Name: <input name="databasename" type="text" />

DB Pass: <input name="dbpass" type="text" />

Admin Pass: <input name="passbox" type="password" />

<input name="Submit1" type="submit" value="submit" />

</form>

<?php

//*********************** CONFIG SETUP ************************************//
// Created by kierzo@kierzo.com
//
// set the admin pass for the page
$adminpass = "*******";   // change ******* with your page pass
//
// set mysql root pass
$mysqlRootPass = "*******";  // change ******* with your mysql root pass
//
//
//*********************** CONFIG SETUP ************************************//

// if isset set the varibables

if(isset($_POST["passbox"]) && ($_POST["databasename"])){

$databasename = $_POST["databasename"];
$password = $_POST["passbox"];
$dbpass = $_POST["dbpass"];

}
else { exit;}

if(($password) == ($adminpass)) {

}
else {

echo "Incorrect Password!";

exit;}

// store connection info...

$connection=mysqli_connect("localhost","root","$mysqlRootPass");

// check connection...

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  // Create database
  echo "

";
#echo "$sql";
$sql="CREATE DATABASE $databasename";

if (mysqli_query($connection,$sql))
  {
  echo "
Database $databasename created successfully!
";
  }
else
  {
  echo "Error creating database: " . mysqli_error($con);
  }

    // Create user

$sql='grant usage on *.* to ' . $databasename . '@localhost identified by ' . "'" . "$dbpass" . "'";
echo "

";
#echo "$sql";
if (mysqli_query($connection,$sql))
  {
  echo "
User Created... $databasename created successfully!
";
  }
else
  {
  echo "Error creating database user: " . mysqli_error($con);
  }

      // Create user permissions

$sql="grant all privileges on $databasename.* to $databasename@localhost";
echo "

";
#echo "$sql";
if (mysqli_query($connection,$sql))
  {
  echo "
User permissions Created... $databasename created successfully!
";
  }
else
  {
  echo "Error creating database user: " . mysqli_error($con);
  }

  echo "
Database Name: $databasename
";
  echo "
Database Username: $databasename
";
  echo "
Database Password: $dbpass
";
  echo "
Database Host: localhost
";
?>

A: open PHP myadmin or MySql workbench go to query window then run below query
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
GRANT ALL ON db1.* TO 'username'@'localhost'"


text:
Q: Basic web service calling in android I need a tutorial on how to do a basic web service call in android. I currently use ksoap but I and getting an error when I make the call and I need to know what the response from the server was. ksoap wont give me that information because it parses the response in the api where I am getting the error.
I am new to all this web service stuff so please help me out

A: Well it depends what you want to develop it using
A good tutorial using PHP, MySQL is here
I know you are using KSOAP at the moment but here is a nice tutorial that uses KSOAP and in explained in nice detail.


text:
Q: GNUPlot : Can't set ylabel vertical Good Morning,
I'm using GNUPlot with LaTeX term to import graphics in LaTeX.
By default my y-label is horizontal and I want it to be vertical.
Writing the following does give the results I'm after:
set term latex
set out 'm16.tex'

set xrange [0:20]
set datafile separator ','
set key inside bottom
set size 0.65,0.9
set xlabel 'Number of samples'
set ylabel 'Occurences' rotate by 90

A: You have to specify the rotate option when setting the latex terminal:
set term latex rotate

From help latex:

If 'rotate' is specified, rotated text, especially a rotated y-axis label,
   is possible (the packages graphics or graphicx are needed). The 'stacked'
   y-axis label mechanism is then deactivated.


text:
Q: How to get use id in facebook graph API using user email and password? I am working on facebook application in java, and i succeed to retrive the access_token.
Now i want to pull for example the user feed but i dont have the user id https://graph.facebook.com/userid(or me)/likes?access_token=...
Yes, I know user id could be replaced by 'me', but my app is a web app, user just input his user name and password in our frame, not facebook OAuth Dialog which is for user authentication and app authorization, so I think facebook should do not know who is me, so I need user uid. In previous implementation, I could use user email and password to get user id and session key by Facebook Rest API, but how could I get it by Graph API by user name and password?Is there a way to do that?

A: The Graph API uses OAuth 2.0 for authorisation.
One of the main goals of OAuth is that the user's credentials don't have to be handed out to the 3rd party applications.
So, it's not possible to get the user id and session key using the Graph API with just the users email & password (unless you logged them in manually yourself).


text:
Q: MYSQL to CSV with PHP with 4 blank rows at top There are 2 blank rows at the top of csv when script is run...Have no idea why.  This code works in another application I've made.  I'm using the same code and same database??
Does the location in directory make a difference?
<?php

mysql_connect("", "", "")
or die(mysql_error());
mysql_select_db("dbname")
or die(mysql_error());
$database = "mydb";

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

// Fetch Record from Database
    $output = "";
// Store Matching
    $sql = mysql_query("SELECT audiolist.`Store Number`, audiolist.Address, audiolist.City, audiolist.State, audiolist.`Zip Code`, audiolist.`Install Date`
                           FROM audiolist INNER JOIN filteredlist ON audiolist.`Store Number`=filteredlist.`Store Number`");
    $columns_total  = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
    $heading = mysql_field_name($sql, $i);
    $output .= '"'.$heading.'",';
}

$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename =  "myfilename" . date("Y-m-d") . ".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

A: Not exactly sure why it matters...but apparently if there are any lines before the initial <?php tag, those lines show up as plank rows when the csv is generated. There were two lines before mine and therefore 2 blank rows...It works now!

A: After this line of your code:
header('Content-Disposition: attachment; filename='.$filename);

Add this code:
 ob_clean();   // discard any data in the output buffer (if possible)
 flush();


text:
Q: How to add a javascript variable as action parameter in Laravel form I was trying add a js variable as my action parameter where that variable varies for every button a form will be created and will be sent to a bootstrap modal-body(initially modal-body is blank).
Here is the js code i was trying to assign to modal-body html
$('.postComment').click(function(e){
    e.preventDefault;
    var id = $(this).attr('id'); //this is the id suppose:id='1234abcd'

    var data =  '{{Form::open(array("method" => "POST","route" => ["post.comment",'+id+'],"class" => "form-horizontal"))}}'+
                '{{Form::textarea("comment", null, array("required","class"=>"form-control","placeholder"=>"Add a comment"))}}'+
                '{{Form::submit("Comment",array("class"=>"btn btn-info"))}}'+
                '{{Form::close()}}';
    $('#comment').modal();
    $('#comment').on('shown.bs.modal', function(){
        $('#comment .modal-body').html(data);
    });
    $("#comment").on('hidden.bs.modal', function(){
            $('#comment .modal-body').html('');
        });
});

When clicking on comment button in the form action appears like this
action="/post/comment/+id+"

But expected is
action="/post/comment/1234abcd"

Am I missing something? or doing in wrong way?

A: If I write the data part like this it worked
var data =  '<form method="post" class="form-horizontal" action="post/comment/'+id+'">'+
            '<input type="hidden" name="_token" value="{{ csrf_token() }}">'+
            '<textarea id="commentBox" name="comment" class="form-control" required></textarea>'+
            '<input type="submit" name="Comment" value="Comment" class="btn btn-info"/>'+
            '</form>';

in the form action it showed
action="/post/comment/1234abcd"

A: You could use a place holder in the action and replace it using javascript when the click occurs.
The problem with what you are trying to do is the laravel form code runs on server long before the javascript runs in browser
Try
 var data =  '{{Form::open(array("method" => "POST","route" => ["post.comment",'+id+'],"class" => "form-horizontal"))}}'+
                '{{Form::textarea("comment", null, array("required","class"=>"form-control","placeholder"=>"Add a comment"))}}'+
                '{{Form::submit("Comment",array("class"=>"btn btn-info"))}}'+
                '{{Form::close()}}';

var $form = $(data);
$form.attr('action', function(_, action){
  return action.replace('+id+', id)
});

$('#comment').modal();
$('#comment').on('shown.bs.modal', function(){
    $('#comment .modal-body').html($form);
});

A: you can write like this
   var id123 = $(this).attr('id'); //this is the id suppose:id='1234abcd'

    var data =  '{{Form::open(array("method" => "POST","route" => ["post.comment'+id123+'"],"class" => "form-horizontal"))}}'+
                '{{Form::textarea("comment", null, array("required","class"=>"form-control","placeholder"=>"Add a comment"))}}'+
                '{{Form::submit("Comment",array("class"=>"btn btn-info"))}}'+
                '{{Form::close()}}';


text:
Q: Where clause in Fluent NHibernate Many-to-Many I am trying to setup a many-to-many mapping in Fluent Nhibernate that has a where clause attached to the child table.
This is basically how it should work:
HasManyToMany(p => p.Images)
  .Table("ProductImages")
  .ParentKeyColumn("ProductID")
  .ChildKeyColumn("ImageID")
  .Where("ImageTypeID = 2");

The ImageTypeID column is in the Images table, but NHibernate is assuming it is part of the ProductImages table. Any idea how I can specify this?
Thanks!

A: You can. Use .ChildWhere in your Fluent NHibernate mapping:
HasManyToMany(p => p.Images)
  .Table("ProductImages")
  .ParentKeyColumn("ProductID")
  .ChildKeyColumn("ImageID")
  .ChildWhere("ImageTypeID = 2");

A: You can't as far as I know. I'm not sure that Where is valid on a many-to-many association.
I would handle this by creating an extension method on IEnumerable<Image> to allow easy filtering on image type. Then you could call Images.Landscape(), e.g., on any Images collection.


text:
Q: JavaScript NPM Error in visual studio code In visual Studio Code , i want my javascript program to run and automatically through a server as , i'm learning javascript through a online.
i try to did the same steps as i watched a tutorial on Setup IDE .
so i installed Git and Node , now when i open Visual Studio , after saving a Hello World Program , it should run automatically .
so i type in Terminal : npm install
then error came , then again i typed npm run dev to start my server in Browser.
i [the error in the pic is :
C:\Users\Addie\Desktop\JS\webpack-starter-master>npm install
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\Addie\Desktop\JS\webpack-starter-master\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Addie\Desktop\JS\webpack-starter-master\package.json'
npm WARN webpack-starter-master No description
npm WARN webpack-starter-master No repository field.
npm WARN webpack-starter-master No README data
npm WARN webpack-starter-master No license field.

up to date in 10.317s
found 0 vulnerabilities

C:\Users\Addie\Desktop\JS\webpack-starter-master>npm run dev
npm ERR! path C:\Users\Addie\Desktop\JS\webpack-starter-master\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\Addie\Desktop\JS\webpack-starter-master\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Addie\AppData\Roaming\npm-cache\_logs\2018-09-02T22_21_22_028Z-debug.log

]1
Please help me out , what should i do and what am i doing wrong?.

A: You need to do npm init to create a package.json for your directory

A: To run a JavaScript file locally (using node):
$ cd PATH_TO_PROJECT_FOLDER
$ node FILE_NAME

If you're trying to run a project which contains a npm run dev script to start up a server:
$ cd PATH_TO_PROJECT_FOLDER
$ npm install
$ npm run dev


text:
Q: Writing infinite list to skip every factor of p? How can I efficiently represent the list [0..] \\ [t+0*p, t+1*p ..]?
I have defined:
Prelude> let factors p t = [t+0*p, t+1*p ..]

I want to efficiently represent an infinite list that is the difference of [0..] and factors p t, but using \\ from Data.List requires too much memory for even medium-sized lists:
Prelude Data.List> [0..10000] \\ (factors 5 0)
<interactive>: out of memory

I know that I can represent the values between t+0*p and t+1*p with:
Prelude> let innerList p1 p2 t = [t+p1+1, t+p1+2 .. t+p2-1]
Prelude> innerList 0 5 0
[1,2,3,4]

However, repeatedly calculating and concatenating innerList for increasing intervals seems clumsy.
Can I efficiently represent [0..] \\ (factors p t) without calculating rem or mod for each element?

A: For the infinite list [0..] \\ [t,t+p..],
yourlist t p = [0..t-1] ++ [i | m <- [0,p..], i <- [t+m+1..t+m+p-1]]

Of course this approach doesn't scale, at all, if you'd want to remove some other factors, like
[0..] \\ [t,t+p..] \\ [s,s+q..] \\ ...

in which case you'll have to remove them in sequence with minus, mentioned in Daniel Fischer's answer. There is no magic bullet here.
But there's also a union, with which the above becomes
[0..] \\ ( [t,t+p..] `union` [s,s+q..] `union` ... )

the advantage is, we can arrange the unions in a tree, and get algorithmic improvement.

A: You can't use (\\) for that, because
(\\)                    :: (Eq a) => [a] -> [a] -> [a]
(\\)                    =  foldl (flip delete)

the list of elements you want to remove is infinite, and a left fold never terminates when the list it folds over is infinite.
If you rather want to use something already written than write it yourself, you can use minus from the data-ordlist package.
The performance should be adequate.
Otherwise,
minus :: Ord a => [a] -> [a] -> [a]
minus xxs@(x:xs) yys@(y:ys)
    | x < y     = x : minus xs yys
    | x == y    = minus xs ys
    | otherwise = minus xss ys
minus xs _      = xs

A: You can use a list comprehesion with a predicate, using rem:
>>> let t = 0
>>> let p = 5
>>> take 40 $ [ x | x <- [1..], x `rem` p /= t ]
[1,2,3,4,6,7,8,9,11,12,13,14,16,17,18,19,21,22,23,24,26,27,28,29,31,32,33,34,36,37,38,39,41,42,43,44,46,47,48,49]

A: If you want efficiency, why does your solution have to use list comprehension syntax?
Why not something like this?
 gen' n i p | i == p = gen' (n + p) 1 p
 gen' n i p = (n+i) : gen' n (i+1) p
 gen = gen' 0 1

and then do
 gen 5

A: Because you have ascending lists, you can simply lazily merge them:
 nums = [1..]
 nogos = factors p t
 result = merge nums (dropWhile (<head nums) nogos) where
      merge (a:as) (b:bs)
        | a < b = a : merge as (b:bs)
        | a == b = merge as bs
        | otherwise = error "should not happen"

Writing this in a general way so that we have a function that builds the difference of two infinite lists, provided only that they are in ascending order, is left as exercise. In the end, the following should be possible
 [1..] `infiniteDifference` primes `infiniteDifference` squares

For this, make it a left associative operator.


text:
Q: Verifying a cosine FourierTransform On page 31 of this standard reference we have the following relation:

I wanted to use mathematica to verify this transform numerically for some example values. So I type in:
transf[a_, c_, \[Beta]_, w_] =
  (\[Pi] (Cos[\[Pi]/\[Beta] -
  ( a c)/\[Beta]] Cosh[\[Pi]/\[Beta] + (c w)/\[Beta]] -
  Cos[\[Pi]/\[Beta] + (a c)/\[Beta]] Cosh[\[Pi]/\[Beta] -
  ( c w)/\[Beta]]))/(\[Beta] Sin[ c] (Cosh[(2 \[Pi] w)/\[Beta]] -
  Cos[(2 \[Pi] a)/\[Beta]]))

And try, i.e. the following
NIntegrate[Cosh[a x]/(Cosh[\[Beta] x]+Cos[c])Cos[x Zeta[3]]
 /.a->0 /.\[Beta]->2/.c->\[Pi]/3,{x,0,Infinity}]

0.377469

Trying to evaluate the analytic right hand side at the same point gives however:
transf[0, \[Pi]/3, 2, Zeta[3]]

0

Which is clearly not the same. What is the issue here? Is the numeric integration in Mathematica wrong? Is there a typo in the reference? Did I misunderstand some of the input? Thanks for any suggestion!


text:
Q: Angular ngFor trackBy not working. Not Updating DOM Hi y'all my dom is not being updated with trackBy for some reason. I have another component where trackBy is working great but for some reason I can't get it to work on my new component. I have to refresh the page everytime something is added to groceryList and I don't know why?
HTML:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

        <button class="btn btn-link" type="button" data-toggle="collapse" attr.data-target="#grocery2{{index}}" aria-expanded="false" aria-controls="grocery2{{index}}">
          {{grocery.recipeName}}
        </button>

{{ingredient}}

<mat-icon svgIcon="shopping_cart"></mat-icon>

Component Code:
import { Component, OnInit, NgModule } from '@angular/core';
import {GetRecipesService} from '../getrecipes.service'
import { MatIconRegistry } from "@angular/material/icon";
import { DomSanitizer } from "@angular/platform-browser";
@Component({
  selector: 'app-grocery-sidebar',
  templateUrl: './grocery-sidebar.component.html',
  styleUrls: ['./grocery-sidebar.component.css']
})
export class GrocerySidebarComponent implements OnInit {

  constructor(getRecipesService: GetRecipesService,private matIconRegistry: MatIconRegistry,private domSanitizer: DomSanitizer) {
    getRecipesService.getGroceryList().subscribe(promise=>{
      this.groceryList = promise;
      this.groceryList = this.groceryList.data;
  });
    this.recipeService=getRecipesService;
    this.matIconRegistry.addSvgIcon("shopping_cart",this.domSanitizer.bypassSecurityTrustResourceUrl("../assets/shopping-cart-solid.svg"));
  }

  addToGroceryList(recipeName,recipeIngredients){
    this.recipeService.addToGroceryList(recipeName,recipeIngredients).subscribe(promise=>{
      console.log("addToGroeryList Promise: "+promise);
      this.refreshGroceryList();
    });

  }

  refreshGroceryList(){
    this.recipeService.getGroceryList().subscribe(promise=>{
      console.log("refreshed groceryList: "+promise.data)
      this.groceryList = promise.data;
      console.log(this.groceryList);
    })
  }

  deleteGroceryRecipeById(recipeId){
    this.recipeService.deleteGroceryRecipeById(recipeId).subscribe(promise=>{
      this.refreshGroceryList();
    });
  }

  public trackByIdGroceryCode(index: number, grocery: any): string {
    console.log("tracking");
    return grocery._id;
}

  ngOnInit(): void {
  }

  recipeService;
  groceryList;
  showFiller=false;
}

And if your wondering, the console.log("tracking") inside of trackByIdGroceryCode() is being called when adding to my groceryList array. So I'm not sure why my dom isnt being updated unless I refresh the page
Here's my console output if you're curious
tracking  grocery-sidebar.component.ts:44:12
addToGroeryList Promise: [object Object] grocery-sidebar.component.ts:23:14
tracking  grocery-sidebar.component.ts:44:12
refreshed groceryList: [object Object],...,[object Object] grocery-sidebar.component.ts:31:14
Array(23) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ] grocery-sidebar.component.ts:33:14
tracking

{{ groceryList | json }}

        <button class="btn btn-link" type="button" data-toggle="collapse" [attr.data-target]="'#grocery2'+index" aria-expanded="false" [aria-controls]="'grocery2'+index">
          {{grocery.recipeName}}
        </button>

{{ingredient}}

<mat-icon svgIcon="shopping_cart"></mat-icon>

Recipe Component that invokes groceryComponent:
import {Component} from '@angular/core';
import {GetRecipesService} from './getrecipes.service'
import { TagInputModule } from 'ngx-chips';
import {GrocerySidebarComponent} from "./grocery-sidebar/grocery-sidebar.component";

TagInputModule.withDefaults({
    tagInput: {
        placeholder: 'Add a ag',
        // add here other default values for tag-input
    },
    dropdown: {
        displayBy: 'my-display-value',
        // add here other default values for tag-input-dropdown
    }
});

@Component({
    selector: 'recipes', //<recipes>
    styleUrls: ['./recipes.component.css'],
    template: `

Modal title

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
                </button>

                    <form>

                        Recipe Name
                        <input [(ngModel)] ="formRecipeName" name="formRecipeName" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">

                        <tag-input [(ngModel)]="formIngredients" id="ingredientTags" [modelAsStrings]="true" name="formIngredients" [secondaryPlaceholder]="'Enter Ingredient'"> </tag-input>

                    <button type="submit" class="btn btn-primary" (click)="addRecipe()" data-dismiss="modal">Submit</button>

                    </form>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

Are you sure?

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
                </button>

                    <button type="submit" class="btn btn-primary" (click)="deleteRecipeInBuffer()" data-dismiss="modal">Delete</button>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                    <button class="btn btn-outline-success my-2 my-sm-0" type="submit" data-toggle="modal" data-target="#exampleModal">Add Recipe</button>

                <form class="form-inline mt-2 mt-md-0">
                    <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
                    <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
                </form>

                        <button type="button" data-toggle="modal" data-target="#deleteModal" class="close" aria-label="Close" (click)="prepareToDelete(recipe._id)">
                        ×
                        </button>

{{recipe.recipeName}}

{{recipe.recipeIngredients}}

                                    <button type="button" class="btn btn-sm btn-outline-secondary" (click)="addToGroceryList(recipe.recipeName,recipe.recipeIngredients)">Add To Grocery List</button>

                                9 mins

    TODO: Edit Recipe. Ingreidents with quantity. Ingredients with style (Chopped. Diced. Sautee..etc). Search or Filter (by name or ingredient).
    TODO: Add to grocery List. Undo Button
                `,
})
export class RecipesComponent{
    constructor(getRecipesService: GetRecipesService,groceryList:GrocerySidebarComponent){
        getRecipesService.getRecipes().subscribe(promise=>{
            this.recipeList = promise;
            this.recipeList = this.recipeList.data;
            console.log(this.recipeList);
        });
        this.recipeService=getRecipesService;
        this.groceryList = groceryList;

    }
    addToGroceryList(recipe,ingredients){
        this.groceryList.addToGroceryList(recipe,ingredients);
    }

    //when user presses x on card, the id is stored here. Then are you sure window appears
    //if yes on are you sure then delete whats in buffer
    //else clear what's in buffer
    prepareToDelete(recipeId){
        this.deleteBuffer = recipeId;
    }
      //if yes after are you sure, delete whats in buffer
  deleteRecipeInBuffer(){
        this.deleteRecipe(this.deleteBuffer);
    }

    addRecipe(){
        this.recipeService.addRecipe(this.formRecipeName,this.formIngredients).subscribe(promise=>{
            console.log("promise"+promise);
            this.refreshRecipeList();
            this.formIngredients = undefined;
            this.formRecipeName = undefined;
        });

    }

    deleteRecipe(recipeId){
        this.recipeService.deleteRecipe(recipeId).subscribe(promise=>{
            console.log(promise);
            this.refreshRecipeList();
        })

    }

    refreshRecipeList(){
        this.recipeService.getRecipes().subscribe(promise=>{
            console.log("refreshed");
            this.recipeList = promise.data;
        });
    }

    public trackByIdCode(index: number, recipe: any): string {
        return recipe._id;
    }
    deleteBuffer;//buffer is used to store recipeId => are you sure window comes up. if yes then delete whats in deleteBuffer
    formRecipeName;//form value in modal
    formIngredients; //form value in modal
    recipeService;//http access service
    recipeList;//list of all recipes recieved from recipeService
    groceryList;
}

UPADTE: I Learned that things update fine when deleting objects but when I call my function to add to my grocery component from my recipe component things don't update. I think my issue is that things arn't being called in the order that I think they are. I still don't know how to fix this but I really appreciate everyone that is trying to help
//

A: Looks like this could be an angular lifecycle issue; maybe the template is not getting updated after the subscriptions that are called when you run refreshGroceryList(). Try doing a manual change detection after you update the data, like so:
constructor(private cdr: ChangeDetectorRef, ...) {}

refreshGroceryList(){
this.recipeService.getGroceryList().subscribe(promise=>{
  console.log("refreshed groceryList: "+promise.data)
  this.groceryList = promise.data;
  this.cdr.detectChanges();
  console.log(this.groceryList);
})

}

A: The problem is you are trying to bind to aria and data attributes. If you change all the aria- attributes to attr.aria- and data- attributes to attr.data- it will work.
Here is a working StackBlitz https://stackblitz.com/edit/angular-ivy-kp6aev?file=src%2Fapp%2Fapp.component.html


text:
Q: Brace match syntax highlighting in posts and input editor Is it possible to make brace match syntax highlighting in posts?
When reading a post with long code blocks that have many loops and inner loops, it would be helpful to find where a particular block of code ends.
So that when we click on a starting brace, it would show the matching closing brace and vice-versa.
As @Barmar suggested in his comment, it would be more helpful to have a brace matching in the input editor than posts.

A: What about non brace using languages? How many levels should this nest? How should it handle incomplete marker pairs?
If code is unclear due to formatting, then it seems the proper thing to do would be to edit the post and improve the formatting and not rely on highlights that might be wrong due to errors in the original code.

A: Most IDE's match braces/parentheses/etc. Dreamweaver seems to do it, too, if you turn it on (on mobile now, will test it when I'm on my laptop later). Notepad++ matches braces as well.
So just copy-paste the code to an IDE, and use the brace-matching there.
If you don't have an IDE which does this, use the online  editor on github. Edit a file of the same language (fork a repo with a file of the same language if you can't get one), the editor has syntax highlighting and brace matching. Actually, for brace matching you can edit a file in any programming language (except for the few languages that treat braces differently)--just that you won't get syntax highlighting.


text:
Q: Android admob, what to do onAdFailedToLoad code == ERROR_CODE_NO_FILL The error is pretty self explanatory, but the desired behavior is kind of unkwon...
What should we do when admob returns there isn't ad to fill a banner (or a video reward)?

*

*should we retry instantly?

*should we wait a few moments (how long) and retry?

*should we just let it empty?

I'm actually retrying immediatly and i noticed that it lead to a very low match rate!! and after match rate declined ecpm also declined i guess they are somehow connected


text:
Q: XML Layout overlap I  am trying to create a certain layout, that consists of 2 parts a scrollview and a "footer" at the bottom, but always on top of the scrollview. Everything inside the scrollview must be visible (by scrolling).

This is my current code:
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

 <ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/banner" />

 <TextView
    android:layout_width="fill_parent"
    android:paddingTop="1dp"
    android:layout_height="3px"
    android:background="#DADADA" />

    <RelativeLayout
    android:id="@+id/InnerRelativeLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" >

   <Button
       android:id="@+id/button1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="true"
       android:layout_alignParentRight="true"
       android:text="Start Connecting" />

   <Button
       android:id="@+id/button01"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_above="@+id/button1"
       android:layout_alignParentLeft="true"
       android:text="First use" />

   <TextView
       android:id="@+id/textView1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="20dp"
       android:text="Welcome to ADB Wireless!"
       android:textSize="25sp" />

   </RelativeLayout>

 </LinearLayout>

But it gives an overlap on small screens & landscape mode. I would only like to have the 2 buttons to be inside the 'footer'. Thank you!

A: <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/button_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Next" />

    <Button
        android:id="@+id/button01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Previous" />
</LinearLayout>

<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@+id/button_layout" >
</ScrollView>

</RelativeLayout>


text:
Q: Why wasn't Gates McFadden removed from the opening credits of season 2 of TNG? This is not a question about why Gates McFadden left TNG; that's been discussed elsewhere.  My question is, why didn't they remove her name from the opening credits?  Did they not have the budget to make new credits?  Was her dismissal sudden enough that they didn't have time to edit the credits?
EDIT: I remembered McFadden being credited on the season 2 episodes when I watched them in syndication more than 20 years ago.  However, it appears that either my memory was faulty or that there were changes made between versions, as online videos don't seem to have her credit.  So, perhaps my question makes a false assumption.  It would be interesting to see if anyone who has some of the earlier versions (such as on VHS) could confirm or deny her credit.


text:
Q: Exception in thread "main" java.lang.NoSuchMethodError: org.apache.spark.sql.SQLContext.sql(Ljava/lang/String;)Lorg/apache/spark/sql/Dataset; I am trying to use Spark SQL from Scala IDE which I setup without Maven. I have Spark 1.5.1 in production environment and trying to execute following code through
 spark-submit --class com.dataflair.spark.Wordcount --master cluster /home/appserver/Sparkjob.jar
package com.dataflair.spark
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext

import org.apache.spark.SparkContext._

import org.apache.spark.sql.SQLContext

import org.slf4j.Logger
import org.slf4j.LoggerFactory;

object Wordcount {
def main(args: Array[String]) {
//Create conf object
val conf = new SparkConf()
.setAppName("WordCount")
//create spark context object
val sc = new SparkContext(conf)
//Check whether sufficient params are supplied
val sqlcontext=new org.apache.spark.sql.SQLContext(sc)

//Check whether sufficient params are supplied

import sqlcontext.implicits._

val dp_new=sqlcontext.sql("  SELECT * FROM  Temp_UFDR_t1 ")

dp_new.registerTempTable("DFUO")

//stop the spark context
sc.stop
}
}

I am getting following issue
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.spark.sql.SQLContext.sql(Ljava/lang/String;)Lorg/apache/spark/sql/Dataset;
        at com.dataflair.spark.Wordcount$.main(Wordcount.scala:26)
        at com.dataflair.spark.Wordcount.main(Wordcount.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:766)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:183)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:208)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:123)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

A: As you said, you are using spark 1.5.1 but we do not have DataSet in spark 1.5.1.
Probably you have boiled your code in Spark 1.5.1 and deployed/running application in Spark1.6 and above Spark Context objects.


text:
Q: how to transform/group this kind of raw json data into hierarchy strucutre I have a set of room data in json, each room data includes which site, building and floor it resides in.
The data examples are like
[
{
  'site':'liverpool', 'building':'building a', 'floor':'0', 'room':'room a'
},
{
  'site':'liverpool', 'building':'building a', 'floor':'1', 'room':'room b'
},
{
  'site':'liverpool', 'building':'building b', 'floor':'0', 'room':'room a'
}
............
]

now I using javascript to break down this data set into a hierarchy structure, such as
{
    'site':[
        {
            'name':'liverpool',
            'buildings':[
                {
                    'name':'building a',
                    'floors':[
                     {
                         'name':0,
                         'rooms':['room a', 'room b']
                     }
                    ]
                }
            ]
        }
    ]
}

for me, it is still very hard to transform the raw data into the wanted structure, could someone instruct me how to do it?
I have tried with underscore, but only achieved with one hierarchy.
 var groups = _.groupBy(data,function(room){
                return (room.site+","+room.building+","+room.floor);
            })

A: Assuming var data is your JSON:
var sites = [];

for(var i=0,l=data.length;i<l;i++) {
    var row = data[i];
    var site = false;
    var building = false;
    var floor = false;

//  search for existing site
    for(var j=0,k=sites.length;j<k;j++) {
        if(sites[j].name == row.site) {
            site = j;
            break;
        }
    }

    if(site === false) {
        site = sites.length;
        sites[site] = {
            name: row.site,
            buildings: []
        };
    }

//  search for existing building
    for(var j=0,k=sites[site].buildings.length;j<k;j++) {
        if(sites[site].buildings[j].name == row.building) {
            building = j;
            break;
        }
    }

    if(building === false) {
        building = sites[site].buildings.length;
        sites[site].buildings[building] = {
            name: row.building,
            floors: []
        };
    }

//  search for existing floor
    for(var j=0,k=sites[site].buildings[building].floors.length;j<k;j++) {
        if(sites[site].buildings[building].floors[j] == row.floor) {
            floor = j;
            break;
        }
    }

    if(floor === false) {
        floor = sites[site].buildings[building].floors.length;
        sites[site].buildings[building].floors[floor] = row.floor;
    }
}

Resulting Structure:
var sites = [
    {
        "name":"liverpool",
        "buildings":[
            {
                "name":"building a",
                "floors":[
                    "0",
                    "1"
                ]
            },
            {
                "name":"building b",
                "floors":[
                    "0"
                ]
            }
        ]
    }
];

Use it:
var liverpool = sites[0];
var building_b = liverpool.buildings[1];

There are probably better ways of doing it though.


text:
Q: Moving Camera on X axis glm::lookat() I'm trying to make a 2D camera on OpenGl using the function glm::lookat(). The problem is that once everything is rendered, I can't move the camera. I'm only trying to move it on an horizontal way.
glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(this->Width), static_cast<GLfloat>(this->Height), 0.0f, 0.1f, 500.0f);
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);

A: glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);
So, something like:
void Update()
{
  static glm::vec3 cameraPos(0,0,-1);

  cameraPos.x += 0.1f;

  ... etc
}

(Though, I'd suggest creating a Camera class, or at least storing the vec3 outside of this method, for anything beyond experimentation.) Everything else should work fine.
Typically, you'd also want to take into account the time difference between frames. There are many ways to measure this - whatever gl framework you're using probably provides a function for it - but you're probably running at 60Hz, so assume the time between frames is 16.6ms.  In which case, you might
float velocity = 10; // units per second
glm::vec3 cameraPos(0,0,-3);
float deltaT = 16.6e-3f; // 16 milliseconds

void Update()
{
  cameraPos.x += velocity * deltaT;
  glm::lookAt(cameraPos, .....);
}

You might run into a situation where everything renders the first frame, then disappears. In that case, drop the velocity to zero to make sure everything is working as it was before, then try some really small velocity values (like 0.001). It depends on how big your geometry is, distance from camera, and a bunch of other stuff. A camera Z of -3 is pretty small, might try backing it off some more while you're working this out.
Good luck!


text:
Q: Android Widget button service does not respond to click Similar questions: service not starting on oreo in app widgetusing The closest to my question is Widget freezes after some time but is unanswered.
I have a simple widget button that should send a notification when pressed. It doesn't work when:

*

*I clear the app from recents just after opening the app on install

*randomly stops working sometimes (sometimes all the clicks are triggered together after I open the app again leading to a bunch of notifications getting fired together.)

From what all I have read so far, it looks to me as if the PendingIntent is getting cleared.
The code is mostly taken from the official app widget guide except for starting a Service instead of Activity.
WidgetProvider:
public class WidgetProvider extends AppWidgetProvider {

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        for (int appWidgetId : appWidgetIds) {
            Intent myIntent = new Intent(context, WidgetService.class);
            myIntent .setAction("SOME_UNIQUE_ACTION");
            PendingIntent pendingIntent = PendingIntent.getForegroundService(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
            views.setOnClickPendingIntent(R.id.button, pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}

WidgetService:
public class WidgetService extends JobIntentService {

    public WidgetService() {
        super();
    }

    @Override
    protected void onHandleWork(@Nullable Intent i) {
        Utils.sendNotification(); // this method works and is tested
    }
}

I tried both answers from here, Broadcast method didn't work and looked indirect as well, so I added #onCreate implementation to call startForeground, which didn't work either.
@Override
    public void onCreate() {
        super.onCreate();

        Utils.sendNotification();
        try {
            startForeground(1, notification);
        } catch (Error e) {
            Log.i(TAG, e.toString());
        }
    }
}

How do I get a button that will start a service reliably every time? Any help appreciated.


text:
Q: Selecting columns of a pandas dataframe based on criteria I have a DF which contains results from the UK election results with one column per party. So the DF is something like:
In[107]: Results.columns
Out[107]:
Index(['Press Association ID Number', 'Constituency Name', 'Region', 'Country',
       'Constituency ID', 'Constituency Type', 'Election Year', 'Electorate',
       ' Total number of valid votes counted ', 'Unnamed: 9',
       ...
       'Wessex Reg', 'Whig', 'Wigan', 'Worth', 'WP', 'WRP', 'WVPTFP', 'Yorks',
       'Young', 'Zeb'],
      dtype='object', length=147)

e.g.
Results.head(2)
Out[108]:
   Press Association ID Number Constituency Name Region Country  \
0                            1          Aberavon  Wales   Wales
1                            2         Aberconwy  Wales   Wales

  Constituency ID Constituency Type  Election Year Electorate  \
0       W07000049            County           2015     49,821
1       W07000058            County           2015     45,525

   Total number of valid votes counted   Unnamed: 9 ...   Wessex Reg  Whig  \
0                                31,523         NaN ...          NaN   NaN
1                                30,148         NaN ...          NaN   NaN

   Wigan  Worth  WP  WRP  WVPTFP  Yorks  Young  Zeb
0    NaN    NaN NaN  NaN     NaN    NaN    NaN  NaN
1    NaN    NaN NaN  NaN     NaN    NaN    NaN  NaN

[2 rows x 147 columns]

The columns containing the votes for the different parties are Results.ix[:, 'Unnamed: 9':]
Most of these parties poll very few votes in any constituency, and so I would like to exclude them. Is there a way (short of iterating through each row and column myself) of returning only those columns which meet a particular condition, for example having at least one value > 1000? I would ideally like to be able to specify something like
    Results.ix[:, 'Unnamed: 9': > 1000]

A: you can do it this way:
In [94]: df
Out[94]:
          a         b         c         d           e         f         g           h
0 -1.450976 -1.361099 -0.411566  0.955718   99.882051 -1.166773 -0.468792  100.333169
1  0.049437 -0.169827  0.692466 -1.441196    0.446337 -2.134966 -0.407058   -0.251068
2 -0.084493 -2.145212 -0.634506  0.697951  101.279115 -0.442328 -0.470583   99.392245
3 -1.604788 -1.136284 -0.680803 -0.196149    2.224444 -0.117834 -0.299730   -0.098353
4 -0.751079 -0.732554  1.235118 -0.427149   99.899120  1.742388 -1.636730   99.822745
5  0.955484 -0.261814 -0.272451  1.039296    0.778508 -2.591915 -0.116368   -0.122376
6  0.395136 -1.155138 -0.065242 -0.519787  100.446026  1.584397  0.448349   99.831206
7 -0.691550  0.052180  0.827145  1.531527   -0.240848  1.832925 -0.801922   -0.298888
8 -0.673087 -0.791235 -1.475404  2.232781  101.521333 -0.424294  0.088186   99.553973
9  1.648968 -1.129342 -1.373288 -2.683352    0.598885  0.306705 -1.742007   -0.161067

In [95]: df[df.loc[:, 'e':].columns[(df.loc[:, 'e':] > 50).any()]]
Out[95]:
            e           h
0   99.882051  100.333169
1    0.446337   -0.251068
2  101.279115   99.392245
3    2.224444   -0.098353
4   99.899120   99.822745
5    0.778508   -0.122376
6  100.446026   99.831206
7   -0.240848   -0.298888
8  101.521333   99.553973
9    0.598885   -0.161067

Explanation:
In [96]: (df.loc[:, 'e':] > 50).any()
Out[96]:
e     True
f    False
g    False
h     True
dtype: bool

In [97]: df.loc[:, 'e':].columns
Out[97]: Index(['e', 'f', 'g', 'h'], dtype='object')

In [98]: df.loc[:, 'e':].columns[(df.loc[:, 'e':] > 50).any()]
Out[98]: Index(['e', 'h'], dtype='object')

Setup:
In [99]: df = pd.DataFrame(np.random.randn(10, 8), columns=list('abcdefgh'))

In [100]: df.loc[::2, list('eh')] += 100

UPDATE:
starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.


text:
Q: How to check whether two properties objects overlaps or not in java? I've two properties, property1 and property2
 Properties properties1 = new Properties();
 Properties properties2 = new Properties();

 properties1.put("A", "Apple");
 properties1.put("B", "Ball");

 properties2.put("A", "Apple");
 properties2.put("C", "Cat");

How can we check whether the key in properties1 overlaps on key in properties2

A: Properties derives from HashTable, so from Map too.
As with a Map you can use properties1.entrySet() to iterate all entries and
then for each entry you can check if it is contained in properties2 by looking first if the key is contained and if it is contained you can compare the values:
    for (Entry<Object, Object> entry : properties1.entrySet()) {
        Object currentKey = entry.getKey();
        boolean isContained = properties2.containsKey(currentKey);
        if (isContained && entry.getValue().equals(properties2.get(currentKey))) {
            System.out.println("property equals for " + entry);
        }
    }

A: You may look for the intersection of both property names sets, then check which values differ :
Set<String> names1 = properties1.stringPropertyNames();
Set<String> names2 = properties2.stringPropertyNames();
names1.retainAll(names2); // after this line, names1 contains only common elements

// let's see which elements have different values
for(String str : names1){
    if(!properties1.getProperty(str).equals(properties2.getProperty(str))){
        System.out.println("Property "+str+" overlapping");
    }
}

A: Properties extends Hashtable, so you can find the keys present in both objects using set intersection:
Set<Object> intersection = new HashSet(properties1.keySet()).retainAll(properties2.keySet());
if(intersection.isEmpty()) {
    //no overlap
}

A: For instance, with Java 8 :
    // Returns overlapping entries (K, V)
    properties1.entrySet()
               .stream()
               .filter(entry -> entry.getValue().equals(properties2.get(entry.getKey())))
               .collect(Collectors.toList())
    );

A: You could chack the intersection between the two Properties objects entry sets:
Set<Entry<Object, Object>> intersection = new HashSet<>(properties1.entrySet());
intersection.retainAll(properties2.entrySet());

intersection will contain the common properties, with both key name and value.

A: You can do it iterating on all the entries (use the entrySet() method) and check if they exists in the other properties.
boolean overlapped = properties1.entrySet()
                                .stream()
                                .allMatch(e -> properties2.containsKey(e.getKey()) &&
                                     properties2.get(e.getKey()).equals(e.getValue()));


text:
Q: Bash - Replace one string in one with another string from another file I have two sorted text files. File A's data looks like this:
adam
humanities

antwon
sciences

bernard
economics

castiel
sciences

dmitri
informatics

zoe
mathematics

File B's data looks like this:
adamburnston
antwonreed
justbernard
castiel
dmitrivalchenkov
zoematthews

I need to replace the line in file A(adam), with the line in file B(adamburnston). Both the files are alphabetically arranged and contain the same number of entries. How do I achieve this result?
Expected output:
adamburnston
humanities

antwonreed
sciences

justbernard
economics

castiel
sciences

dmitrivalchenkov
informatics

zoematthews
mathematics

A: The following pipeline works:
sed '2~3!d' A | paste -d $'\n' B - | sed $'3~2i\n'

The first part tells GNU sed to print the second line, and then each third line. paste merges B with the output of the first sed, using a newline as the delimiter. The last line adds newlines after each pair of lines.

A: This awk should work:
awk 'FNR==NR{a[i++]=$0;next} NF>0{c++; if (c%2==0) print a[j++] ORS $0 ORS}' fileB fileA


text:
Q: SQL - Counting Number of Invoiced Years Per Customer to Get a Yearly Average of Sales I'm learning SQL and am stuck trying to solve an exercise. Hoping someone can give me some input.
I have a database with an invoice table and a customer table.
I'm trying to get the average sales per customer per year. So if Customer 1 had 4 years of Data I need his total sales / 4, Customer 2 had 6 years of data total sales / 6 and so on.
My issue is that a customer can have multiple invoices in a single year.
i.e. This customer has 4 years of Data but 3 invoices on 2010 and 2 invoices on 2012

I was able to COUNT the number of invoices per Year but I haven't been able to get a COUNT of the individual years that a customer appears in the data. I know what my issue is on the Sum Years field but can't think of a way to solve this. I am probably also over complicating my code.
 SELECT
    i.BillingCountry,
    c.CustomerId,
    strftime('%Y',i.InvoiceDate) AS Year,
    c.FirstName || " " || c.LastName AS [Customer Name],
    COUNT(strftime('%Y',i.InvoiceDate)) AS NumberYears,
    COUNT(c.CustomerId) AS [Sum Years],
    ROUND(SUM(i.Total)/COUNT(strftime('%Y',i.InvoiceDate)),2) AS [Average]
FROM
    invoices AS i
INNER JOIN
    customers AS c
ON
    i.CustomerId = c.CustomerId
WHERE
c.CustomerId = 1
GROUP BY
    c.CustomerId,
    Year
ORDER BY
c.CustomerId

Here is my result:

These are two samples of the tables I'm working with:
Customers:

Invoices:


text:
Q: Write to textfile using input type text i have a little problem that i am trying to solve. Well i have a cart there a user can type in how many goods it wants to buy. But the problem is when the user types in for example "2" i want it to write to the text file the name of the goods meat meat for example, and not the number 2. I have an array there i store the good, price and so on.
here is the array i store:
$filename="shop.txt";
$lines = array();
$file = fopen($filename, "r");

while(!feof($file)) {

//read file line by line into a new array element
$lines[] = fgets($file, 4096);

}
fclose ($file);

I got five forms for each good to input.

Meat:   <input type="text" name="cb4" value=""><br>
        <input type="submit" value="Submit">
</form>

This is where i got a for loop that checks the form and writes to textfile.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $result_string = '';
        foreach($_POST as $item) {

            $result_string .= $item."\n";
            $counter++;

        }
        file_put_contents('kundvagn.txt', $result_string , FILE_APPEND);

    }

If i input 2 in the meat goods, the output is now:
Your shopping cart contains the following:
2
You got total of: 1 goods in your shoppingcart

A: This should load the lines - no output to browser must happen before session_start(); The counter is incremented at the top of the loop so that it will start at 1
<?php session_start(); ?>

 <?php
 $filename="shop.txt";
 $_SESSION['lines'] = array();
 $file = fopen($filename, "r");
 $counter = 0;
 while(!feof($file)) {
 $counter++;
 //read file line by line into a new array element
 $_SESSION['lines'][$counter] = fgets($file, 500);

 }
 fclose ($file);

 ?>

This should also break up the file into an array without the loop
    $file = fread($file, filesize($file)); // Get file contents
    $_SESSION['list'] = explode ("\n", $file); // Split all the rows

You may need to have a blank line at the top of your file to occupy position 0.
And this should get them out
 <?php session_start(); ?>

 <?php
 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $result_string = '';
         foreach($_POST as $item) {

             $result_string .= $_SESSION['list'][$item] . "\n";
             $counter++;

         }
         file_put_contents('kundvagn.txt', $result_string , FILE_APPEND);

     }
 ?>

This is a good description of how to use sessions:
http://www.w3schools.com/php/php_sessions.asp
This shows another method of getting the lines from the file - effectively it is already an array if it is read into a variable - it can then be split by the linefeeds.
Parse txt files and turn them into static html files
If they are putting the quantity in the box and not the item number they want then this should work
  <?php
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $result_string = '';
          foreach($_POST as $item) {

          $result_string .= $item . " " . $_SESSION['list'][$counter] . "\n";
          $counter++;

          }
          file_put_contents('kundvagn.txt', $result_string , FILE_APPEND);

      }
  ?>

This will record even those with no text entry so you would need to think about cutting out the "0" ones:
 // only list items greater than 0
 if($item > 0){
     $result_string .= $item . " " . $_SESSION['list'][$counter] . "\n";
 }

As far as I can see the counter should be counting each POST item submitted whether it is set or not. I have not been able to check that.
You would need to put the loading counter at the bottom of the loading loop - this was put above before, on the assumption that there would be no item value "0" so there could be no array position "0" that would be relevant - other than if you wanted a message to say "You didn't pick.....". If you use the explode method that will tally OK and is probably the most efficient method anyway. You may also need to check that your POST array is in the order you expect it to be.
This might be handy for exploring your POST array:
Print $_POST variable name along with value


text:
Q: Let $V$ be a vector space over $\mathbb{C}$ and let $T: V \rightarrow V$ be a linear transformation such that $W \subset V$ is an invariant subspace. Let $V$ be a vector space over $\mathbb{C}$ and let $T: V \rightarrow V$ be a linear transformation such that $W \subset V$ is an invariant subspace.
Prove that there exists $\lambda$ an eigenvalues of $T$ and $v\notin W$ such that $(T- \lambda I)v \in W$.
I have been stuck with this exercise for hours, I thought about using minimal polynomials or to think about Jordans's form because it's what I'm learning but it didn't help.
I would be glad if you can give me a hint or a direction how to solve.
Thank you!

A: Expansion of my comment/question above.
$W$ is invariant under $T$ implies, it induces a linear map $T':V/W\to V/W$. One is of course assuming that $W\neq V$, so $V/W\neq 0$ and thus $T'$ must have an eigen vector $v'\in V/W$ with $T'(v')=\lambda v'$. Lift everything to $V$, so if $v$ lifts $v'$, one has $v\not\in W$, $T(v)-\lambda v\in W$.

A: I assume $V$ is of finite dimension over $\Bbb C$:
$\dim_{\Bbb C} V < \infty. \tag 0$
Since $W$ is an invariant subspace of $T$,
$T(W) \subseteq W, \tag 1$
the linear transformation $T$ factors through to a linear transformation $\tilde T$ defined on the quotient vector space $V/W$:
$\tilde T: V/W \to V/W \tag 2$
given by
$\tilde T(v + W) = T(v) + W; \tag 3$
$\tilde T$ is well-defined and depends only on the coset $v + W$, for
$v_1 + W = v_2 + W \Longleftrightarrow v_1 - v_2 \in W, \tag 4$
which implies via (1)
$T(v_1) - T(v_2) = T(v_1 - v_2) \in W, \tag 5$
and thus
$T(v_1) + W = T(v_2) + W, \tag 6$
that is
$\tilde T(v_1 + W) = \tilde T(v_2 + W) \tag 7$
and thus we see that $\tilde T$ is well-defined.  In light of (0),
$\dim_{\Bbb C} V/W < \infty, \tag 8$
and thus in the usual manner we infer that there exists some
$\lambda \in \Bbb C \tag 9$
and
$v \in V \setminus W \tag{10}$
with
$(\tilde T - \lambda I)(v + W) = 0 \in V/W; \tag{11}$
thus,
$(T - \lambda I)v + W = (\tilde T - \lambda I)(v + W) = 0 \in V/W, \tag{12}$
and therefore
$(T - \lambda I)v \in W; \tag{13}$
finally,
$v \notin W \tag{14}$
as indicated by (10).


text:
Q: How to use Immutable.js with Redux and TypeScript? I am trying to change my state-object to an immutable Immutable.js object, but I'm having big troubles with the type definitions. I tried to find similar issues on the net but couldn't really find anything helpful.
I have the following state which I want to convert into an Immmutable object.
export interface PostState {
  ids: number[];
  entities: { [id: number]: Post};
  loading: boolean;
  error: string;
};

export interface Post {
  id: number;
  comments: {
    ids: number[];
    loading: boolean;
  }
};

Any suggestions? How should I define these interfaces to ensure immutability with Immutable.js?

A:
which I want to convert into an Immmutable object.

Basic
The two great JavaScript structures are : Object (used as a Dictionary also called HashMap also called Map) and Array (also called List etc).
Samples
In your state you have one Map:
entities: { [id: number]: Post};

And A few Arrays e.g.
ids: number[];

Conversion
For Map, Immutable has its own Structure : https://facebook.github.io/immutable-js/docs/#/Map
For List there is : https://facebook.github.io/immutable-js/docs/#/List
Declaration
Exactly what you would expect e.g. for List:
ids: number[]; -> ids: List<number>


text:
Q: .NET Core - Apply Multiple Constructor Discovery Rules in Implementation Factory I am working with c# and .NET Core 3.1, and I have a class that looks like this.
public class MyClass : IMyClass
{
    public MyClass()
    {
        …
    }

    public MyClass(IDependency dependency)
    {
        …
    }

    public MyClass(string appSettings)
    {
        …
    }
    …
}

So I know that with Dependency Injection, you can add services like this:
services
    .AddScoped<IDependency, Dependency>()
    .AddScoped<IMyClass, MyClass>();

and the Service Provider has rules (See https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#multiple-constructor-discovery-rules) to select the constructor based on which has the most arguments registered (In this case, MyClass(IDependency dependency)).
I have a specific case though, where, if a setting is found in configuration and valid, I want to use the third constructor. I planned to do that with something like this
services
    .AddScoped<IDependency, Dependency>()
    .AddScoped<IMyClass>(s =>
    {
        if(<insert config read and validation here>)
        {
            return new MyClass(appSetting);
        }
        else
        {
            //apply default rules to get MyClass
        }
    }

The problem is I can't figure out a clean way to apply the default rules within an implementation factory. Does anyone know of a clean way to do this?
I've tried using ActivatorUtilities.CreateInstance, passing in just the ServiceProviders, but that seems to prioritize the first matching constructor, regardless of available registered dependencies (In this case MyClass()).
I also tried using services.AddScoped<IMyClass, MyClass>(); and the implementation factory combined, calling s.GetRequiredService<IMyClass>() in the else block, but that just results in an infinite loop of the implementation factory trying to resolve itself.


text:
Q: How to change first value in list of two lists I would like to know how to change the first value of such list:
[100][TimeStamp]
 [200][Timestamp]
 [300][Timestamp]
       etc
My code for now looks like this:
bitrateList = []
for x in range(SCANTIME):
    stop = time.time() + 1
    while (time.time()<stop):
        totalSize += len(sock.recv(bufferUDP))
    bitrateList.append([[totalSize], [time.ctime()]])
    print(bitrateList[x])
    totalSize = 0

for x in range(len(bitrateList)):
    for y in range(1):
        bitrateList[x][y] = bitrateList[x][y]*8
        print(bitrateList[x][y])

However accessing to first element of each row as I did results in this:
https://imgur.com/9TGHe0O
How can should I change referring to first element of each row in my list in order to look like this?
[800][TimeStamp]
 [1600][Timestamp]
 [2100][Timestamp]
       etc

A: bitrateList[x][y] when x = 0 and y = 0 is [100] not 100. So when you multiply [100] by 8, due to operator overloading you get = [100,100,100,100,100,100,100,100]. You need to access the first element of that list. So, try this:
bitrateList = []
for x in range(SCANTIME):
    stop = time.time() + 1
    while (time.time()<stop):
        totalSize += len(sock.recv(bufferUDP))
    bitrateList.append([[totalSize], [time.ctime()]])
    print(bitrateList[x])
    totalSize = 0

for x in range(len(bitrateList)):
    bitrateList[x][0][0] = bitrateList[x][0][0]*8
    print(bitrateList[x][0])


text:
Q: How to show the output for the execution for any command and/or script in stdout and file but keeping the color in the stdout? For some commands, in the terminal they print with some colors in the stdout, for example:
git status
mvn help:help -Ddetail=true
gradle build
Any Linux command (ls [-...], etc)

Note: it applies for scripts that contain:

*

*Executions of Linux commands

*Executions for tools commands

*Executions other scripts

Therefore the following is possible:
./mvnw help:help -Ddetail=true
./gradlew build
./customscript.sh

Until nothing is new and all work how is expected, therefore:

*

*linux_command

*tool_command (maven, git, gradle etc)

*script.sh (execute linux/tools commands and other scripts)

So if any of them print in the terminal (stdout) some colors, it is the default behavior according each command/tool
Now if I want see the output in the terminal (as above) and write it to some file, according with:

*

*How to redirect output to a file and stdout
Therefore is possible do in general
"linux_command" | tee [-a] "/some/path/log_file.log"
"tool_command"  | tee [-a] "/some/path/log_file.log"
"script.sh"     | tee [-a] "/some/path/log_file.log"

And it works how is expected, but the output in the terminal (stdout) does not include the colors anymore.
Question:

*

*How to show the output for the execution for any command and/or script in stdout and file but keeping the color in the stdout?

Same behaviour when the pipe and tee were not included and of course meanwhile write the content in the .log file.
Note I did do a research about the script command

*

*How to trick an application into thinking its stdout is a terminal, not a pipe
but it overrides the script.sh content
I need a general approach, it for any command and/or script.sh

A: unbuffer is your command
 unbuffer git status | tee   => I keep my color
 git status | tee   => back in no-color world
You can have  :

*

*on Debian/Ubuntu  with expect package

*on Fedora with expect package

*On MacOS with brew.sh       expect package

*On MacOS with macports.org  expect package

Source of expect package is https://core.tcl-lang.org/expect/index
FYI , if your problem is only limited to Git ,
Git has a flag to force color .
git -c status.color=always status


text:
Q: Finding ip address - python's socket module code
import socket
line = 'http://www.permobil.com/en/Corporate/'
IP = socket.gethostbyname(line)

error
IP = socket.gethostbyname(line)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

I know there are several answers for the same error, but none helped
i looked 1 2
while others answers were not applicable.

A: try this:
import socket

ip = socket.gethostbyname("permobil.com")
print ip

A: import socket
from urlparse import urlparse

parsed_uri = urlparse('http://www.permobil.com/en/Corporate/' )
domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
domain = domain.replace("http://","")
domain = domain.replace("www.", "")
domain = domain.replace("/", "")
IP = socket.gethostbyname(domain)


text:
Q: What is the name of the texture pack featured in "20 Things You Didn't Know About Minecraft"? I saw a video by marosells, "20 Things You Didn't Know About Minecraft", and I've been looking for the name of the texture pack used in it since then: it's like the regular texture pack, but way improved.
What is the name of the texture pack?

A: It's the Faithful 32x32 pack by Vattic, which, as its name implies, is an attempt at a "faithful" higher-resolution recreation of the default texture pack.


text:
Q: Compact map of a closed convex set Question: $X$ is a $B^*$ space and $C$ is a closed convex set of $X$. Let $T: C\to C$ be a compact map (defined below). Prove that $T(C)$ is sequentially pre-compact (That is, any sequence in $T(C)$ has a Cauchy subsequence).
(The real goal is to show that $T$ has a fixed point in $C$, but showing $T(C)$ is sequentially pre-compact is good enough because of Schauder's fixed point theorem)
Compact map: Given $X$ a $B^*$ space and $E \subset X$, Let $T:E \to X$. We call $T$ a compact map if $T$ is continuous and for all $K\subset E$ with $K$ bounded, we have that $T(K)$ is sequentially compact. (That is, every sequence in $T(K)$ has a convergent subsequence with limits in $T(K)$.).
My attempt: If $C$ has only one element there is nothing to prove. So assume there are at least two element in $C$. I am able to show that the following is true,
$$\Lambda =  \bigcup_{\substack{K \subseteq C\\ K \text{ bounded}}}K = C$$
(The forward inclusion is trivial. For the reverse inclusion, if we assume $x \in C\setminus\Lambda$, since there is some other $y$ also in $C$; we can look at the convex hull of $\{x,y\} \subseteq C$ which is totally bounded and therefore bounded and thus is $\subseteq \Lambda$, which puts $x\in \Lambda$ which is a contradiction!)
This also gives me
$$T(C) = \bigcup_{\substack{K \subseteq C\\ K \text{ bounded}}} T(K)$$
But I am sort of lost here trying to show that any sequence in $T(C)$ has a Cauchy subsequence. Intuitively, since the union is arbitrary, it seems to me that it should be possible to create a sequence such that for any $N \in \mathbb{N}$ and for any $K \subseteq C$ bounded, there is some $k > N$ such that $x_k \not\in T(K)$.
Correction/Edit: The question (which originally appeared in my homework set) has been updated to include the additional hypothesis that $C$ is bounded.
My solution: Now the entire question is trivial since we have the bounded subset $C\subseteq C$ such that $T(C)$ is sequentially compact. Finally, in order to use Schauder's fixed point theorem, we need the set to be complete; but this is achieved easily. First we notice that the sequential compactness of $T(C)$ ensures the compact-ness of $T(C)$. So if we consider a Cauchy sequence $\{x_k\} \subset C$ that doesn't coverge in $C$, by the continuity of $T$, we obtain a Cauchy sequence $\{T(x_k)\} \subset T(C)$ that does not converge in $T(C)$ - but this contradicts the compactness of $T(C)$! So, $C$ is complete and we can use Schauder; and so we win!
Further question: I am still curious to know if the statement still holds if we remove the bounded assumption on $C$. According to the answer by @Kavi Rama Murthy, it does look like we don't always have sequential pre-compactness of $T(C)$ in this case; but the question about the fixed point itself remains elusive (as noted in my reply comment).

A: The definition of a compact map has been revised after I posted this answer.
$T(C)$ need not be sequentially compact: Let $C=X$ and $Tx=f(x)x_0$ where $x_0$ is a fixed nonzero elmeent of $X$ and $f$ is a fixed non-zero continuous linear functional on $X$. Then the hypothesis is satisfed but $T(C)$ is the span of $x_0$ which is not pre-compact.
Take $X=C=\mathbb R$ and $Tx=x+1$ to see that $T$ may not have any fixed point.


text:
Q: Bootstrap 3 Form in Zf2 How can i use Bootstrap 3 in Zend Framework 2.2.4?
I mean the textfields or textareas. https://bitbucket.org/dlu/dlutwbootstrap doesn't work :(. At the Internet i found this Snippet but it doesn't work, too.
$formRenderer = $this->formRenderer($form, 'renderer.bootstrap', 'horizontal');

-> http://reverseform.modo.si/form/test-bootstrap

A: To be a little more specific than the "just add form-control" solutions, here is the syntax to set the class for any given Zend form element (Element\Text, etc):
$element->setAttribute('class', 'form-control');
I would have put this in a comment but I don't have the reputation yet. Yay StackOverflow!

A: ok i have found the solution by self.
Just add the Class form-control to a form field.

A: If you are looking for something better than just adding form-control perhaps look at:
https://github.com/neilime/zf2-twb-bundle
I've been using it recently and for the most part it is working great. It is also actively maintained unlike dlutwbootstrap.