text:
Q: VueJS2 with Cesium: Uncaught typeError: Cannot read property 'viewer' of undefined using ScreenSpaceEventHandler I'm constructing a globe with Cesium and using VueJS. One of my components looks as the code below. This component is added to the App.vue. The globe is working perfectly and displaying all the primitives great.
Now I would like to add some Cesium ScreenSpaceEventHandlers to the viewer as you can see in the code however. The screenSpaceEventHandler concerning the LEFT CLICK, is giving me the error below when I click it. The error made me believe that the viewer is nog yet defined, however, this is strange as the viewer is already working, as I can tell by rectangles and rectangleoutlines being drawn with no problem and also using the viewer data by calling his.viewer many times(maybe not visible in the code below).
I hope if someone looks at the code below they can see what I am missing here. I simply call the viewer data by saying "this.viewer…". however it "cannot read property 'viewer' of undefined. The error happens at one of the last lines of the code below: "let pickedFeature = this.viewer.scene.pick(movement.position);". Clearly I cannot use this.viewer here, I just don't understand why not, and why it would be undefined? What can I do :slight_smile:
I hope someone can help me out with this. Thank you.
ERROR
Which indicates to me that the viewer is working fine. However I run into the error with the following stack trace:

Uncaught TypeError: Cannot read property 'viewer' of undefined at
onLeftClick (Globe.vue?c172:419) at cancelMouseEvent
(ScreenSpaceEventHandler.js?1863:295) at handleMouseUp
(ScreenSpaceEventHandler.js?1863:317) at handlePointerUp
(ScreenSpaceEventHandler.js?1863:867) at HTMLCanvasElement.listener
(ScreenSpaceEventHandler.js?1863:54)

CODE
<template>

</template>

import * as Cesium from "cesium";

export default {
  name: "Globe",
  data: function () {
        return {
            viewer : undefined,
            terrainProviderViewModels : [],
            selectedTerrainProviderViewModel : undefined,
            imageryProviderViewModels : [],
            selectedImageryProviderViewModel : undefined,
        }
    },
    mounted: function () {
    window.CESIUM_BASE_URL = "/cesium/"
    this.drawGlobe();
    },
   methods: {
    async drawGlobe() {
      try{
        this.terrainProviderViewModels.push(await this.getTerrainViewModels());
        this.selectedTerrainProviderViewModel = await this.assignTerrainProviderViewModel();
        this.imageryProviderViewModels.push(await this.getImageryModels());
        this.selectedImageryProviderViewModel = await this.assignImageryModels();
        this.viewer = await this.createViewer();
        await this.drawCells();

      } catch(e) {
        console.log("Failed to draw globe: " + e);
      }
    },
        async getTerrainViewModels() {
            // some code to get terrain view models
        },

        async assignTerrainProviderViewModel() {
            // some code to get terrain provider view models
        },
        async getImageryModels() {
            // some code to get imagery models
        },
        async assignImageryModels() {
            // some code to assign current imagery models
        },
        async createViewer() {
            // creating  a viewer
        },
        async drawCells() {
            await this.createRectangleInstancesAndRectangleOutlineInstances();
            await this.createPrimitives();
            await this.addPrimitivesToViewer();
            await this.addEvents();
        },
        async createRectangleInstancesAndRectangleOutlineInstances() {
            // some code to create rectangleInstances
        },
        async createPrimitives() {
            // some code to create primitives
        },
        async addPrimitivesToViewer() {
            // some code to add primitives to viewer
        },
        async addEvents() {
            try{
                this.viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
                    let pickedFeature = this.viewer.scene.pick(movement.position);
                    // .... some more code
                },Cesium.ScreenSpaceEventType.LEFT_CLICK);
            }catch(e) {
                console.log(e);
            }
        }
   }
}

A: I have added the code from the addEvents() method to the createViewer() method where the viewer is created. I expected viewer to be some sort of object, however it shows as an unknown component. So perhaps this is why this.viewer does not work? Anyway, it works now.

A: I had to check for:
viewer?.isDestroyed()

This worked for me:
if (!viewer?.isDestroyed() && viewer?.screenSpaceEventHandler) {
      viewer.screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_CLICK);
    }


text:
Q: Total/Average/Changing Salary 1,2,3,4 Menu Change your program so there is a main menu for the manager to select from with four options:

*

*Print the total weekly salaries bill.

*Print the average salary.

*Change a player's salary.

*Quit

When I run the program, I enter the number 1 and the program stops. How do I link it to the 4 below programs?
Program:
Chelsea_Salaries_2014 = {'Jose Mourinho':[53, 163500, 'Unknown']}
Chelsea_Salaries_2014['Eden Hazard']=[22, 185000, 'June 2017']
Chelsea_Salaries_2014['Fernando Torres']=[29, 175000, 'June 2016']
Chelsea_Salaries_2014['John Terry']=[32, 175000, 'June 2015']
Chelsea_Salaries_2014['Frank Lampard']=[35, 125000, 'June 2014']
Chelsea_Salaries_2014['Ashley Cole']=[32, 120000, 'June 2014']
Chelsea_Salaries_2014['Petr Cech']=[31, 100000, 'June 2016']
Chelsea_Salaries_2014['Gary Cahill']=[27, 80000, 'June 2017']
Chelsea_Salaries_2014['David Luiz']=[26, 75000, 'June 2017']
Chelsea_Salaries_2014['John Obi Mikel']=[26, 75000, 'June 2017']
Chelsea_Salaries_2014['Nemanja Matic']=[25, 75000, 'June 2019']
Chelsea_Salaries_2014['Marco Van Ginkel']=[20, 30000, 'June 2018']
Chelsea_Salaries_2014['Ramires']=[26, 60000, 'June 2017']
Chelsea_Salaries_2014['Oscar']=[21, 67500, 'June 2017']
Chelsea_Salaries_2014['Lucas Piazon']=[19, 15000, 'June 2017']
Chelsea_Salaries_2014['Ryan Bertrand']=[23, 35000, 'June 2017']
Chelsea_Salaries_2014['Marko Marin']=[27, 35000, 'June 2017']
Chelsea_Salaries_2014['Cesar Azpilicueta']=[23, 55000, 'June 2017']
Chelsea_Salaries_2014['Branislav Ivanovic']=[29, 67500, 'June 2016']
Chelsea_Salaries_2014['Ross Turnbull']=[22, 17000, 'June 2017']
Chelsea_Salaries_2014['Demba Ba']=[28, 65000, 'June 2016']
Chelsea_Salaries_2014['Oriol Romeu']=[22, 15000, 'June 2015']

user_input = (int('Welcome! What would you like to do? 1: Print the total salaries bill. 2: Print the average salary. 3: Change a players salary. 4: Quit. '))

if user_input == 1:
    print(sum(i[1] for i in Chelsea_Salaries_2014.values()))
else:
    if user_input == 2:
       print(sum(i[1] for i in Chelsea_Salaries_2014.values()))/len(Chelsea_Salaries_2014)
    else:
        if user_input == 3:
            def change_salary(Chelsea_Salaries_2014):
                search_input = input('What player would you like to search for? ')
                print('His Current Salary is £{0:,}'.format(Chelsea_Salaries_2014[search_input][1]))
                new_salary = int(input('What would you like to change his salary to? '))
            if new_salary <= 200000:
                Chelsea_Salaries_2014[search_input][1] = new_salary
                print('Salary has been changed to £{0:,}'.format(new_salary))
            else:
                print('This salary is ridiculous!')

            while True:
                change_salary(Chelsea_Salaries_2014)
                choice = input("Go again? y/n ")
                if choice.lower() in ('n', 'no'):
                        break
        else:
            if user_input == 4:
                print('Goodbye!')

A: Put the raw input in a while.
 while True:
 user_input = raw_input("Welcome!...")
 if user_input == 1:
  ...
 elif user_unput == 2:
  ...
 else:
  print "this salary is ridic..."

After completing a 1,2,3... input ask the user if they would like to do something else y/n, if n: break, this will end the loop. If y, the loop begins again and asks for another user input.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using await keyword to implement co-routines for game scripts I am attempting to implement co-routines in C# in order to make my life easier when it comes to scripting enemy behavior in my game. The game is fixed framerate. What would be an ideal syntax for writing the scripts would be:
wait(60)
while(true)
{
  shootAtPlayer();
  wait(30);
}

Which means wait 60 frames, shoot at player, wait 30, shoot at player, wait 30... e.t.c.
I have sort of implemented this solution using yield return in C#:
public IEnumerable update()
{
  yield return 60;
  while(true)
  {
    shootAtPlayer();
    yield return 30;
  }
}

The caller keeps a stack of alive routines (0 on the IEnumerable counter) and sleeping routines ( > 0). Every frame the caller reduces the sleeping frame counter of each sleeping routine by 1 until one reaches 0. This routine is made alive again and continues execution until the next yield return. This works fine in most cases but it is annoying that the subroutine cannot be split up like below:
public IEnumerable update()
{
  yield return 60;
  while(true)
  {
    doSomeLogic()
    yield return 30;
  }
}

public IEnumerable doSomeLogic()
{
  somethingHappening();
  yield return 100;
  somethingElseHappens();
}

The above syntax is incorrect as yield return cannot be nested within another method meaning the execution state can only ever be maintained in a single method (the update() in this case). This is a limitation of the yield return statement and I couldn't really find a way to work around it.
I asked earlier how might it be possible to implement the desired behaviour using C# and it was mentioned that the await keyword might work well in this situation. I am trying to figure out now how to change the code to use await. Is it possible to nest awaits in called methods like I wanted to do with yield return? also how would I implement a counter using awaits? The caller of the routines would need to be in control of decrementing the waiting frames left for each waiting routine as it will be the one called once per frame. How would I go about implementing this?

A: I'm not sure if async/await are good for this, but it is definitely possible. I've created a small (well, at least I've tried to make it as small as possible) testing environment to illustrate possible approach. Let's start with a concept:
/// A simple frame-based game engine.
interface IGameEngine
{
    /// Proceed to next frame.
    void NextFrame();

    /// Await this to schedule action.
    /// <param name="framesToWait">Number of frames to wait.</param>
    /// <returns>Awaitable task.</returns>
    Task Wait(int framesToWait);
}

This should allow us to write complex game scripts this way:
static class Scripts
{
    public static async void AttackPlayer(IGameEngine g)
    {
        await g.Wait(60);
        while(true)
        {
            await DoSomeLogic(g);
            await g.Wait(30);
        }
    }

    private static async Task DoSomeLogic(IGameEngine g)
    {
        SomethingHappening();
        await g.Wait(10);
        SomethingElseHappens();
    }

    private static void ShootAtPlayer()
    {
        Console.WriteLine("Pew Pew!");
    }

    private static void SomethingHappening()
    {
        Console.WriteLine("Something happening!");
    }

    private static void SomethingElseHappens()
    {
        Console.WriteLine("SomethingElseHappens!");
    }
}

I'm going to use engine this way:
static void Main(string[] args)
{
    IGameEngine engine = new GameEngine();
    Scripts.AttackPlayer(engine);
    while(true)
    {
        engine.NextFrame();
        Thread.Sleep(100);
    }
}

Now we can get to implementation part. Of course you can implement a custom awaitable object, but I'll just rely on Task and TaskCompletionSource<T> (unfortunately, no non-generic version, so I'll just use TaskCompletionSource<object>):
class GameEngine : IGameEngine
{
    private int _frameCounter;
    private Dictionary<int, TaskCompletionSource<object>> _scheduledActions;

    public GameEngine()
    {
        _scheduledActions = new Dictionary<int, TaskCompletionSource<object>>();
    }

    public void NextFrame()
    {
        if(_frameCounter == int.MaxValue)
        {
            _frameCounter = 0;
        }
        else
        {
            ++_frameCounter;
        }
        TaskCompletionSource<object> completionSource;
        if(_scheduledActions.TryGetValue(_frameCounter, out completionSource))
        {
            Console.WriteLine("{0}: Current frame: {1}",
                Thread.CurrentThread.ManagedThreadId, _frameCounter);
            _scheduledActions.Remove(_frameCounter);
            completionSource.SetResult(null);
        }
        else
        {
            Console.WriteLine("{0}: Current frame: {1}, no events.",
                Thread.CurrentThread.ManagedThreadId, _frameCounter);
        }
    }

    public Task Wait(int framesToWait)
    {
        if(framesToWait < 0)
        {
            throw new ArgumentOutOfRangeException("framesToWait", "Should be non-negative.");
        }
        if(framesToWait == 0)
        {
            return Task.FromResult<object>(null);
        }
        long scheduledFrame = (long)_frameCounter + (long)framesToWait;
        if(scheduledFrame > int.MaxValue)
        {
            scheduledFrame -= int.MaxValue;
        }
        TaskCompletionSource<object> completionSource;
        if(!_scheduledActions.TryGetValue((int)scheduledFrame, out completionSource))
        {
            completionSource = new TaskCompletionSource<object>();
            _scheduledActions.Add((int)scheduledFrame, completionSource);
        }
        return completionSource.Task;
    }
}

Main ideas:

*

*Wait method creates a task, which completes when the specified frame is reached.

*I keep a dictionary of scheduled task and complete them as soon as required frame is reached.

Update: simplified code by removing unnecessary List<>.


text:
Q: How to replace a string in a column with REGEX I have a table which references mobile numbers, but they are not all in international format. In the mobile column, I have many records and I need to change just all records with a 1 as first char to 491 and leave the rest unchanged. I tried this:
UPDATE test
SET mobile=(REPLACE (mobile,'1','491'));

But it turns a number like 1512231178 to 4915122349149178. It should be 491512231178. I think I need something like REGEXP '^1' in the REPLACE.
How can I do this with a simple update?

A: You can simply do like this:
UPDATE test SET mobile = '49' + mobile
where mobile like '1%'

A: Giorgi Nakeuri's clever problem substitution (prefixing for replacement) will work for your particular example. In other cases, where it is impossible to simplify the problem in such a way, you could use the INSERT string function, which does almost exactly what you want: replaces a substring of a specific length at a specific position with another substring. It does not allow you to also specify that the old substring match a specific value but you could use a WHERE clause for that, as Giorgi did:
UPDATE
  test
SET
  mobile = INSERT(mobile, 1, 1, '491')
WHERE
  mobile LIKE '1%'
;

If you needed to parametrise both the old and the new substring, this is how you could go about it:
UPDATE
  test
SET
  mobile = INSERT(mobile, 1, LENGTH(@OldValue), @NewValue)
WHERE
  mobile LIKE CONCAT(@OldValue, '%')
;


text:
Q: How to select the max event in a repetitive process? I have a process with repetitive events with an order, you can see an example in the table

User
Event
Date

XYZ
Event 1
2022-01-01

XYZ
Event 2
2022-01-02

XYZ
Event 3
2022-01-03

XYZ
Event 4
2022-01-04

XYZ
Event 3
2022-01-05

XYZ
Event 4
2022-01-06

I need to select those users that have been stuck in the second "event 3" (2022-01-05) but haven´t pass to the second "event 4". This is repetetive like I said before, it could be 3 "events 3" but I need to select the max "event 3" but for those users that their last evenet isn't "event 4"
Was using rank but didn't solve my problem and honestly don't know how to do it. Thanks in advance.

A: It is strange that you tried RANK and it didn't work. You should have shown your query. Maybe it is just a little mistake that would have been easy to correct. Or there is something essential about window functions that you have not understood and we could have explained.
You need each user's last row. You get this with RANK, DENSE_RANK, ROW_NUMBER or MAX(date) OVER.
select user
from
(
  select user, event, date, max(date) over (partition by user) as user_max_date
  from mytable
) with_max_date
where date = user_max_date
and event = 'Event 3';

A: Basicly we need to select users whose 'Event 3' is 1 less than 'Event 4', we can use a couple of linked subqueries.
select
    e3.user
from

    (select t.user, count(*) count_event
    from table t
    where t.event = 'Event 3'
    group by t.user, t.event) e3

    join (select t.user, count(*) count_event
    from table t
    where  t.event = 'Event 4'
    group by t.user, t.event) e4
      on e3.user = e4.user and e3.count_event = e4.count_event - 1


text:
Q: fstream never reaches eof I'm writing a translator for a lisp-like language.  The input file is read in token-by-token.  I'm controlling it with an std::fstream at the top level like this:
...
std::fstream fin(path, std::fstream::in);
symtable table; // aliased map<>

while (!fin.eof()) {
   try {
      std::cout << "file still has contents!" << std::endl;
      parse(fin, symbol_table);
   } catch (LexException le) {
      std::cout << le.what() << std::endl;
   } catch (ParseException pe) {
      std::cout << le.what() << std::endl;
   }
}

In my lexer, I handle leading whitespace and count lines like this:
char ch;
while (fin >> std::noskipws >> ch) {
   if (ch == '\n') {
      line++;
      continue;
   } else if (isspace(ch)) {
      continue;
   }

   break;
}

if (ch <= 32) {
    // return the "empty" token, as there's nothing grab from the file anymore
    return std::make_tuple("", -500);
}
// The rest is code which builds a token

This is also the area where things are getting weird.
When I pass in this as an input: (), it's fine, and produces exactly what I want.
When I pass in this as input: (, I get an infinite loop.
When I debug, I see that ( is indeed read in as a token.  My code then goes through, reads in the newline that Vim inserts, and then enters an infinite loop because EOF is never read.  Furthermore, my std::cout statement is never printed.
Why is this the case?  Why does it work just fine with (), but fails on (?
Edit: The full source is too large for one post, but is available on my github.


text:
Q: Create new static address dynamically in Java web application When developing a Web Application in Java, launching in Tomcat, I need to be able to create (dynamically) a new static address (link,URL) in the server that will be used to view the information of a new item, let's call it new_item_001, which have been just created by one user.
Say I want to create a new address
www.domain.com/webapp/items/new_item_001

which can be used to render a view of the contents of new_item_001.
Which is the best approach to do this?

*

*Should I dynamically create a new servlet class for this view?

*Should I dynamically create the folder items and one html file new_item_001 for this item inside of it?

*Should I edit the server address mapping rules to create this static address and map it to a central servlet which somehow knows which item to display?

I understand the question is ill posed, and that I am far from even understanding the issue, so I would like some guidelines on what to look for.

A: None of the above.
You should simply have a servlet mapped to /items/*. When a request come to this servlet, analyze the actual path of the request, extract the part after /items/ to know the actual value (new_item_001) in your example, get the data corresponding to this item from the database, and send it to the browser.
Using a true MVC framework like Spring MVC would make that much easier. You could simply map a method of a controller using
@RequestMapping("/items/{itemId}")
public Item getItem(@PathVariable("itemId") String itemId) {
    ...
}

and let the framework do all the URL parsing for you.

A: I would like to tackle this in a simple way. Creating a servlet for each created item would be overkill and become quite cumbersome to manage after a successful run of the application for some time.
Changing/editing server mapping URL looks very naive approach and is not scaling too. Let configuration be there and change them only when you actually need to change them.
My suggestion is to create one servlet that handles all these requests. For example, you may save item information on a datastore or on file system(i.e images uploaded by user etc..). Next time a GET request is received by the application to fetch saved information of an item, servlet should be able to reference the item on database associated with the item id on the URL. If you don't wish to expose item id/surrogate key in the database, you can also have a simple mapping between them by implementing your own logic. Frameworks like Spring MVC do a good job in mapping URLs to resources like this should you wish to use a framework.
Additionally to minimize the number of requests to the same item, you can also implement an HTTP caching strategy(i.e. ETAG, If-Modified-Since) by instructing your web server at the time of first GET request from a user.


text:
Q: Google windows instance not enabling 445/139 port even though firewall rule is defined to allow I'm creating a google windows instance for which i need to enable SMB [File and Printer Sharing] 445 and 139 ports.
I have created a firewall rule under "VPC Network" => Firewall rules
But still created windows instance does not have 445 or 139 port enable.
Firewall rule is as below:
"default-allow-smb
Ingress
Apply to all
IP ranges: 0.0.0.0/0
tcp:445,139
Allow
65534
default"
When I login to windows instance via RDP and check under "Control Panel" => System and Security => Windows Firewall => Advance Settings => Inbound Rules : "File and Printer Sharing" (SMB-in) shows DISABLED only.
Created google windows instance on google cloud console shows "default-allow-smb" firewall rule under network details.
Firewall Rule is as below
Firewall Rule details

A: Windows Environment inside your Google Compute Engine VM instance
I am using Windows Server 2019 Datacenter
Server with Desktop Experience, x64 built on 20190910 Google Compute Engine VM instance

I used Microsoft documentation and followed the steps to open the firewall ports to enable file and printer sharing. Currently for me, File and Printer Sharing (SMB-In) is disabled. However, there is an "Enable Rule" button on the right-hand side that you can click on to enable the rule.

Then, it should enable the rule, just like it shows here:

As you can see Enabled field is set to Yes

Firewall Rules for your Google Compute Engine VM instance

If you would like to double check whether you properly set up your Firewall Rules, you could check How to open a specific port in Google Compute Engine or check the official Google Documentation for Firewall Rules


text:
Q: Coinase API issue I am trying to use Coinbase api. However there is no luch.
Here is my code of the function:
public void sendPaymnet(String accountEmail){
    Coinbase cb = new CoinbaseBuilder()
            .withApiKey(System.getenv("xxxxxxx"), System.getenv("xxxxxxxxxxxxxxxxxxxx"))
            .build();
    Transaction t = new Transaction();
    t.setTo(accountEmail);
    t.setAmount(Money.parse("USD 0.01"));
    Transaction r = cb.sendMoney(t);

}

It's showing error on the line : cb.sendMoney(t); and when I try to run the code the app stops. Thanks in advance


text:
Q: How do I unlock/get Jason and Leatherface? I completed story mode of the game and explored some of the krypt unlocking stuff but I don't have Leatherface and Jason how do I unlock them or have them?

A: Both Jason and Leatherface are DLC characters that are purchased from the store. You can either buy them individually or as part of packs.
Jason is part of Kombat pack 1 and Leatherface is part of Kombat pack 2. Obviously, additional characters come with these packs.
If you have the XL edition of the game the packs should automatically be in your account.
Once the DLCs are installed, the characters should become available to play with and against.


text:
Q: why can't I declare a namespace and a method in a do using Clojure I try to write a macro in clojure that sets up a namespace and automatically adds a few methods to it. My macro wasn't working and I tracked it down to a do statement. It is not possible to declare a new namespace in a do and immediately afterwards declare a method in that namespace. Why?
This does not work:
(ns xyz)
(do
  (ns abc)
  (prn *ns*)
  (defn tst[] (prn "test" *ns*)))

(prn "after" *ns*)
(tst)

This works (namespace declaration before the do):
(ns xyz)
(ns abc)
(do
  (prn *ns*)
  (defn tst[] (prn "test" *ns*)))

(prn "after" *ns*)
(tst)

Thanks for reading,
 Markus

A: Actually your code happens to work with Clojure >1.0 but don't rely on that!
Each top level form is compiled and then executed:
(ns xyz) ; compiled with current ns / exec sets the current ns to xyz
(do ; the whole form is compiled inthe current ns (xyz) so it defines xyz/tst
  (ns abc)
  (prn *ns*)
  (defn tst[] (prn "test" *ns*)))
; the form above is executed: it sets the new current ns
; and the value for xyz/tst

(prn "after" *ns*) ; we are in abc
(tst) ; abc/tst doesn't exists

In clojure > 1.0, a do a the top level is "unrolled" so your code is now equivalent to:
(ns xyz)
; (do
(ns abc)
(prn *ns*)
(defn tst[] (prn "test" *ns*));)

(prn "after" *ns*)
(tst)

A: Your code does not do what you probably think it does.  The function tst
will print the value of *ns*, a var, at the time the function is run, not when it is defined.
user> (ns foobar)
nil
foobar> (abc/tst)
"test" #<Namespace foobar>
nil
foobar> (ns zelsbot)
nil
zelsbot> (abc/tst)
"test" #<Namespace zelsbot>
nil

What you are trying to do has already been nicely provided by clojure.contrib.with-ns:
(ns xyz
  (:use clojure.contrib.with-ns))

(with-ns (create-ns 'abc)
  (defn tst [] (print "defined in namespace abc")))

It evaluates its body in the namespace you provide as its first argument, thus allowing you to add functions to a namespace other than the current one.

A: Its a problem of "macro expansion time" time vs. "runtime". Do you want the code in the (do to happen when the program is compiled or when the program is run by the user?
the (ns ...) lines are expanded by the reader and then used by the compiler to decide where to put the resulting compiled code.
If i understand correctly ns sets the top level binding of the var that tells the rest of the compiler what name space it is building code for. As a though experiment try to think about what name space the (prn ...) expression should go in.


text:
Q: I want to break my text into two parts - asp.net Here's the problem:
I have couple of pages which gets its content from a database. The content is displayed in a Literal control kept on an asp.net page.
The article sometimes gets quite long so I want to break the content into two parts using a client script. Unfortunately I cannot change the query to pull data partially. The entire data has to come.
What I want is that when the page (http://mysite.com/showpage.aspx?pid=45) or any other page is opened, I show the first 500 words in that literal control. A Link gets generated below the 500 words which says 'Click Here to View More...'
On clicking this link, a postback occurs and this time the entire content is shown to the user. I understand there is an extra roundtrip required but that's ok for my users.
How can I create such a functionality? Please help me with the script. Thanks.

A: Basically you need to have a function to count the number of words including the space and other characters.
If the total is exceeding 500 words, wrap the 500 characters with the hyperlink and take only the first 500 characters.
Alternatively you might want to try any JQuery tooltip.
Hope this helps,
hadi

A: i use the following jQuery function to shorten a div of text and add a more button.
http://www.reindel.com/truncate/
Where, in the example below, 120 is the character limit.

Character limit:
  An acceptable set of characters
  (designated by a regular expression)
  to truncate in front of, once the max
  has been reached. If an acceptable
  character is not found at the max, the
  plugin will traverse the string
  backwards until one is found. If none
  is found, the string will not
  truncate. The default value is a
  single white space character.

$("#contentDiv").truncate( 120,{
        chars: /\s/,
        trail: [ " ( more . . . )",
                 "( . . . less )" ]
    });


text:
Q: What is returned by split when no delimiter is present What is returned by the python split function when no delimiter is present? I'm thinking it must be a list with one element, which is the entire string. For instance
s = "700"
parts = s.split(".")

What is in parts[0]? Is it "700"? Or is it nothing?
My personal testing, what I've tried, indicates that parts[0] = "700", but I want to be certain.

A: .split just creates a string list, and when it hit your specified delimiter, it adds a new string to the list, which the following chars will be placed in, and so on. So if it doesn't hit the delimiter, everything will be at the first item of the array


text:
Q: Period 3 window in chaos Li and Yorke established the fact that period 3 implies chaos, which implies that if we have a period 3 orbit in a system then we have a chaotic system. I have seen that in bifurcation diagrams there exists a period 3 window and that an attractor crisis occurs after the period 3 window due to the unstable orbit created by the saddle node bifurcation colliding with the attractor, but am struggling to understand why the period 3 exists, and how it is produced. If anyone could help me that would be great!

A: Since I cannot comment, hence I am posting this in the answers. Kindly have a look at the Sharkovsky ordering to better understand the origins of the statement period three implies chaos.
http://www.scholarpedia.org/article/Sharkovsky_ordering


text:
Q: java.lang.NoClassDefFoundError at Runtime in Activity's inner class I have found a lot of similar questions, but no one helps me.
I have next problem. I have complete project for Android and I have to export it's functionality to .aar library. First of all I created new project and created new module where put my source project. At this step all things goes well and I get my mylib.aar file in /build/outputs/aar/ folder. Then I created new project to test my mylib.aar, so I created libs folder under my app folder in Android Studio, and in build.gradle file of my test project I added these lines:
repositories {
    flatDir {dirs 'libs'}
}

dependencies {
    compile(name: 'mylib', ext: 'aar')
}

In manifest file I added declaration of MainActivity from library:
<activity android:name="com.testlib.mylib.MainActivity"
            android:label="MainActivity"/>

Android Studio found this file well and I even can watch source code through built-in decompiler. But when I try to start this activity from another activity that isn't placed in my lib I get this error:
3838-3838/com.testapp.testsdkapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testapp.testsdkapp, PID: 3838
    java.lang.NoClassDefFoundError: com.testlib.mylib.MainActivity$RegisterInBackgroundTask
            at com.testlib.mylib.MainActivity.registerInBackground(MainActivity.java:1551)
            at com.testlib.mylib.MainActivity.onCreate(MainActivity.java:269)
            at android.app.Activity.performCreate(Activity.java:5937)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

RegisterInBackgroundTask is inner public AsyncTask class declared in my MainActivity in the library. I tried to put mylib.aar in aar folder and declare in build.gradle in other way, but it didn't help me and I get similar error.
If this information is not enough, I'll add required parts of code etc. So please help me, if you know how to solve my problem! Thanks.

A: import mylib.aar as module in your project and inside dependencies add following line
  compile project(':mylib')


text:
Q: Displaying image in HTML from javascript using two variables I want to show a card within my html page from a file. I am trying to get two randomly selected values from two arrays then concantenating them together to create the src for the image. When i try to do this i keep getting this error:
Uncaught TypeError: Cannot set property 'src' of null
    at blackJack.js:14
HTML Code
<!DOCTYPE html>

<meta charset="UTF-8">

<title>Section 2: Javascript Language Basics</title>

Section 2: Javascript Language Basics

Javascript
var suits, cards, players, randCards, randSuit;

suits = ['hearts', 'diamonds', 'spades', 'clubs'];
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
players = [];

randCards = Math.floor(Math.random() * 13) + 1;
var randSuit = suits[Math.floor(Math.random() * suits.length)];
image = randCards + randSuit;
console.log(randCards+randSuit);
console.log(image);

document.getElementById("myImg").src = '/Users/victorcollins/Desktop/Computer Science/IA/Coding/Playing Cards/PNG-cards-1.3'+image+'.png';

A:
Uncaught TypeError: Cannot set property 'src' of null at
  blackJack.js:14

You element must be loaded into DOM before you can access the same, so put this script tag just before ending body tag.


text:
Q: How would you go about this when using partial fraction decomposition? $\frac{(u+1)^2}{(u^2+1)(u^2+3)}$
The solution of my professor says it's obvious that with
$\frac{A}{u^2+1} + \frac{B}{u^2+3}$
$A+B = 1 $
I'm curious why this is so obvious, any ideas?

A: $A+B$ is the coefficient of $u^{2}$ in the numerator.

A: $$\begin{align}\dfrac{A}{u^2+1} + \dfrac{B}{u^2+3} &= \dfrac{(u+1)^2}{(u^2+1)(u^2+3)} \\ \dfrac{\color{red}{A}u^2 + 3A +\color{red}{B}u^2 + B}{(u^2+1)(u^2+3)} &= \dfrac{\color{#2df}{u}^2+2u+1}{(u^2+1)(u^2+3)}\end{align}$$
Now if we compare the co - efficient of $u^2$ on both sides , we get : $\boxed{A+B=1}$.


text:
Q: Is it possible to exclude folders from a web application project in vs 2010? I had previously asked this question. At the time I was working with VS 2008.
To restate the question. I have a web application that generates 1000's of small xml files in a certain directory. I would like to exclude this directory from the web application project in visual studio 2010. With vs 2008 it was not possible. Has anything changed?
Besides the general wait for VS to iterate through this directory and add an item in the solution explorer for each file, it also strains my system resources, so I would like to exclude it from the project, but the dir and files need to physically exist on disk, because they are part of the application.
Any OOB VS 2010 solutions, or any good workarounds?
Thanks
Update: This also sums up the issue nicely http://forums.asp.net/t/1179077.aspx

A: Right click on the folder in Solution Explorer in VS 2010 click on 'Exclude From Project'...

A: Check out this post, a modification to the project file has been introduced to exclude a specific directory from the build process. You could look at other msbuild options too
Exclude folder from website build using MSBuild


text:
Q: Can I send an NSURLRequest over a socket? I would like to take an NSURLRequest and turn it into some usable data that is ready to be written to a socket() instead of something like an NSURLConnection.
What is the best way to accomplish this?

A: NO!
You can create a NSMutableURLRequest and provide that request with a HTTPBodyStream then create a NSURLConnection to send the request.
The HTTPBodyStream is an NSInputStream the request will read the body from. You can get it value from user, file or NSData.


text:
Q: Changing Background Image CSS Property Based on image selection I am working on something I have not done before and wanted to see if anyone knows of existing jsjfiddle or something I can research/review to learn how to accomplish this.
The below image attachment shows what I am trying to create. I have the HTML/CSS in place as seen here:

JOHN DOE

Artist Bio

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

View all work from this artist

Right now the large image is a background property of the featured-artist class and my goal is to change that property if any of the 6 images on the right are selected. So if one image is selected, it changes the background image of the "featured-artist" css class.
If there is a jsfiddle that I can study or a tutorial, please send my way!
Click To See What I am trying to create

A: This should work:-
jQuery
$('.artist-bio img').on('click',function(){
    var imgSrc = $(this).attr('src');
    $('.featured-artist').css('background-image','url('+imgSrc+')');
});

If you are using separate images for thumbnail and background, you can set the large image paths to a data attribute on the img elements and then use that instead of their src attributes. Like so:-
HTML

jQuery
$('.artist-bio img').on('click',function(){
    var imgSrc = $(this).data('src');
    $('.featured-artist').css('background-image','url('+imgSrc+')');
});

A:


text:
Q: Using configparser for text read from URL using urllib2 I have to read a txt ini file  from my browser. [this is required]
res = urllib2.urlopen(URL)
inifile = res.read()

Then I want to basically use this the same way as I would have read any txt file.
config = ConfigParser.SafeConfigParser()
config.read( inifile )

But now looks like I can't use it as this is actually a string now
Can anybody suggest a way around?

A: You want configparser.readfp -- Presumably, you might even be able to get away with:
res = urllib2.urlopen(URL)
config = ConfgiParser.SafeConfigParser()
config.readfp(res)

assuming that urllib2.urlopen returns an object that is sufficiently file-like (i.e. it has a readline method).  For easier debugging, you could do:
config.readfp(res, URL)

If you have to read it the data from a string, you could pack the whole thing into a io.StringIO (or StringIO.StringIO) buffer and read from that:
import io

res = urllib2.urlopen(URL)
inifile_text = res.read()

inifile = io.StringIO(inifile_text)
inifile.seek(0)
config.readfp(inifile)


text:
Q: How can I demonstrate that delete does not deallocate all memory new [] allocates? I want to write a simple application that proves that a memory leak exists if you use delete on a pointer that was allocated using new [].
I am currently using the CRT Debug library to monitor the memory in my application to capture the memory after allocation and after the improper deallocation. Please see my test code here:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#include <memory>

using namespace std;

int main()
{
    _CrtMemState s1, s2, mem_diff;

    // Allocate 40 bytes of memory.
    int *leak = new int[10];

    // Capture the memory state after the allocation.
    _CrtMemCheckpoint(&s1);

    // Deallocate that memory with incorrect delete operator.
    delete leak;

    // Capture and compare the memory after the deallocation.
    _CrtMemCheckpoint(&s2);
    _CrtMemDifference(&mem_diff, &s1, &s2);
    _CrtMemDumpStatistics(&mem_diff);

    return 0;
}

However, in my debug output I'm see that all 40 bytes are being deallocated. This is the output from my debug console in Visual Studio 2015 Express:
0 bytes in 0 Free Blocks.
-40 bytes in -1 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
0 bytes in 0 Client Blocks.
Largest number used: 0 bytes.
Total allocations: 0 bytes.

My other idea for why this is working is that it's undefined behaviour and is compiler specific behaviour in this case.

A: void leak_via_wrong_delete() {
  std::vector<int>* buff = new std::vector<int>[1000];
  for (auto i = 0; i < 1000; ++i)
    buff[i].resize(i * 1000);
  delete buff;
}

Wrap this with your leak detection code.
In practice, the real reason why delete[] is important is that it calls the destructor of all of the elements in the array, in most implementations I know of.  (There may be one medium-obscure platform where it also fails catastrophically, I cannot recall).
For classes without trivial destruction, they store the number of elements (or something similar) in the bytes before the start of the allocated array.  Then delete[] examines it and destroys each object in turn.


text:
Q: Custom tabLayout badge view getting cut off [Android] For the tab layout, am inflating custom layout custom_tab.xml, Where the badge view is getting cut off if the length of the name is increased.
I have tried wrap_content for all views, still no effect
This is the custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="48dp"
              android:layout_margin="5dp"
              android:orientation="horizontal">

    <TextView

        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="title"
        android:textColor="@color/white"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView

        android:id="@+id/tv_count"
        android:layout_width="31dp"
        android:layout_height="31dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:background="@drawable/badge_drawable"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="12sp" />

</LinearLayout>

This is the java code for inflating views for tablayout
private void setupTabIcons() {
    for (int i = 0; i < NewFragment.categories.size(); i++) {
        try {
            LinearLayout currentTabLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);

            ..............................
            ..............................

            tabLayout.getTabAt(i).setCustomView(currentTabLayout);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Screen shot for text having increased length with single line set as false

Screen shot for text having increased length with single line set as true

which in both case cuts the badge view from the layout
I want the text view to be single line.
Can anyone please help me fixing this issue.
Any kind of help or suggestion will be greatly appreciated.
Thanks

A: Fixed the issue by setting width to a higher level under dimens.xml file under tag
<dimen name="tab_max_width">XXXdp</dimen>


text:
Q: How to print a matplotlib figure without saving it first? Using
    import matplotlib.pyplot as plt
    plt.plot(x) # plot some data
    plt.savefig('output.ps') # I can also save from the menu
    plt.show()

one can save a matplotlib figure. How can one directly print a figure on a color printer without saving it first? What that means is that, is there a plt.printfig() ?


text:
Q: Page loads very slow Good day everyone!
Please, I've tried all I can to resolve this issue, all to know avail.
The index page loads faster, but when I try logging in to the dashboard and accessing every other pages under PHP session, I keep getting these errors on my JS console - moreover, the pages loads very slowly under PHP session.
These are the errors:
> A cookie associated with a cross-site resource at http://flutterwave.com/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

5[Intervention] Slow network is detected. See <URL> for more details. Fallback font will be used while loading: <URL>
DevTools failed to load SourceMap: Could not parse content for https://azuredate.com/asset/css/bootstrap.css.map: Unexpected token < in JSON at position 0
33XHR finished loading: POST "<URL>".
jquery-2.2.3.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
send @ jquery-2.2.3.min.js:4
ajax @ jquery-2.2.3.min.js:4
n._evalUrl @ jquery-2.2.3.min.js:4
ua @ jquery-2.2.3.min.js:3
append @ jquery-2.2.3.min.js:3
(anonymous) @ jquery-2.2.3.min.js:3
K @ jquery-2.2.3.min.js:2
html @ jquery-2.2.3.min.js:3
success @ dashboard:1074
i @ jquery-2.2.3.min.js:2
fireWith @ jquery-2.2.3.min.js:2
z @ jquery-2.2.3.min.js:4
(anonymous) @ jquery-2.2.3.min.js:4
load (async)
send @ jquery-2.2.3.min.js:4
ajax @ jquery-2.2.3.min.js:4
load_unread_messages @ dashboard:1068
(anonymous) @ dashboard:1078
i @ jquery-2.2.3.min.js:2
fireWith @ jquery-2.2.3.min.js:2
ready @ jquery-2.2.3.min.js:2
J @ jquery-2.2.3.min.js:2
64XHR finished loading: GET "<URL>".
7Error with Feature-Policy header: Unrecognized feature: 'speaker'.
DevTools failed to load SourceMap: Could not load content for https://assets.flutterwave.com/assets/index.all.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for https://assets.flutterwave.com/assets/popper.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not parse content for https://azuredate.com/asset/css/bootstrap.css.map: Unexpected token < in JSON at position 0
DevTools failed to load SourceMap: Could not load content for https://assets.flutterwave.com/assets/popper.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
2DevTools failed to load SourceMap: Could not load content for https://assets.flutterwave.com/assets/index.all.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for https://assets.flutterwave.com/assets/popper.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for https://assets.flutterwave.com/assets/index.all.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for https://assets.flutterwave.com/assets/popper.min.js.map:
HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

Meanwhile, below are the JS files am loading - which works perfectly fine on my localhost

    <script type='text/javascript' src='<?php echo base_url();?>asset/js/jquery-2.2.3.min.js'></script>
    <script src="<?php echo base_url();?>asset/js/jquery-ui.js"></script>
    <!-- menu js aim -->
    <script src="<?php echo base_url();?>asset/js/jquery.menu-aim.js"> </script>
    <script src="<?php echo base_url();?>asset/js/main.js"></script> <!-- Resource jQuery -->
    <!-- //menu js aim -->

    <!-- for bootstrap working -->
     <script src="<?php echo base_url();?>asset/js/bootstrap.js"></script>
    <!-- //for bootstrap working -->
    <!-- for smooth scrolling -->
    <script type="text/javascript" src="<?php echo base_url();?>asset/js/move-top.js"></script>
    <script type="text/javascript" src="<?php echo base_url();?>asset/js/easing.js"></script>
I've tried using a jquery cdn for this particular issue, but it's not working. I have also tried a higher version of jQuery and it's not working either.

The url is https://azuredate.com
Help a brother in need, please!
Thanks in anticipation.

A: At the top of your errors it says that "a slow network is detected", I would guess that is likely the issue. Does the dashboard load eventually? I think you should resolve each issue raised by the errors one by one, that missing cookie at the start could have a flow-on effect of failed retrievals, you are getting a heap of 404 not founds. Perhaps try other sources for those files, and test if that works better?


text:
Q: Want to upgrade my docker from 19.03.5 to latest where many countainers are running I am new to docker and linux. I am running docker 19.03.5. I had sonarqube 7.9.2 installed but I had to upgrade the sonarqube. After the upgrade I hit this issue. Now as per my understaning I don't have any choice but to upgrade docker too. Docker has many contaniers running and I am afraid that this upgrade will effect others work-  Any suggestion are welcome!
After a search I get that all the containers will restart after docker start but I still want to confirm if there is anything I should keep in mind?
Issue to resolve is:
After upgrade the sonarqube contanier close with error
Dropping Privileges
2022.05.02 12:18:50 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonarqube/temp
2022.05.02 12:18:50 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on [HTTP: 127.0.0.1:9001, TCP: 127.0.0.1:36393]
    2022.05.02 12:18:50 INFO  app[][o.s.a.ProcessLauncherImpl] Launch process[ELASTICSEARCH] from [/opt/sonarqube/elasticsearch]: /opt/sonarqube/elasticsearch/bin/elasticsearch
    could not find java in ES_JAVA_HOME at /usr/lib/jvm/java-11-openjdk/bin/java
    2022.05.02 12:18:50 WARN  app[][o.s.a.p.AbstractManagedProcess] Process exited with exit value [ElasticSearch]: 1
    2022.05.02 12:18:50 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
    2022.05.02 12:18:50 INFO  app[][o.s.a.SchedulerImpl] Process[ElasticSearch] is stopped
    2022.05.02 12:18:50 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped
      [1]: https://github.com/SonarSource/docker-sonarqube/issues/493
  [1]: https://github.com/SonarSource/docker-sonarqube/issues/493

and to solve this I have to upgrade Docker as mentioned here. I am open for any other way to solve the issue.


text:
Q: Method Post not working with Axios and React JS I am new in React.I am looking for how to save the data of a form with axios in a database. But not working..
My API.JS

const axios = require ("axios");
const querystring = require('querystring');

export function getPeople(){
  return axios.get(`http://127.0.0.1:9000/people`)
}

export function postPeople(){
  axios.post('http://127.0.0.1:9000/people', querystring.stringify({
    'bar': 123
  }));
}

My app.js:

import React, { Component } from 'react';
import { getPeople, postPeople } from './api';

addItem = () => {
    postPeople();
}

My Express.js:

var express = require('express')
var cors = require('cors')
var app = express()

app.get('/people', cors(), function (req, res, next) {
  res.json([
    {
      id: 0,
      name: "0",
      age: 20,
      city: 'R0eiro',
      country: '04'
    },
    {
      id: 1,
      name: "0",
      age: 29,
      city: 'Minas 00',
      country: '00'
    },
})

app.listen(9000, function () {
  console.log('The server is running in the port 9000')
})

Be givin that errors:

POST http://127.0.0.1:9000/people 404 (Not Found)
Failed to load http://127.0.0.1:9000/people: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.
Uncaught (in promise) Error: Network Error
      at createError (createError.js:16)
      at XMLHttpRequest.handleError (xhr.js:87)

Someone help me?

A: You're running into a CORS problem.
Taken from this SO answer:

Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing)
  header.
When Site A tries to fetch content from Site B, Site B can send an
  Access-Control-Allow-Origin response header to tell the browser that
  the content of this page is accessible to certain origins. (An origin
  is a domain, plus a scheme and port number.) By default, Site B's
  pages are not accessible to any other origin; using the
  Access-Control-Allow-Origin header opens a door for cross-origin
  access by specific requesting origins.
For each resource/page that Site B wants to make accessible to Site A,
  Site B should serve its pages with the response header:
Access-Control-Allow-Origin: http://siteA.com Modern browsers will not
  block cross-domain requests outright. If Site A requests a page from
  Site B, the browser will actually fetch the requested page on the
  network level and check if the response headers list Site A as a
  permitted requester domain. If Site B has not indicated that Site A is
  allowed to access this page, the browser will trigger the
  XMLHttpRequest's error event and deny the response data to the
  requesting JavaScript code.

You'll probably want a cors npm package:
From the command like install cors:
npm install cors

Then in your API.js:
const axios = require ("axios");
const querystring = require('querystring');
const cors = require('cors')
app.use(cors())

export function getPeople(){
  return axios.get(`http://127.0.0.1:9000/people`)
}

export function postPeople(){
  axios.post('http://127.0.0.1:9000/people', querystring.stringify({
    'bar': 123
  }));
}

A: You are getting CORS errors because you're trying to make requests to a different port (which counts as a different domain). You could set up CORS headers as seen in the other answer, but:
A much better way is to use a proxy in your react app. See Proxying API Requests if you are using create-react-app.
Then you would use the same port and just prefix with a /api route:
axios.post('/api/people', querystring.stringify({
  'bar': 123
}));


text:
Q: How to publishing limited function in magento webservices instead of showing all? How to publish limited function in magento soap v2 web services wsdl xml file?

A: One option is you can restrict it by adding SOAP role by providing limited access. To do this login to admin panel :
System > Web Services > SOAP/XML-RPC-Roles and create a new roles.
then click on "Role Resources" tab and select custom option from Resource Access dropdown and select roles which you want to expose through API.
After this create new SOAP user or existing user assign your newly created role.
I hope this help!
Thanks


text:
Q: Quartz.net Job unhandled exception behaviour I am implementing quartz.net scheduler to my project, and have some questions about the workings of this library:

*

*What happens if one job raises an exception without a catch block (unhandled exception)? Would this cause the process to terminate and AppDomain Unloading? Would other jobs suffer?

*Does Quartz.net lib try to restart jobs that raised unhandled exceptions? Or should I implement it manually in my project?

Thanks.

A: From what I can determine being a user of Quartz.net myself.

*

*If your job (or quartz itself) raises an unhandled exception like all .net2 or later programs it will take our your app domain. You could try using AppDomain.UnhandledException handler.

*I think by default RequestRecovery is true but you can set this to false when you schedule the job.


text:
Q: Symfony: How to save record with undefined foreign key record For example, Comment table has foreign key at Author table. How do I create a new author record when I save a new comment? e.g.: Comment: id = 1, author_id = [newly generated id associated with author table], content = "this is a new comment". Author: id = 1, author_name = [newly generated author name].

A: This has nothing to do with Symfony. I assume you're using Doctrine, am I right? Well, all you have to do is to create Comment and Author objects:
$author = new Author();
$author->setName('Crozin');

$comment = new Comment();
$comment->setAuthor($author);
$comment->setContent('This is my first comment!');

$comment->save();

Doctrine should recognize that you're using two brand new objects that aren't persisted in database and thus both object will be inserted.


text:
Q: partial differential equation by Lagrange's method given different solution Let
$$z= ax^2 + by^2 …\tag{1}$$
Let $\displaystyle\frac{\partial z}{\partial x}= 2ax$ and let $p = 2ax$ or $a\displaystyle = \frac p{2x}$
Similarly we get $\displaystyle b= \frac q{2y}$
If we plug in $(1),$ we get, $2z = px + qy$
Now, I solved $(2)$ by Lagrange's method, in order to get $(1).$ But I didn't get.
I compared the equation $(2)$  with $Pp+Qq = R$, then $P = x , Q = y$ and $R = 2z$
Now by rule, $dx/P = dy/Q= dz/R$
i.e., $dx/x = dy/y = dz/2z$
Take $dx/x = dy/y$
By solving, I got,$lnx = lny + ln C_1$ or $x/y= c_1$
Similarly $dy/y = dz/2z$ gives us, $2lny = lnz + lnc_2$ or $y^2/z$ = $c_2$
Now by lagrange's method, solution must be $F(c_1, c_2) =0$
But I got, $F(x/y,y^2/z) = 0$...(3)
When I solve (2), I should get (1). But I got (3). How (1) and (3) are equal? Please explain.


text:
Q: Online Editor for HTML CSS and Javascript I need an editor for html,css and javascript that I can integrate with php.
My project is related to decorating your album, where user can select the pre defined templates and they can change the css html and javascript of that template.
Please help me out in this

A: There are many publishers such, I particularly like the Netbeans.
With it you can edit projects in PHP with syntax recognition for HTML, Javascript and CSS, among others.


text:
Q: Is there a way to test verification emails using Karate? The problem I have is that I need to test if user verification is working. We generate a verification token, and an email is sent to the user. Whenever the user clicks on it, it checks if the verification token has expired. I've tried mocking this, but it just won't work. We have an endpoint to verify a user, but we still need the verification token, which is not available on any endpoint.

A: I think this article may help you: https://www.testingexcellence.com/automated-api-testing-emails-karate/
To summarize:

*

*use the API at http://qamail.ala.se/ to create a test mailbox

*initiate the flow that sends the e-mail

*use the API to "read" the e-mail and grab the token

EDIT: looks like the link is dead. but you should be able to find similar offerings on the internet. since the source-code seems to be available, it may make sense for you to host this e-mail server somewhere so that it can receive e-mail from whichever system is the sender


text:
Q: FadeIn текста в slick каруселе Доброй ночи, дорогие друзья.
Использую slick carousel. На каждом слайде есть текст, при появлении слайда или при скролле на новый слайд блок с текстом должен всплывать (например FadeIn).
Вопрос в том, как поймать действие появление нового слайда.
Понимаю, вопрос несерьезный, но хотелось бы разобраться.
В какую сторону копать?


text:
Q: How addition will be if we don't define it only on pairs of numbers? In calculus by Michael spivak  book
he say in page 4

It might seem reasonable to regard addition as an operation which can be performed on several numbers at once and consider the sum $a_1+...+a_n$ of n number $a_1,...,a_n$ as a basic concept . it is more convenient , however to consider addition of pairs of numbers only and to define other sums in terms of sums of this types

My questions :
1- How addition will be if we don't define it only on pairs of numbers ?
2- why it is more convenient , however to consider addition of pairs of numbers only and to define other sums in terms of sums of this types?

A: How addition will be if we don't define it only on pairs of numbers ?
The short answer is, it will be summation, as in $\sum_{i = 1}^n a_i$.
The long answer is, Spivak was writing in the 1960s, for people fresh out of high school, who hadn't necessarily ever heard of associative or commutative laws, but were familiar with expressions like "$a + b + c$." He's about to show that that expression can be justified by use of the associative law of addition; he's anticipating objections from readers who don't see why it needs to be justified at all.
why it is more convenient , however to consider addition of pairs of numbers only and to define other sums in terms of sums of this types?
Because then you can define the algebraic properties of the real numbers as consequences of the field laws and order laws, Spivak's properties P1-P12, and these involve only the binary operation.

A: Unless I am misunderstanding the question, addition this way would be exactly the same. We don't only define addition on pairs of numbers - we define it on any number of numbers by using the associative property. Because we have defined
$$a_1+a_2$$
Then we can express a sum of any number of terms
$$a_1+a_2+...+a_n$$
as a bunch of sums in the form that we have defined:
$$(((a_1+a_2)+a_3)+...+a_n)$$
The reason this is more convenient is because if we were going to define it for any number of addends, we would have to address an infinite number of cases. But if we simply define $a_1+a_2$ and then create the commutative property, we can let it do the heavy lifting for us, since all other cases, using the commutative property, can be reduced to the case $a_1+a_2.$
I suppose you could try to define it for many addends. But if you did, here's what would happen:
Currently, addition is defined, at the most basic level, as an iterative operation. If $S(n)$ is the successor function
$$S(n)=n+1$$
then addition can be expressed in terms of the successor function
$$a+b=S^b(a)$$
However, trouble arises when you try to do it for three numbers. You would need a "successor function" with multiple arguments, but what would that even represent? Or you could do something like
$$a+b+c=S^{b+c}(a)=S^{S^c(b)}(a)$$
or
$$a+b+c=S^c(a+b)=S^c(S^b(a))$$
but that is the same as pairing up the addends
$$(a+b)+c$$
That's why it is much more convenient just to define it for two addends.


text:
Q: SharePoint 2010 multi-lingual search refinments I have a search refinement panel in my SharePoint 2010 site that utilizes a managed metadata term set in which I have a second language installed and parallel terms defined for that language.  For example, my multi-lingual term set is "color", and I have "red" and "blue" as my terms, with parallel terms of "rojo" and "azul".
A user can select a the language they want to display with the site, but for some reason I cannot get the Spanish terms to be displayed...the refinement panel always shows the English terms.  My backup plan is to write a custom refinement panel to query the term store and get my alternate language terms, but I would think I could do this through configuration.  Does anyone have any insight into this?

A: I found the answer to my own question:
http://technet.microsoft.com/en-us/library/ff805062.aspx
http://social.technet.microsoft.com/Forums/en/sharepoint2010setup/thread/de2d48f6-043f-4dde-a3c3-bd5228c68965


text:
Q: vue-chartjs load data from parent component I have a component for a LineChart, here is the code :
<script>
  import { Line } from 'vue-chartjs'

  export default {
    extends: Line,
    props: ['data', 'options'],
    mounted () {
      this.renderChart(this.data, this.options)
    }
  }
</script>

I want to use this component in another one as I can affect data to data and options value of the component Chart.vue.
I'm new to VueJS and can't understand an example like that in vue-chartjs doc.
Here is my component that will be the parent one, and what I've done from now :
<template>
  <div class="dashboard">
    <chart></chart>
  </div>

</template>

<script>
  import Chart from '@/components/Chart'

  export default {
    name: 'DashBoard',
    components: {
      'chart': Chart
    },
    mounted () {},
    data () {
      return {
        datacollection: null
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

A: Where does your data come from?
Your example code is weird, as you are not passing your data as props.
So no wonder, that nothing shows up.
You have to pass your datacollection to your chart component.
<chart :data="datacollection" />

And keep in mind, that if you are using an API your data will arrive async. So the component mounts, renders the chart but your data is not there. So you need to add a v-if to be sure that your api call is finished.


text:
Q: Logarithm Subtraction and Division with Same Bases I'm rusty on logarithms.  What is the approach to a problem like this?  Any hints would be appreciated.
I'm thinking the subtraction on the numerator and denominator can become division since the bases are the same?

A: The identities $\log_a b + \log_a c \equiv \log_a(bc)$ and
$b\log_a c \equiv \log_a c^b$ will be needed here. You can then do
\begin{align*}
 \frac{\log_2 24 - \frac 12 \log_2 72}
      {\log_3 18 - \frac 13 \log_3 72}
 &=
 \frac{\log_2 24 - \log_2 \sqrt{72}}
      {\log_3 18 - \log_3 \sqrt[3]{72}} \\
 &=
 \frac{\log_2 \frac{24}{\sqrt{72}}}
      {\log_3 \frac{18}{\sqrt[3]{72}}} \\
 &=
 \frac{\log_2 \frac{24}{3\sqrt 8}}
      {\log_3 \frac{18}{2\sqrt[3]{9}}} \\
 &=
 \frac{\log_2 \frac{8}{\sqrt 8}}
      {\log_3 \frac{9}{\sqrt[3]{9}}} \\
 &=
 \frac{\log_2 8 - \log_2 \sqrt 8}
      {\log_3 9 - \log_3 \sqrt[3]{9}} \\
 &=
 \frac{\log_2 2^3 - \log_2 2^{3/2}}
      {\log_3 3^2 - \log_3 3^{2/3}} \\
 &=
 \frac{3 - \frac 32}
      {2 - \frac 23} \quad \text{by definition} \\
 &= \frac 98
\end{align*}

A: 1)
$\log_2 24 =\log_2 (3\times 2^3)= \log_2 3 + \log_2 2^3 = \log_2 3 + 3$.
$\frac 12\log_2 72  = \frac 12 (\log_2 3^2\times 2^3) = \frac 12(\log_2 3^2 + \log_2 2^3)=\frac 12(2\log 3 + 3) = \log 3 +\frac 32$
So $\log_2 24 -\frac 12\log_2 72 = (\log_2 3 + 3)-(\log_2 3 +\frac 32) = \frac 32$
Likewise.
$\log_3 18 = \log_3 2\times 3^2 = \log_3 2 + \log_3 3^2 = \log_3 2 + 2$
$\frac 13\log_3 72 = \frac 13(\log_3 3^2\times 2^3) = \frac 13(\log_3 3^2 + \log_3 2^3)=\frac 13(2 + 3\log_3 2)= \frac 23+ \log_3 2$.
So $\log_3 18-\frac 12\log_3 72 = (\log_3 2+2)-(\frac 23 + \log_3 2)= \frac 43$.
So $\frac {\log_2 24 -\frac 12\log_2 72}{\log_3 18-\frac 13\log_3 72}=\frac {\frac 32}{\frac 43}=\frac 32\frac 34=\frac {9}8$.
2)
$\frac {\log_2 24 -\frac 12\log_2 72}{\log_3 18-\frac 13\log_3 72}=$
$\frac {\log_2 24 -\log_2 72^{\frac 12}}{\log_3 18-\log_3 72^{\frac 13}}=$
$\frac {\log_2 \frac {24}{72^{\frac 12}}}{\log_3 \frac {18}{72^{\frac 13}}}=$
$\frac {\log_2 \frac {3*2^3}{3^{2*\frac 12}2^{3*\frac 12}}} {\log_3 \frac{2*3^2}{3^{2*\frac 13}2^{3*\frac 13}}}=$
$\frac {\log_2 2^{\frac 32}}{\log_3 3^{\frac 43}}=$
$\frac {\frac 32}{\frac 43}=\frac 32\frac 34=\frac 98$.

A: Often better to factor the arguments of the logarithms to get to much simpler logarithms more quickly...  \begin{align*}
&\frac{\log_2 24 - \frac{1}{2} \log_2 72}{\log_3 18 - \frac{1}{3} \log_3 72}  \\
    &\quad{}= \frac{\log_2 (2^3 \cdot 3) - \frac{1}{2} \log_2 (2^3 \cdot 3^2)}{\log_3(2\cdot 3^2) - \frac{1}{3} \log_3 (2^3 \cdot 3^2)}  \\
    &\quad{}= \frac{\log_2 2^3 + \log_2 3 - \frac{1}{2} \left( \log_2 2^3 + \log_2 3^2 \right)}{\log_3 2 + \log_3 3^2 - \frac{1}{3} \left( \log_3 2^3 + \log_3 3^2 \right)}  \\
    &\quad{}= \frac{3\log_2 2 + \log_2 3 - \frac{1}{2} \left( 3\log_2 2 + 2\log_2 3 \right)}{\log_3 2 + 2\log_3 3 - \frac{1}{3} \left( 3\log_3 2 + 2\log_3 3 \right)}  \\
    &\quad{}= \frac{3 + \log_2 3 - \frac{1}{2} \left( 3 + 2\log_2 3 \right)}{\log_3 2 + 2 - \frac{1}{3} \left( 3\log_3 2 + 2 \right)}  \\
    &\quad{}= \frac{3 + \log_2 3 - \frac{3}{2} - \log_2 3 }{\log_3 2 + 2 - \log_3 2 - \frac{2}{3}}  \\
    &\quad{}= \frac{3 - \frac{3}{2}}{2 - \frac{2}{3}} \cdot \frac{6}{6}  \\
    &\quad{}= \frac{18-9}{12-4}  \\
    &\quad{}= \frac{9}{8}  \text{.}
\end{align*}

A: Rule 1: $\ \log_a(x^q) = q\log_a(x)$
Rule 2 (Addition): $\ \log_a(x) + \log_a(y) = \log_a(xy), \ $
Rule 3 (Subtraction): $\ \log_a(x) - \log_a(y) = \log_a(\frac{x}{y}), \ $
Rule 3 is actually Rule 2 but replacing y with $\  \frac{1}{y} =y^{-1}$, and then using Rule 1.
Rule 4 (Change of base): $\ \frac{\log_a(x^p)}{\log_a(x^q)} = \log_q(p)$

A: Yes, the subtractions can become division, and the fractions can become roots, plus $\log_a b =\frac 1 {\log_b a}$


text:
Q: Vuejs Dynamic input binding & computed is not a function I need help in dynamically setting the input v-model. Based on the dropdown selection. I will get data from the backend. Right now, it's a dummy data.
ScreenShot
example, there will be 3 input boxes in each row. numerator, denominator and the computed value. For each input box, I have passed v-model like this form['num_' + idx], form['den_' + idx], form['comp_' + idx]. I have created a form object in data(state).
if I bind the computed value input box (:value) with computed property, then I am not able to pass arguments. I need the current numerator,  denominator value. it gives me an error computedValue is not a function.
Right now, I have tried putting this computedValue function in the methods section and also added a button next to the computed each input box. What I really need is, when the value in the numerator and denominator changes. it automatically calculates the value and show it in the third computed input box.
The value in the computed input box is not showing. Sometimes it shows value if I change row data in other rows.
<template>

    <select v-model="service">
      <option disabled value="">Please select one</option>
      <option>Order to cash</option>
    </select>
    <select @change="changeAccountEvent($event)" >
      <option disabled value="">Please select one</option>
      <option>Nissan</option>
      <option>Ford</option>
    </select>

{{d.metric}}

              <input v-model="form['num_' + idx]" type="number">

              <input v-model="form['den_' + idx]" type="number">

            <input v-model="form['comp_' + idx]" type="number" >
            <button
              @click="computedValue(form['num_' + idx], form['den_' + idx], idx, d.formula)">get value
            </button>

</template>

Please guide me.
Cheers
Meet

A: You need to use Vue.set instead of index [] for object updates to be reactive.
Instead of:
this.form[`comp_${c}`] = parseFloat(a) / parseFloat(b);

Try:
Vue.set(this.form, `comp_${c}`, parseFloat(a) / parseFloat(b));

A: You need to use reactive properties in order for your vm to be notified of updates to a property and updated reactively.
form['num_' + idx], form['den_' + idx], and form['comp_' + idx] aren't reactive because you haven't declared them on the object you've returned from the data() method in the script block.
You need to use Vue.set/Vue.prototype.$set AKA this.$set to dynamically set reactive properties like so:
this.$set(this.form, 'num_' + idx, value)

see Reactivity in Depth - Vue.js


text:
Q: How to initialize two attributes of type list with the same list? class Bins:

    def __init__(self, id:str, initial_list:list):
        self.id_ = id
        self.capacities = initial_list
        self.remaining_capacities = initial_list

example = Bins("t1",[0,0,1])
example.capacities[1] = 1
print(example.remaining_capacities) # gives [0, 1, 1]

As shown, the problem with this approach is that I cannot modify the attributes independently.

A: You can use the built-in list.copy() to make a deep copy.
    def __init__(self, id:str, initial_list:list):
        self.id_ = id
        self.capacities = initial_list.copy()
        self.remaining_capacities = initial_list.copy()


text:
Q: Share user login/session between cakephp and moodle I have a website already running made with CakePHP, which has its own login system using the Auth component.
Now I'm going to create another website using moodle, hosted in the same server. Is there any way to share the user session between those 2 websites?
For example, if a user logs into the moodle website and clicks a link to a page of the other website, he is not asked to log in again, since the system recognises that he is already logged in.
I guess that one thing to do would be to tell moodle (somehow) to  use same table of users in the database that the CakePHP website is already using. And then tell the CakePHP website to accept the sessions created in that other website. Something like this right?
But I don't know how to do those things or if they even possible, any advice on how to approach this would be very helpful.

A: Single sign-on (SSO) is not currently a trivial thing to do in Moodle.
Some other approaches you may consider are:

*

*Use external authentication in Moodle and configure it to use Cake's database. Does not provide SSO but tells Moodle to use Cake's user accounts.

*Configure both Moodle and Cake to use a common authentication system like LDAP, POP3 or CAS. Depending of your choice it is possible that you may achieve SSO.
More information about Moodle authentication plug-ins in this page:
http://docs.moodle.org/dev/Authentication_plugins


text:
Q: Distinctly counting measure results that match a certain criteria We have a measure for feedback scores which I am trying to report on. I need to calculate how many have reached a score >5 to calculate a performance %age. The issue I have is where there is more than one score available for my member which is aggregated in my results.
Here is what I have so far:
with
MEMBER [Client Sat Score] AS ([Measures].[Avg_Score], Linkmember([Bill Period].[Fiscal].[Fiscal Period].&[201409],[Date].[Fiscal]),[Bill Period].[Fiscal].[All],[Time Slice].[KeyTimeSlice].[12M])

MEMBER [Sum Scores] AS([Measures].[Sum of Scores], Linkmember([Bill Period].[Fiscal].[Fiscal Period].&[201409],[Date].[Fiscal]),[Bill Period].[Fiscal].[All],[Time Slice].[KeyTimeSlice].[12M])

MEMBER [Number Scores] AS([Measures].[Number of Scores], Linkmember([Bill Period].[Fiscal].[Fiscal Period].&[201409],[Date].[Fiscal]),[Bill Period].[Fiscal].[All],[Time Slice].[KeyTimeSlice].[12M])

MEMBER [Over 5] As IIF([Client Sat Score]>5,1,NULL)

MEMBER [Scores Over 5] As SUM([Matter].[KeyMatterNumber].[KeyMatterNumber].members,[Over 5])

MEMBER [Percent 6 or 7s] As IIF([Number Scores]=0,NULL,[Scores Over 5] / [Number Scores])

select {[Client Sat Score],[Sum Scores],[Number Scores],[Over 5],[Scores Over 5],[Percent 6 or 7s] }
on columns,

non empty ({[Client].[KeyClientRelatedID].&[XXX] })
on rows

from [Cube]

This returns 4 for "Scores over 5" but there are actually 2 scores of 7 on one of the members. These scores are on different date keys but I am unable to stop them aggregating within the SUM.
Any suggestions/advice please?
EDIT:
I've found that if I run the following I do get the 5 separate results each with a score above 5:
select {[Measures].[Avg_Score] }
on columns,

non empty ({[Matter].[KeyMatterNumber].[KeyMatterNumber].members })*
{[Date].[KeyDate].[KeyDate].&[20130206]:[Date].[KeyDate].[KeyDate].&[20140206]}
on rows

from [Cube]
where (
[Client].[KeyClientRelatedID].&[XXXX]
)

Does this help at all with the amendment of my first query?

A: It is difficult to answer without a cube schema available. However, it sounds like you are trying to do a row level calculation post-aggregation which results in your attempts to find the combination of dimensions that will cause leaf level data to be used in the calculation. Even if possible these invariably perform badly.
I would suggest pushing this calculation into the underlying database and generating an additional dimension with banded values { [1-5], [6-7] }.
Also, you didn't mention if this Analysis Services (or another vendor) Multidimensional or Tabular - if Tabular just create a row calc for "Over 5" in the cube and use that as your new dimension members.


text:
Q: iOS in Settings app Good morning all, I was wondering if there is a way to capture a password while it is being typed in Settings . i.e. I am connecting to a Wifi hotspot and I need to save the typed password in NSUserDefaults. ?
Any thoughts ?
Much Thanks
JZ

A: It would be pretty dangerous if you can read (whatever) system settings of iOs device - so in short - afaik it`s not possible. But you can make your own settings (which are shown in settings app) for your own app via settings bundle - these settings you can use whatever you want.


text:
Q: Adding an LED through a FET circuit that currently drives a solenoid I would like to save space on a layout by consolidating a FET or two, where feasible, on an existing board. One of the FETs used, a coolMOS P7 series (IPA60R280P7SXKSA1), seems to have the drain current availability and the acceptable logic to combine its existing solenoid drive function to also include a green LED.
Factoring in the flyback diodes/magnetic field collapse aspect of the solenoid, would it be a poor design practice to put an LED in parallel? If so, why?
Thanks

A: Please add reference designators to each component.
Assuming the diode on the right is the LED, adding a current limiting resistor in series with it should be all you need.  The series combination of the LED and its resistor is in parallel with the solenoid coil and the flyback suppression diode.


text:
Q: Talkback is announcing the app name on tap of element in certain timeout but it is not consistent - React Native Talkback is announcing the app name on tap of element in certain timeout but it is not consistent - React Native
I tried to find out that the app name where it is announcing by talk back but didn't get the solution. Why it is announcing or to stop the announcement of app name.


text:
Q: mysql create table with foreign keys failing I am trying to create a tables in a db that have foreign keys. what am i missing?
CREATE TABLE `users` (
`id` bigint(10) NOT NULL AUTO_INCREMENT,
`userName` varchar(24) NOT NULL DEFAULT '',
`password` varchar(32) NOT NULL DEFAULT '',
`firstName` varchar(32) NOT NULL DEFAULT '',
`lastName` varchar(32) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
 ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1

CREATE TABLE `topLevelPermissions` (
`id` bigint(10) NOT NULL AUTO_INCREMENT,
`userId` bigint(10) NOT NULL DEFAULT '0',
`user` char(1) NOT NULL DEFAULT '0',
`group` char(1) NOT NULL DEFAULT '0',
`someField` char(1) NOT NULL DEFAULT '0',
`someOtherField` char(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
FOREIGN KEY (`userId`) REFERENCES users (`id`) ON DELETE CASCADE
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1

and i see nothing related to foreign keys.  in fact when i
show create table topLevelPermissions;

i see
 CREATE TABLE `topLevelPermissions` (
 `id` bigint(10) NOT NULL AUTO_INCREMENT,
`userId` bigint(10) NOT NULL DEFAULT '0',
`user` char(1) NOT NULL DEFAULT '0',
`group` char(1) NOT NULL DEFAULT '0',
`someField` char(1) NOT NULL DEFAULT '0',
`someOtherField` char(1) NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`),
 KEY `userId` (`userId`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1

A: Innodb only supports foreign key constraints. So switch to Innodb if you want to utilize foreign key constraints.


text:
Q: c# Stream Reading and Deserialization I have this code:
public static List<ReplicableObject> ParseStreamForObjects(Stream stream)
{
   List<ReplicableObject> result = new List<ReplicableObject>();
   while (true)
   {
      // HERE I want to check that there's at least four bytes left in the stream
      BinaryReader br = new BinaryReader(stream);
      int length = br.ReadInt32();
      // HERE I want to check that there's enough bytes left in the stream
      byte[] bytes = br.ReadBytes(length);
      MemoryStream ms = new MemoryStream(bytes);
      ms.Position = 0;
      result.Add((ReplicableObject) Formatter.Deserialize(ms));
      ms.Close();
      br.Close();
   }
   return result;
}

Unfortunately, the stream object is always going to be a TCP stream, which means no seek operations. So how can I check to make sure that I'm not over-running the stream where I've put the // HERE comments?

A: I don't think there's any way to query a NetworkStream to find the data you're looking for.  What you'll probably need to do is buffer whatever data the stream makes available into another data structure, then parse objects out of that structure once you know it's got enough bytes in it.
The NetworkStream class provides a DataAvailable property that tells you if any data is available to be read, and the Read() method returns a value indicating how many bytes it actually retrieved.  You should be able to use those values to do the buffering you need.

A: See Mr. Skeets page

Sometimes, you don't know the length of the stream in advance (for instance a network stream) and just want to read the whole lot into a buffer. Here's a method to do just that:

/// <summary>
/// Reads data from a stream until the end is reached. The
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// </summary>
/// <param name="stream">The stream to read data from</param>
public static byte[] ReadFully (Stream stream)
{
    byte[] buffer = new byte[32768];
    using (MemoryStream ms = new MemoryStream())
    {
        while (true)
        {
            int read = stream.Read (buffer, 0, buffer.Length);
            if (read <= 0)
                return ms.ToArray();
            ms.Write (buffer, 0, read);
        }
    }
}

This should give you some ideas.  Once you have the byte array, checking the Length will be easy to do.
In your example, it would look something like this:
int bytes_to_read = 4;
byte[] length_bytes = new byte[bytes_to_read];
int bytes_read = stream.Read(length_bytes, 0, length_bytes.Length);
// Check that there's at least four bytes left in the stream
if(bytes_read != bytes_to_read) break;
int bytes_in_msg = BitConverter.ToInt32(length_bytes);
byte[] msg_bytes = new byte[bytes_in_msg];
bytes_read = stream.Read(msg_bytes, 0, msg_bytes.Length);
// Check that there's enough bytes left in the stream
if(bytes_read != bytes_in_msg ) break;
...


text:
Q: How to create trial account for Salesforce Marketng cloud How to create trial account to access Salesforce Marketing cloud

A: A free Marketing Cloud Developer Edition was released at Connections in September 2014 but was only available for a couple of months. If you didn't sign up during that period, then unfortunately you missed out.
I enquired about the availability of the Developer Edition at Connections last year and Salesforce explained that while the public program had been discontinued, free Developer Edition accounts are still available, by request.
I would suggest you contact your Salesforce Account Representative to enquire if you can get access to an account (I'd suggest that you also explain what you intend to use the account for).

A: http://www.salesforce.com/ap/marketing-cloud/overview/
In the above link, you can click on any of these to create trial accounts.


text:
Q: c++ binary file opened for input/output won't update contents I'm solving a c++ problem that requires updating a binary file.
Examples shows binary file is opened with ios::in ios::out ios::binary flags. I tried the following code but the binary file won't update on windows OS.
#include <fstream>
#include <iostream>

using namespace std;

void printFileContent() {
    ifstream inFile ("test.bin", ios::in | ios::binary);
    if (inFile) {
        int data;
        inFile.read(reinterpret_cast <char*>(&data), sizeof(int));
        cout << data << endl;
    }
    inFile.close();
}

void createFile() {
    ofstream outFile ("test.bin", ios::out | ios::binary);
    if (outFile) {
        int data = 5;
        outFile.write(reinterpret_cast <const char*>(&data), sizeof(int));
    }
    outFile.close();
}

void updateFileContent(){
    fstream ioFile ("test.bin", ios::out | ios::in | ios::binary);
    if (ioFile) {
        int data;
        ioFile.read(reinterpret_cast <char*>(&data), sizeof(int)); // Read value
        data++; // Update value
        ioFile.seekg(-sizeof(int), ios::cur); // Seek original position
        ioFile.write(reinterpret_cast <const char*>(&data), sizeof(int)); // Write new value
    }
    ioFile.close();
}

int main(int argc, char** argv) {
    createFile();
    printFileContent();
    updateFileContent();
    printFileContent();
    return 0;
}

The program outputs 5 but it should output 6. I've tried the same in Mac OS and it works fine.
I've tested my code on this website (https://www.onlinegdb.com/online_c++_compiler) and it outputs 6.
I think it is a windows related issue. Does anyone know why could this happen?.
My windows version is 20H2(OS compilation 19042.867).

A: sorry a can't leave comment so this is a comment .
what happens if you write :
date = date + 1;

or
date += 1;

instead of :
date++;


text:
Q: How do I use a loop to iterate through a dictionary that contains lists, calculate something, and add the result to the dictionary? I'm building a dictionary that has years (key), and a list as the value [population data, 0, 0]
I was able to write a loop to add years as the dictionary keys (1950 to 1990), and import population data from a file to add as [value[0], ...]
Right now, value[1] and value[2] are empty.
How do I write a loop that iterates through my dictionary (starting at index 1, not 0), calculates the population change, and puts that in value[1] ...for every item in my dictionary?
(After, I will put percent change in value[2])

myDict = {'1950':[141902, 0, 0],
'1951':[157311, 0, 0],
'1952':[186006, 0, 0],
.... }  # etc. population data from a file object
dict_key = [1950, 1951, 1952, 1953, ... ]  # 41 values total, to 1990

What I have so far:

def calculate_population_change(myDict, dict_key):
for i in range(1, (len(dict_key))):
    value[i] = 7
    myDict[key[i]] = [value[i], 0, 0]

return myDict

I wrote value[i] = 7 as a test, to see how to put something in that spot
Thank you for taking a look.
The rest of the code is at, if you need more context: https://github.com/alexisabadger/pythonDictionaryAndList/blob/main/PopulationDataCounter.py

A: You can iterate through your dictionary with a foor loop and since your keys represent an ascending number stored as a String, you can convert the sting to an integer, substract one and convert that to a string again in order to get the list of the year before.
for year in myDict:
    if year != '1950':
        #Calculate the difference in population of two consecutive years.
        myDict[year][1] = myDict[year][1]-myDict[str(int(year)-1)][1]

        #Calculate the difference as a percentage
        myDict[year][2] = (1-myDict[year][1]/myDict[str(int(year)-1)][1])*100


text:
Q: Erase disk before selling I have an old Windows 7 computer that I want to format and prepare for selling to somebody. I am using Parted Magic for disk operations and I'm wondering if "erasing the disk safely" is really necessary or if I could just delete the existing partitions using partitions manager, then reinstall Windows on it? Also for information purposes the disk is a 500GB standard drive, and I'm worried about how much time erasing the disk safely could take.

A: If you have any Linux in hand, this is very simple and easy:
sudo dd if=/dev/zero of=/dev/sdX

where sdX should be replaced by the actual device of the disk you want to wipe.
Quick estimation about timing. I used this way to wipe a 3.5" hard drive (1 TB). The write speed started off at 220 MB/s and near the end it's 100 MB, so I assume 150 MB on average. Then it'd take less than 2 hours for a complete wipe, if everything does well.
You can also try the built-in functionality, DiskPart.exe to wipe. You can open up a Command Prompt window with Administrator privileges (use Task Manager to achieve this), then run in Command Prompt:
DiskPart

SELECT DISK 2  (where you should replace 2 with your actual disk number)
CLEAN ALL

Then DiskPart will clean the whole disk, identical to the Linux dd method.
Optionally in Linux, you can dd if=/dev/urandom so the disk is overwritten with random data, but it is considerably slow depending on your computer configuration.

A: If the disk at any point contained sensitive information, or if you ever used the computer that the disk was installed in for sensitive purposes, then yes, a proper wipe is necessary.
Due to the nature of how hard drives work, any data that you delete from within an operating system is never quite deleted, at least not immediately. Instead, the filesystem on the drive (NTFS, in the case of most Windows-formatted drives) removes all references to the data's location on the hard drive, making it inaccessible from within the operating system. The data itself stays on the hard drive until it is naturally overwritten by a newer piece of data that needs to take its place. Depending on how much free space is left on your drive, this could be anything from hours to never at all.
Likewise, cleaning partitions also does nothing to the existence of the data on the drive, and this doesn't change when you're installing Windows to the drive, unless the installation happens to take up the space of the entire drive in question (which is unlikely).
Freely-available data recovery tools like Recuva and GetDataBack are designed for this exact purpose - to recover files, folders and even entire partitions from a hard drive that hasn't been properly wiped. This means that any remaining data in the structures of your hard drive is easily recoverable to anyone technologically adept enough to know of and operate these programs, which is a very low bar.
That said, it's not necessary to use third-party utilities like Parted Magic to securely wipe a (mechanical) disk. In fact, you can do so from Windows itself provided that the disk you want to wipe is not the one you're booting from. Simply select the disk in question in My Computer and run a long format by right-clicking on the drive, selecting Format and unchecking the Quick format checkbox. Windows' long format wipes drives just as most other third-party "secure wipe tools" out there do (for those who doubt this claim, see the addendum).
If you are booting from the drive that you want to securely wipe, then your only option is to create a bootable disk containing a tool like DBAN or Parted Magic, and then boot into that to wipe the drive in question.
As for the time that the format will take, I expect for a standard HDD it will take a few hours. The question you need to ask yourself is whether that's too high a time cost to make sure that any data you once stored on the drive doesn't end up in anyone else's hands.

ADDENDUM
There are apparently a number of people who doubt the claim that Windows' long format provides any less secure a wipe than third-party secure wipe tools, or who believe that Secure Erase provides an inherently more secure wipe for HDDs. They'd be patently wrong.
Windows' long format tool works by writing binary zeroes to the raw sectors of the drive, and has done so since Windows Vista was released more than a decade ago. This is also how third-party secure wipe tools work, including the Linux go-to
dd if=/dev/zero.
Secure Erase does the same, with the difference that it's a firmware-level tool built into the drive itself, and as such depends on the hard drive manufacturer's implementation of the ATA specification to zero-write the drive successfully. Considering that many hard drive manufacturers have in the past shown a failure or unwillingness to implement these standards correctly, with some drives reporting a successful wipe even while all the data on the drive was still intact, this makes Secure Erase inherently insecure unless you're willing to test your particular drive's implementation of SE and confirm it works as intended... in which event it would be exactly as secure as a Windows long format or zero-write; no more and no less.
The exception to this is if your drive is an SSD (which the OP's is not) in which case you have no option but to resort to a Secure Erase, as software zero-writes are ineffective on an SSD. Even in this scenario, however, a Secure Erase is the least secure disk sanitisation option available to you; you should use an Enhanced Secure Erase, which writes a vendor-defined pattern to the drive, or a Block Erase, a newer (and therefore less-supported, but even more secure) option which also wipes an SSD's non-user-accessible areas such as the HPA (traditionally, these are the areas of an SSD that are the hardest to wipe and therefore most likely to contain remnant data).

A: Do it more securely with pseudo random numbers from /dev/urandom instead of zeros from /dev/zero. As root or as normal user with sudo:
sudo dd if=/dev/urandom of=/dev/sdX bs=1M

With
bs= blocksize, how many bytes to write at once,
urandom = pseudo random numbers, pretty secure.
sdX = the hard drive you want to overwrite (be careful to choose the right one)

Urandom uses data from /dev/random/ to start its random number generator seed and uses as much real random number as possible. But if runs out of random numbers, it won't stop but generate pseudo random numbers with real random numbers as seeds.
Dont use /dev/random it uses "real" random numbers from packet counters or mouse movement etc. When there are no random numbers left, it will just stop and wait for new ones. This takes ages to complete.
urandom means unblocking random, because it continues with pseudo random numbers and does not block the system by waiting for new real random numbers.
This is a bit slower but more secure.

A: In particularly case you can just use CMD to fill erased places on disk with, for example, large movie file.
C:>\...\for /L %a in (1,1,999) Do copy YOUR_MOVIE_FILE %a

Where 9999 - your count of copies.
Then quick format for clean.


text:
Q: label word wrapping within a html table cell Fragment of code -
HtmlTableCell fixedDataCell = new HtmlTableCell();
fixedDataCell.Style.Add(HtmlTextWriterStyle.Height, "22px");
fixedDataCell.Style.Add(HtmlTextWriterStyle.Width, "100px");
fixedDataCell.Style.Add(HtmlTextWriterStyle.FontSize, "small");
fixedDataCell.NoWrap = true;

Label lbl = new Label();
lbl.Text = "ABCDEFGHIJKLMNOQRSTUVWXYZ";
lbl.Width = 1;

fixedDataCell.Controls.Add(lbl);

The cell expands instead of truncating or adding an ellipsis to the label's Text. It's important that the cell remain at a certain width. How to do I handle the label within that cell?
EDIT: Apparently just adding a width value will fix this.

A: To hide the overflow try with:
fixedDataCell.Style.Add(HtmlTextWriterStyle.OverflowX, "hidden");

While, to have ellipsis:
fixedDataCell.Style.Add(HtmlTextWriterStyle.OverflowX, "ellipsis");

A: Apparently just adding a width value will fix this.

A: HTML would only wrap a logical word such as those separated by space or punctuation, for long-spelling words, HTML would not break or wrap the word.  So the content would bleed or force-expand the container if the container is "narrower" than the required horizontal space for the word, which is true in your example.
By adding CSS attribute such as "overflow-x: hidden", the bleeding content would be clipped to fit the container, but you may want to add tooltip in case the user would like to see the clipped content.
I would caution the usage of "overflow-x: ellipsis" as it is a CSS3 attribute which may not be supported in older versions of IE.