text:
Q: Handle UnknownHostException properly in RabbitMQ, preventing auto recovery I have written a Spring Application that is implementing RabbitMQ manually with the RabbitMQ Client API.
The way the Connection Factory and Connection are set are similar to the tutorial:
public class Recv {
  private final static String QUEUE_NAME = "hello";

  public static void main(String[] argv)
      throws java.io.IOException,
             java.lang.InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("122.34.1.1");
    factory.setPort(5672);
    factory.setUsername("user");
    factory.setPassword("password")
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    ...
    }
}

The connection works correct.  However, if I turn off my host server, my application seems to stuck in some sort of loop where it tries to auto recover by keep pinging the turned-off host.
Because of this, my console get filled with tons of stacktraces that say "UnknownHostException".  The exact location according to stacktraces is the line:
Connection connection = factory.newConnection();

I have tried to put a try-catch block around this line, but that doesn't seem to work at all.
If the traditional try-catch block can't handle the exception coming from the connection, what is the proper way to catch the exception and stop the auto-recovery from creating this loop?
Thanks.

A: Try setting up your Rabbit like this (on both ends):
@Bean
    public ConnectionFactory connectionFactory() {
        final CachingConnectionFactory connectionFactory = new CachingConnectionFactory(server);
        connectionFactory.setUsername("user");
        connectionFactory.setPassword("pass");
        return connectionFactory;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
        final SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        return factory;
    }

The port should be set by default. If not, it will show on startup and you can change it. The Queue should be declared and set by the consumer (host or whatever you call it).
And put a @EnableRabbit annotation on your configuration class if you haven't.
Consumer declares a Queue:
@RabbitListener(queues = "myQueue")
@Component
public class RabbitListener {

    @Bean
        public Queue getQueue() {
            return new Queue("myQueue");
        }

        @RabbitHandler
        public void getElementFromMyQueue(@Payload Object object) {

            // handle object as you want
    }
}

After that just @Autowire the RabbitTemplate on the sender and you should be good to go. The queue should remain idle but 'active', even when the host is down


text:
Q: re.findall() and unicode like error in python 3 I'm using python 3.3.0 in Windows 8. Below code successfully runs in python 2.7.x
import re, urllib
import urllib.request

arg_end = "--"
url = "http://www.johandemeij.com/post.php?id=276+AND+1=2+UNION+SELECT+1,2,p0w3R,4,p0w3R,p0w3R,7,8,p0w3R,p0w3R--"

url = site.replace("p0w3R","concat(0x1e,0x1e,version(),0x1e,user(),0x1e,database(),0x1e,0x20)")+arg_end

requrl = urllib.request.Request(url)

response = urllib.request.urlopen(requrl)

source = response.read()

match = re.findall("\x1e\x1e\S+", str(source))

print("match>>>", match)

In this script, I'm getting no value in match variable!
And when I'm using this:
match = re.findall("\x1e\x1e\S+", source)

It gives me error like:
TypeError: can't use a string pattern on a bytes-like object

In-fact, when I'm injecting url in the browser, I'm getting result like below in particular vulnerable column.
5.1.61-0+squeeze1johan@localhostjohan_db
So, what's wrong with that re or what should I change and where?
When I tried to read about \x in re module of python docs, I found nothing! or may be, I failed to get it. I appeal you to suggest me something with an example regarding this, if it's available in easy way to understand.
One more thing when I tried to convert 1e into string it gave nothing!
I have just started to learn python 3 and instead of writing simple programs, I really want to create some useful scripts. So, I'm trying to get my hands dirty in making simple SQLi scanner in python 3.
I got inspiration from darkMySQLi tool.

A: By default ordinary string literals "" are bytestrings in Python 2, but they are Unicode strings in Python 3. b"" creates a bytestring in both versions.
Read about the difference between bytes and strings (Unicode) in Python.
You could use urllib.parse.urlencode({'id': '276 AND ...'}) to construct the url query, decode source bytes to Unicode using source.decode(encoding) (how to find the character encoding depends on content-type). For example, if there is charset parameter in the Content-Type http header:
import cgi

# extract encoding from Content-Type and print the response
_, params = cgi.parse_header(response.headers.get('Content-Type', ''))
print(response.read().decode(params['charset']))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I fire an event inside an Angular10 app with RxJS? I am starting out with Angular10.  I've written a Canvas and can draw on it.  Lets call the thing I draw on the canvas a Foobar --- my Angular10 drawing code of Foobars work fine.  I am getting a Foobar from a REST call using HttpClient and that works fine too because it populates this.foobar when I do the REST call.  What I want to do is make the Canvas observe the this.foobar 'model' so that when this.foobar changes, then the Canvas redraws the Foobar.
Does this mean I make the Foobar an Observable with RxJS?  If so how do I do that? Then this.foobar.subscribe(()=> {this.canvas.drawFoobar()}).  How do I make Foobar an Observable?  Do I need to extend the Foobar Typescript class?
Once I get the "listening" to Foobar working (I am a good Java Swing programmer), how do I fire a Foobar changed event manually?  Suppose I modify Foobar and want to fire a modelChanged event (like in Swing) what is the pattern to do that in RxJS?
Please give me some hints andget me going in the right direction.  Is there a blog where RxJS is explained using Java Swing listening concepts?  Thank you and greatly appreciated!

A: Subjects are RxJS's most common way to convert an imperative piece of code into functional RxJS streams. Subjects are both observers and observables so you can imperatively write subject.next(value) and also subject.subscribe(value => {..})
Here's a naive pattern that turns a property into a stream. Here, you wouldn't subscribe to foobar, you can instead subscribe to _foobar which is a BehaviorSubject representing the values being set on the property foobar
private _foobar$ = new BehaviorSubject<Foobar>(new Foobar(/*default*/));

get foobarProp(): Foobar {
  return this._foobar$.value
}

set foobarProp(val: Foobar): void {
  this._foobar$.next(val);
}

this._foobar.next(val); is not limited to a setter function. You can write that wherever you like.

A: Thank you!  I You got me going in the right direction and I got it to work.  For other with the same task, this is my solution (pardon the bad Typescript, I am starting out):
app.component.ts
import { Component,OnInit, ViewChild } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { ApiService } from './api.service';
import { CanvasComponent } from './canvas/canvas.component';
import { Foobar } from './foobar';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'FOOOBAR';

  foobarSubject:BehaviorSubject<Foobar>;
  @ViewChild(CanvasComponent) canvasComponent:CanvasComponent;

  constructor(private apiService: ApiService) {
  }

  ngOnInit() {
    console.log("ngInit() called");
    this.foobarSubject= new BehaviorSubject<Forbar>(null);
    this.registerFoobar();
  }

  go() {
    this.foobarSubject.subscribe(
      (data:Foobar) => {
        if (data != null) {
          console.log("foobar was not null, updating canvas");
          this.canvasComponent.update(data);
        }
      }
    );
  }

  // Register the callback containing the REST call
  // so that it loads the next Foobar in the foobarSubject
  registerFoobar() {
    console.log("getting foobar");
    this.apiService.getFoobarObservable().subscribe(
      (foobar:Foobar) => {this.foobarSubject.next(foobar)},
      (err) => console.error(err),
      () => console.log("foobar: + this.foobarSubject.value.toString())
    );
  }
}

app.component.html

Hello {{title}}

<app-canvas></app-canvas>

<button mat-button matSuffix mat-icon-button aria-label="Go" title="Go"
(click)="go()">GO</button>

app.service.html
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Foobar } from './foobar';

    const remoteUrl = 'http://localhost:8080/foobar;

    @Injectable({
      providedIn: 'root'
    })
    export class ApiService {

      constructor(private http: HttpClient) { }

      getFoobarObservable(): Observable<Foobar> {
        return this.http.get<Foobar>(remoteUrl);
      }
    }


text:
Q: Extract raster data by feature attributes/elements I have a DEM raster, and a shapefile consisting of ~20 lines of steepest descent, created from the "flow Path Tracing" tool in Arc Hydro. Though the lines are all in the same shapefile, I wish to maintain their distinction (each has a separate ObjectID in the attribute table) in extracting DEM elevation values through a tool such as Extract by Mask. Using Extract by Mask with the line shapefile just produces one raster, with no separation between different lines.
Is there a way to extract DEM raster values corresponding to line location and maintain separate line IDs, so that I can later export them to Matlab for further analysis?
I'm currently using ArcMap 10.2


text:
Q: Typescript useQuery Type What would be the type which I have defined as any? I have tried TQueryFnData as per the RQ docs. but get Cannot find name 'TQueryFnData'
export const useFetchUser = (userID: string | undefined) => {
    return useQuery<any, Error>([users.fetchUser, userID],
        () => axios.get(`https://jsonplaceholder.typicode.com/users/${userID}`)
            .then(response => response.data))
}

An example of the data returned is: https://jsonplaceholder.typicode.com/users/1
export interface Users {
    id: number,
    name: string,
    username: string,
    email: string,
    address: Address,
    phone: string,
    website: string,
    company: Company
}

export interface Address {
  ...
}

export interface Geo {
  ...
}

export interface Company {
  ...
}

A: Fix typo -
export interface Users
// to
export interface User

It is useQuery<Users, Error>
export const useFetchUser = (userID: string | undefined) => {
    return useQuery<User, Error>([users.fetchUser, userID],
        () => axios.get(`https://jsonplaceholder.typicode.com/users/${userID}`)
            .then(response => response.data))
}

Lastly here's a working example of your code on codesandbox

A: As described in the docs and in my blog, the best thing you can do is make sure that your query function is typed to return a Promise of the type you'd expect. Then, you don't need to pass generics to useQuery at all.
There are many ways to achieve that:

*

*declare return type on the queryFn:

export const useFetchUser = (userID: string | undefined) => {
    return useQuery([users.fetchUser, userID],
        (): Promise<User> => axios.get(`https://jsonplaceholder.typicode.com/users/${userID}`)
            .then(response => response.data))
}

*declare a generic for axios.get:

export const useFetchUser = (userID: string | undefined) => {
    return useQuery([users.fetchUser, userID],
        () => axios.get<User>(`https://jsonplaceholder.typicode.com/users/${userID}`)
            .then(response => response.data))
}


text:
Q: How do I auto fill the Input Table records for batch processing the Delete Field Tool, in ArcMap? I have over 500 individual shapefiles that need to have a specific field removed from their tables. In theory I can use the batch option with the Delete Field tool, but adding the Input Table cell for 500+ records is extraordinarily tedious. Is there some way to automate or semi-automate that part of the process? It hardly makes the batch aspect worth it as it seems to work right now.

A: Search for them in Explorer, e.g. "*.shp" (right window), select all and drag to tool window ( left one):

Use "fill" option on field column.


text:
Q: Not all Loops processed, only 5655 out of 13200 I have 2 javascript loops, one nested in the other, that does an AJAX call to the serverside. The loops generate a pair of numbers (latlng coordinates), which is then passed to the server via .getJSON() where it will be inserted into a MySQL table.
Problem: The script runs for about 6 minute, with a total of 13200 AJAX calls. In chrome's webdeveloper tools, it says 5656/13646 requests 536.20KB/2.15MB. When I check the tables for the inserted entries, I only see 5655 rows! What happened to the rest?
JS Code
for(var i = 0; i < 110; i++) {
    var lat_current = lat_start + lat_increment * i;

    for(var j = 0; j < 120; j++) {

        // Do some calculations
        // More code here...

        // Insert LatLng into database
        $.getJSON(base_url + 'insert_latlng_to_crawl',
            {
                lat: lat_current,
                lng: lng_current
            },
            function(json){
            });

    }

}

A: It might be counting the return values.
5655/13200
5655 is what you sent and the number after the / is total (which includes returned values which is 2x your first number). Sent and received json values. Im assuming a success status of some sort?
Also the question is how many duplicate values are being inserted into your table? Do you have unique keys on your table?

A: You should create a javascript object, then pass it to the server and process it server-side
 var coords=Array();//Create an array to store the calculations
 for(var i = 0; i < 110; i++) {
    var lat_current = lat_start + lat_increment * i;

    for(var j = 0; j < 120; j++) {

    // Do some calculations
    // More code here...

    // append the results to the array
    coords.push({lat: lat_current, lng: lng_current});

}

//Make the ajax call to the server, sending the completed Array JSON encoded
coords= JSON.stringify(coords);
$.ajax({
  type: 'POST',//you should send big chunks of data via POST
  url: url,
  data: coords,
  success: success,
  dataType: JSON
});


text:
Q: do I need to install WSE 3 for Visual Studio 2010 I'm trying to add a service reference in VS 2010 (WCF). The web service uses WS-Policy and when I consume the service I get some commented code in my app.confing customBindings section:
<!--    WsdlImporter encountered unrecognized policy assertions in ServiceDescription 'http://ws.TheirSite.com/WebServices/ResellerApiV1.wsdl':    -->
<!--    <wsdl:binding name='ResellerApiBinding'>    -->
<!--        <ns0:SupportingTokens xmlns:ns0="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">..</ns0:SupportingTokens>    -->

and I can't seem to create a SOAP header with the UserNameToken info.
Are these commented sections because I need to install WSE 3.0 or is that included with the 4.0 Framework?
EDIT: Thanks for the comments. The host got back to me and said I need to add this security tag to resolve this issue (*note the enableUnsecuredResponse is only available within the 4.0 Framework):
<security authenticationMode="UserNameOverTransport" enableUnsecuredResponse="true" />

Apparently the commented xml in the app.config is caused by the VisualStudio WsdlImporter tool (svcutil.exe?) which can't process the SupportingTokens policy, but adding the above  directive will insert the WS-Security UsernameToken into the SOAP header.

A: Recently, I've had to support WSE 3.0 in Visual Studio 2010 (not by choice) as we had some .NET 2.0 applications which (for a few reasons) we can't upgrade, and which need to use WSE 3.0 for some "non-standard" reasons.
You can have Visual Studio use the old Importer to generate WSDL proxies, but you need to install WSE 3.0 and make some modifications to configuration.  It's all documented in two blog posts here:
http://www.sanderstechnology.com/?p=10648
http://www.sanderstechnology.com/?p=10659

A: Web Service Enhancements 3 (WSE 3) is not officially supported since Visual Studio 2008. The reason is that Microsoft wants you migrate your code to WCF.
Follow the blog below to enable WSE 3.0 in Visual Studio 2012, 2010 and 2008
http://digantakumar.com/2010/06/04/wse-3-in-visual-studio-2008-and-2010/


text:
Q: Modal popup not working for dynamically generated list items I am trying to open a modal whenever a user selects on the X image inside of a LI item inside of a UL. The items are dynamically generated from items that are inside of the TempData field. I can assign the data-target to a static field and it will work without any issues, but no luck for the generated ones. Here is how I am trying to do it.
@if (TempData.ContainsKey("ShiftSegments"))
{
var NewShiftSegments =
    new List<ShiftSegmentData>();
NewShiftSegments =
    (List<ShiftSegmentData>)TempData["ShiftSegments"];
if (NewShiftSegments != null)
{
    foreach (var item in NewShiftSegments)
    {

                @item.ShiftSegmentTypeName

                @item.StartDT.TimeOfDay
                -
                @item.EndDT.TimeOfDay

    }
}
}

And here is the modal I am trying to open:

Delete Down Time?

            Are you sure you want to delete this Down Time period?

            <button class="btn btn-primary" id="btnConfirmSegmentDelete">Confirm</button>
            <button class="btn btn-primary" id="cancelSegmentDelete" data-dismiss="modal">
                Cancel
            </button>

Thanks in advance for any help.

A: give class to your href link class="mypopup"
$(document).on('click', '.mypopup', function(e) { $('#shiftSegmentDeleteModal').modal('show'); });


text:
Q: How to let someone login with another account, even though he is already logged in with one account? First: Why is this necessary? Why not make people log out first? Because my app automatically creates a new account, when people who aren't logged in open it.
I tried this code:
  def create
    current_user.signout
    super
  end

But it doesn't work. I don't even know what doesn't work, as I don't get any errors.
I'm using devise.

A: You need to find the current user first and also define a signout action.
Without more information a basic example would be (this is assuming a lot of things):
def create
  current_user = User.find(params[:id]) # you need to pass the ID to the create action somehow
  current_user.signout
end

# User model (user.rb)
  def signout
    # signout logic goes here
  end


text:
Q: how to play YouTube video with fullscreen in android application I want to play the YouTube video in fullscreen mode by default in my Android application. I have tried with the options force_full screen and flag_full screen, but nothing is working.Can you please help me on this?
Thanks.

A: This should be work:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com  /watch?v=VIDEOID"));
intent.putExtra("force_fullscreen",true);
startActivity(intent);

Thanks DagW

A: you can use this code, if you use YouTube SDK
player.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
                    @Override
                    public void onPlaying() {
                        player.setFullscreen(true);
                    }

                    @Override
                    public void onPaused() {

                    }

                    @Override
                    public void onStopped() {

                    }

                    @Override
                    public void onBuffering(boolean b) {

                    }

                    @Override
                    public void onSeekTo(int i) {

                    }
                });


text:
Q: Using awk how to compare 2 fields and print something out Let say I have file1 with the following content:
1,2,3,4,12,6
1,2,3,5,333,6
1,2,3,12,5,6
1,2,3,44,101,6

While file2 has the following content:
22,4,111,1,6,7,12
22,4,56,55,6,7,12
22,4,12,12,6,7,12
22,4,333,102,6,7,12

What I want is if 5th field on file1 has a greater value than the 3rd field on file2 print something like Value 333 greater than 56
How could this be done using awk?

A: $ awk -F, 'FILENAME=="file1" {inputs[FNR]=$5} FILENAME=="file2" && inputs[FNR] > $3 {print inputs[FNR] " is greater than " $3 " on line " FNR}' file1 file2
333 is greater than 56 on line 2

A: I have used below method to get the same required output
for i in {1..4}; do second_file=`awk -F "," -v i="$i" 'NR==i{print $3}' j.txt`; first_file=`awk -F "," -v i="$i" 'NR==i {print $5}' l.txt`; if [[ $first_file -gt  $second_file ]]; then echo $first_file is greater than $second_file; fi; done

output
333 is greater than 56


text:
Q: How to lookup an HBase table efficiently I have a HBase lookup table where I store some information. I have a MapReduce program which runs some Pentaho KTRs and in the MapReduce job I capture the output. From certain fields in the output of the KTRs, I retrieve some keys and using them I have to lookup some values in HBase. My scenario is:
1. The rowkey is of format <Table Code>-<CRC>, ex- DDVC-XXX

For each output of the KTRs:

2. If no result is found for a particular key(which I get from the Pentaho KTRs),
    then increment a column value which has the rowkey of format
    <Table Code>-last, ex: DDVC-last
3. Take this incremented value and put it in the HBase table with the specific key.

So, here I am doing one Get, one Increment and one Put operation if I could not find a value for a rowkey. Can someone give me some suggestion on how to do it efficiently and without hitting HBase over again over again. Because, I can see the majority of the time the job requires is for executing the above algorithm, which hits HBase multiple times for a single row.
Thanks in advance.!!

A: Although the schema design may merit some attention, the problem as you described it may not be further improved performance-wise.  The Get, Increment, and Put are separate operations and do require three separate HBase calls.


text:
Q: Owin identity framework returns no claims when tables are renamed If I create a brand new MVC website in Visual Studio (asp.net 4.6.1), I am able to add/retrieve claims by doing the following in the Register() method of the AccountController class:
if (ModelState.IsValid)
{
    var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
    var result = await UserManager.CreateAsync(user, model.Password);

    var addClaimResult = UserManager.AddClaim(user.Id, new Claim("test", "test"));
    var claims= UserManager.GetClaims(user.Id);

    //claims.Count == 1
}

If I rename the tables by overriding OnModelCreating as follows, then claims.Count above is 0. In other words, once I rename the tables, I cannot get the claims from the database anymore.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    string prefix = "Identity";
    modelBuilder.Entity<ApplicationUser>().ToTable($"{prefix}Users", "dbo");
    modelBuilder.Entity<IdentityUser>().ToTable($"{prefix}Users", "dbo");
    modelBuilder.Entity<IdentityUserRole>().ToTable($"{prefix}UserRoles", "dbo");
    modelBuilder.Entity<IdentityUserLogin>().ToTable($"{prefix}UserLogins", "dbo");
    modelBuilder.Entity<IdentityUserClaim>().ToTable($"{prefix}UserClaims", "dbo");
    modelBuilder.Entity<IdentityRole>().ToTable($"{prefix}Roles", "dbo");
}

The AddClaim method returns successfully, and I can confirm that 'test' is added to the table in the database. Everything else related to the identity framework still works (logins, etc), it's just that the claims added to the database are never returned. I've tried through MVC and Web API 2, I've tried at different times (ie after login, after authorizing, after multiple web method calls, whatever).
I enabled entity framework logging. AddClaim hits the database. GetClaims doesn't hit the database in either case (tables renamed or not).
Why is the claims.Count = 0?

A: ASP Identity 2 + Web API Token Auth - Persistent claims not Loading
Same answer as above.
modelBuilder.Entity().ToTable($"{prefix}Users", "dbo"); not needed.


text:
Q: "BindException: Address already in use" after restart of app I got a BindException when i restart my application. It acts as a server waiting for remote control messages. The ServerSocket is running in a background thread (AsyncTask). After restart of my application i always get the exception mentioned above. I have to wait for like 10 minutes until it can bind again to the port in order to listen.
I tried different ports (all >50000) so I'm sure there is no other application blocking my port. I tried to be careful about closing the socket and i tried to use the SO_REUSEADDR option. Also I am sure that there is only one connection open at run time, since i logged every socketbind.
So what i think is, that the connection is not closed properly. I've read about the habit of sockets not closing instantly. But i cannot wait like 10 minutes on every restart of the application and i did not find a way to shorten or kill this time.
Do you have any ideas?
The exception:
10-04 16:39:22.526: WARN/System.err(4974): java.net.BindException: Address already in use
10-04 16:39:22.526: WARN/System.err(4974):     at org.apache.harmony.luni.platform.OSNetworkSystem.bind(Native Method)
10-04 16:39:22.526: WARN/System.err(4974):     at dalvik.system.BlockGuard$WrappedNetworkSystem.bind(BlockGuard.java:275)
10-04 16:39:22.526: WARN/System.err(4974):     at org.apache.harmony.luni.net.PlainSocketImpl.bind(PlainSocketImpl.java:165)
10-04 16:39:22.526: WARN/System.err(4974):     at java.net.ServerSocket.<init>(ServerSocket.java:123)
10-04 16:39:22.526: WARN/System.err(4974):     at java.net.ServerSocket.<init>(ServerSocket.java:74)
10-04 16:39:22.526: WARN/System.err(4974):     at com.*******.remote.RemoteHandlerListener$1.doInBackground(RemoteHandlerListener.java:114)

The code:
ServerSocket server;
try {
    server = new ServerSocket();
    server.setReuseAddress(true);
    server.bind(new InetSocketAddress(serverport));
} catch (IOException e) {
    e.printStackTrace();
    return null;
}

while (true) {
    BufferedReader inStream = null;
    Socket client = null;
    try {
        client = server.accept();
        inStream = new BufferedReader(new InputStreamReader( client.getInputStream()));
        // read from stream
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (inStream != null) {
            try {
                inStream.close();
            } catch (IOException e) { }
        }
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) { }
        }
    }
}
try {
    server.close();
} catch (IOException e) { }

The exception is thrown on the server.bind-statement.
EDIT:
Cause of the problem: The thread will not terminate itself since the accept-call is blocking. The program did not terminate completely and the socket was not unbound.
Solution: Set SO_TIMEOUT to the socket and check for isCancelled in the while()-loop. This way the thread will finish if you call cancel() on it.

A: Try to print the stacktrace of all the caught exceptions. That will probably help a lot. Maybe there is something wrong in your code you posted. You are creating try-catch blocks without handeling the Exception. You even don't know if there are any.

Update: Next step is to make sure your application is really stopped. At first sight of your code you never quit your infinite loop of accepting clients. Try to fix that and add a print statement after you close the serversocket:
try {
    server.close();
    System.out.println("Server successfully stopped.");
} catch (IOException e) { }

Make sure you find this in the output of your application.
And if you want to be sloppy, you can enforce the application (and the serversocket) to shutdown using:
System.exit(0);

A: I Agree - Usually this indicates that the restart failed to terminate the server process properly. Somehow it's still running and therefore the port is still blocked.
Waiting for 10 minutes is somewhat long. Just check (if possible) if the previously running java process has terminated.

A: If you haven't already, you should study the Android dev stuff on Activity Lifecycles.  The tl;dr of that article is that the Android operating system makes absolutely no guarantee about when an application will be killed except that it can happen any time, and that's why they provide the onPause, onResume, onRestart, etc.  You can't ever guarantee that your app will always die completely, but you can perform your own cleanup, and I'd recommend killing your thread and closing your socket (or some other management) inside of onPause.
In addition, when using Java sockets (whether it's Android or not), it's never good practice to let program termination be the action that closes your sockets.  You should almost always close them yourself in some sort of clean-up area.  Especially when dealing with threads.
Update:  You said that you are hitting back and then restarting.  This doesn't call onDestroy.  onDestroy is only called if the OS needs the memory and kills your app completely (the equivalent of killing it in the Task Manager)


text:
Q: Add avs_FastSimpleImport to magento store I am trying to install FastSimpleImport in a magento store to import new products into the store. I've put the files in the app/code/community and the app/etc/modules folders (that's how I downloaded it from GitHub). But after that, the documentation only says "The above code is designed to be included into your own module." So I have a couple of questions:

*

*Does this mean I have to create a new module in the app/code/local folder?

*I am not very experienced with Magento. I just created a custom module (in the app/code/local) that hooks into an event to send updates to a warehouse. Can I add the code for the import of new products to this module, or should I create a new one?

*When I created the other custom module, I could hook it into an event. But how does that work with FSI? Do I hook it up to a cronjob?

I know these are a lot of questions, and it's not even all of them. I have searched for tutorials or tips on how to use FastSimpleImport, but can't find any good examples on how to create the custom module. Any help would be much appreciated.
EDIT:
I think I need to specify my questions. How do I use FastSimpleImport in a custom module after installing it, and what does the custom module look like? Does anyone have an example or know a tutorial I can follow?

A: I only know the first question:
using AVS_FASTSIMPLEIMPORT or HO_IMPORT you must create a lightweight module. this is my example for an import with HO-nl/HO_Import
<?xml version="1.0"?>
<config>
  <modules>
    <module1>
      <version>0.1.0</version>
    </module1>
  </modules>
  <global>
    <helpers>
      <module1>
        <class>module1_Helper</class>
      </module1>
    </helpers>
    <ho_import>
        <events>
          <process_before helper="ho_import/import_product::prepareSomeData"/>
          <import_before helper="ho_import/import_product::callWifeIfItIsOk"/>
          <source_row_fieldmap_before helper="ho_import/import_product::checkIfValid"/>
          <source_row_fieldmap_after helper="ho_import/import_product::extractData"/>
          <source_fieldmap_after helper="ho_import/import_product::appendExtraData"/>
          <import_after helper="ho_import/import_product::reindexStuff"/>
          <process_after helper="ho_import/import_product::cleanupSomeData"/>
      </events>
        <ebay_electronics>
            <log_level>1</log_level>
            <entity_type>catalog_product</entity_type>
            <source model="ho_import/source_adapter_xml">
                <file>var/import/ebay_electronics.xml</file>
                <rootNode>objects</rootNode>
                <childNode>getsingleitem_us_electronics_ebay</childNode>
            </source>
            <import_options>
                <partial_indexing>1</partial_indexing>
                <continue_after_errors>1</continue_after_errors>
                <ignore_duplicates>1</ignore_duplicates>
                <archive_import_files>0</archive_import_files>
                <allow_rename_files>0</allow_rename_files>
                <error_limit>10000</error_limit>
            </import_options>
            <fieldmap>
                <ho_import_profile value="ebay_electronics" />
                <sku field="sku" required="1"/>
                <_attribute_set value="Default" />
                <_type value="simple" />
                <_store value="admin" />
                <_category field="_category" />
                <_product_websites helper="ho_import/import::getAllWebsites"><limit>1</limit></_product_websites>
                <cost field="cost" />
                <price field="price" />
                <location field="Location" />
                <country_of_manufacture field="country_of_manufacture" />
                <name field="name" />
                <short_description helper="ho_import/import::truncate">
                    <value field="short_description"/>
                    <length>150</length>
                    <etc>…</etc>
                </short_description>
                <description helper="ho_import/import::truncate">
                    <value field="description"/>
                    <length>400</length>
                    <etc>…</etc>
                </description>
                <manufacturer field="manufacturer" />
                <qty field="qty" />
                <weight helper="ho_import/import::getFieldDefault"><field>weight</field><default>1</default></weight>
                <status value="1" />
                <is_in_stock value="1" />
                <tax_class_id field="tax_class_id" />
                <visibility field="visibility" />
                <_media_attribute_id helper="ho_import/import_product::getMediaAttributeId"/>
                <_media_image helper="ho_import/import_product::getMediaImage"/>
                <_media_lable/>
                <image helper="ho_import/import::getMediaImage">
                    <imagefield field="image"/>
                    <limit>1</limit>
                    <filename use="sku"/> <!-- optional, when the server doesn't give back readable image names -->
                    <extension value="jpg"/> <!-- optional, when the URL doesn't end in a filename -->
                </image>
                <image_label use="name"/>
                <small_image helper="ho_import/import::getMediaImage">
                    <imagefield field="small_image"/>
                    <limit>1</limit>
                    <filename use="sku"/> <!-- optional, when the server doesn't give back readable image names -->
                    <extension value="jpg"/> <!-- optional, when the URL doesn't end in a filename -->
                </small_image>
                <small_image_label use="name"/>
                <thumbnail helper="ho_import/import::getMediaImage">
                    <imagefield field="thumbnail"/>
                    <limit>1</limit>
                    <filename use="sku"/> <!-- optional, when the server doesn't give back readable image names -->
                    <extension value="jpg"/> <!-- optional, when the URL doesn't end in a filename -->
                </thumbnail>
                <thumbnail_label use="name"/>
                <gallery/>
                <media_gallery />
            </fieldmap>
        </ebay_electronics>
      </ho_import>
  </global>
</config>

then I have an empty helper/data.php and it works ok.
Note: HO_Import works (extends) AVS_FASTSIMPLEIMPORT. hope it helps.


text:
Q: A greatest common divisor problem I want to show that given  positive integers $p$ and $q$, if $p x + q y =1$ for integers $x$ and $y$ with $x>0$ then
\begin{align*}
p&=\gcd\left( \frac{1+\sqrt{1-4 m n}}{2},  n \right)\\
q&=\gcd\left( \frac{1-\sqrt{1-4 m n}}{2},  n \right)
\end{align*}
where $n=pq$ and $m=x y$.
So far I have:
First consider $p x + q m /x=1$. Solving for $x$
$$
 x = \frac{1 \pm \sqrt{1-4 m n}}{2p}
$$
Since $x>0$, the solution is
$$
 x = \frac{1 + \sqrt{1-4 m n}}{2p}
$$
Therefor $p \mid \frac{1 + \sqrt{1-4 m n}}{2}$. Since $p \mid n$,
we conclude $p=s\gcd(\frac{1 + \sqrt{1-4 m n}}{2},n)$ for some integers $s$.
Noting that $y<0$ and $p m/y + q y=1$, reasoning in a similar fashion, we conclude
$q=t \gcd\left( \frac{1 - \sqrt{1-4 m n}}{2},  n \right)$ for some integer $t$.
How can I show $s$ and $t$ are equal to 1?

A: First I think that what you have shown is :
$$gcd(\frac{1+\sqrt{1-4mn}}{2},n)=ps\text{ and } gcd(\frac{1-\sqrt{1-4mn}}{2},n)=qt $$
Secondly, I assume here that $\sqrt{1-4mn}$ is an integer (it does not seem obvious why it is so).
We want to show that $s$ is $1$. then $s$ divides $\frac{1+\sqrt{1-4mn}}{2}$, and $s$ divides $\frac{n}{p}=q$. So that $s$ must be a  divisor of $q$.
Now because of what you have shown $s$ divides $q$ which divides $\frac{1-\sqrt{1-4mn}}{2}$. Now $s$ divides both $\frac{1+\sqrt{1-4mn}}{2}$ and $\frac{1-\sqrt{1-4mn}}{2}$ so it divides their sum which is one. So $s=1$.
Of course, the same thing applies to $t$ and you are good.


text:
Q: Maximum reach node in a Graph Given a DAG(Directed Acyclic Graph) I want to find the node with maximum reach, or rather, how many nodes can be reached by a single node.
Tried doing BFS by topological order but it doenst work because the sourse might not be the maximum reach source
I couldnt find it but if this has already been asked please redirect me to the correct answer and I'll delete this post.
Thanks


text:
Q: Receiving SMS from Twilio sent with test credentials? I sent SMS using Twilio test credentials (https://www.twilio.com/console/project/settings) as described here (https://www.twilio.com/docs/iam/test-credentials#test-sms-messages).
Is there any possibility to view SMS body?
Or are there any other possibilities to receive SMS from Twilio not spending money (near 0.09$ to my Country)?

A: If you want to send an actual SMS, then you are charged for sending the SMS. The test credentials are more for exercising the API. You cannot view the message log using the test credentials, ("message": "Resource not accessible with Test Account Credentials").
How To Use Twilio Test Credentials with Magic Phone Numbers


text:
Q: Simple regular expression replacing colons I need  a simple regexp for php preg_replace:
Input: Quick brown :no: fox etc
Output: Quick brown !|no|! fox etc
:something:
to
!|something|!

A: Try this:
$str = preg_replace('/:([^:]+):/', '!|\\1|!', $str);

A: $output = preg_replace('/:([^ ]+):/', '!|$1|!', $input);

You might want to replace [^ ] with a more specific set, depending on what you are expecting to be in between the :s.

A: That depends on if a space is allowed between the colons. If it isn't:
$out = preg_replace('!:([^ ]+):!', '!|$1|!', $in);

is fine. You may also want to consider using a non-greedy expression instead:
$out = preg_replace('!:(.+?):!', '!|$1|!', $in);

Here is another option:
$out = preg_replace('!:([^:]+):!', '!|$1|!', $in);


text:
Q: javascript promise return pending I'm creating javascript function to get something using promise and async await. but i got Promise  as return. can anyone help me?
here is my code
 class NetworkError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NetworkError';
  }
}

const fetchingUserFromInternet = (isOffline) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (isOffline) {
        reject(new NetworkError('Gagal mendapatkan data dari internet'), null);
      }
      resolve({ name: 'John', age: 18 });
    }, 500);
  })

};

const gettingUserName = async () => {
  const user = await fetchingUserFromInternet(false)
    .then((user) => {
      return user.name
    })
    .catch((rejectedReason) => {
      return rejectedReason
    })
};

module.exports = { fetchingUserFromInternet, gettingUserName, NetworkError };

A: Your gettingUserName method is never returning anything. You should do this:
const gettingUserName = async () => {
  try {
      const user = await fetchingUserFromInternet(false)
      return user.name;
   } catch (e){
      return e;
   }
};

or this:
const gettingUserName = () => {
  return fetchingUserFromInternet(false)
    .then((user) => {
      return user.name
    })
    .catch((rejectedReason) => {
      return rejectedReason
    })
};


text:
Q: Fatal error: Class 'Mage_Concept_Helper_Data' not found in C:\xampp\htdocs\myshop\app\Mage.php on line 547 I try this with Inchoo Tutorial.
This was a common error, I tried to create a configuration to my extension.
this is very basic configuration creation with following files.
my Config.xml file : Path(\app\code\local\Wired\Concept\etc)
<?xml version="1.0"?>
<config>
<modules>
    <Wired_Concept>
        <version>0.1.0</version>
    </Wired_Concept>
</modules>
<global>
    <models>
        <concept>
            <class>Wired_Concept_Model</class>
        </concept>
    </models>
    <helpers>
        <concept>
            <class>Wired_concept_Helper</class>
        </concept>
    </helpers>
 </global>
<adminhtml>
<acl>
    <resources>
        <all>
            <title>Allow Everything</title>
        </all>
        <admin>
            <children>
                <system>
                    <children>
                        <config>
                            <children>
                                <wired>
                                    <title>Wired - All</title>
                                </wired>
                            </children>
                        </config>
                    </children>
                </system>
            </children>
        </admin>
    </resources>
</acl>
</adminhtml>
</config>

My system.xml : Path(\app\code\local\Wired\Concept\etc)
<?xml version="1.0" encoding="UTF-8"?>
<config>
<tabs>
    <wired translate="label" module="concept">
        Wired Extensions
        <sort_order>100</sort_order>
    </wired>
</tabs>
<sections>
    <wired translate="label" module="concept">
        Extension Options
        <tab>wired</tab>
        <sort_order>1000</sort_order>
        <show_in_default>1</show_in_default>
        <show_in_website>1</show_in_website>
        <show_in_store>1</show_in_store>
    </wired>
<groups>
<wired_group translate="label" module="concept">
                My Extension Options
                <frontend_type>text</frontend_type>
                <sort_order>1000</sort_order>
                <show_in_default>1</show_in_default>
                <show_in_website>1</show_in_website>
                <show_in_store>1</show_in_store>

                <fields>
                    <wired_input translate="label">
                        My Input Field:
                        <comment>My Comment</comment>
                        <frontend_type>text</frontend_type>
                        <sort_order>20</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                    </wired_input>
                    <wired_select translate="label">
                        My Dropdown:
                        <comment>Source model provider Magento's default Yes/No values</comment>
                        <frontend_type>select</frontend_type>
                        <sort_order>90</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                        <source_model>adminhtml/system_config_source_yesno</source_model>
                    </wired_select>
                </fields>
            </wired_group>
        </groups>
</sections>
</config>

My Data.php Helper File : Path(app\code\local\Wired\Concept\Helper)
<?php
class Wired_Concept_Helper_Data extends Mage_Core_Helper_Abstract
{
}

My Wired_Concept.xml file : Path(app\etc\modules)
<?xml version="1.0" encoding="utf-8"?>
<config>
<modules>
    <Wired_Concept>
        <active>true</active>
        <codePool>local</codePool>
    </Wired_Concept>
</modules>
</config>

I tried several ways and read several pages.But i can't figure out my problem, Definitely i can understand my helper file is missing some thing, with my eye i can't see that.
Pls Help me to figure it out.

A: You have declared the Helper class wrongly in config.xml.
Check below for  your code snippet
<helpers>
        <concept>
            <class>Wired_concept_Helper</class>
        </concept>
    </helpers>

Here the class should be
<class>Wired_Concept_Helper</class>

A: 1.You missed out the closing tag </config> in app\etc\modules\Wired_Concept.xml. So that it not appear in admin configuration section and cause error.
2.You have to close </wired> tag after </groups> tag in \app\code\local\Wired\Concept\etc\system.xml.
Please refer and replace the code below in system.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<tabs>
    <wired translate="label" module="concept">
        Wired Extensions
        <sort_order>100</sort_order>
    </wired>
</tabs>
<sections>
    <wired translate="label" module="concept">
        Extension Options
        <tab>wired</tab>
        <sort_order>1000</sort_order>
        <show_in_default>1</show_in_default>
        <show_in_website>1</show_in_website>
        <show_in_store>1</show_in_store>

        <groups>
            <wired_group translate="label" module="concept">
                My Extension Options
                <frontend_type>text</frontend_type>
                <sort_order>1000</sort_order>
                <show_in_default>1</show_in_default>
                <show_in_website>1</show_in_website>
                <show_in_store>1</show_in_store>

                <fields>
                    <wired_input translate="label">
                        My Input Field:
                        <comment>My Comment</comment>
                        <frontend_type>text</frontend_type>
                        <sort_order>20</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                    </wired_input>
                    <wired_select translate="label">
                        My Dropdown:
                        <comment>Source model provider Magento's default Yes/No values</comment>
                        <frontend_type>select</frontend_type>
                        <sort_order>90</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                        <source_model>adminhtml/system_config_source_yesno</source_model>
                    </wired_select>
                </fields>
            </wired_group>
        </groups>
    </wired>
</sections>
</config>

Now check in your admin section


text:
Q: syntax error when trying to input date and time I just started with SQL and I'm having a problem when trying to insert an date and time.
The table structure:
CREATE TABLE Voo_Pac
(
     codReserva INT NOT NULL PRIMARY KEY,
     DataCont DATE,
     HoraCont TIME
);

Code I'm trying to use to insert date and time:
INSERT INTO Voo_Pac (codReserva, DataCont, HoraCont)
VALUES (1), (15-08-2019), (12:13:52);

When I try to execute the code, it gives me the following message:

Error 1: could not prepare statement (1 near ":13": syntax error)

A: I assume you are using MySQL/MariaDB/SQL Server because of the TIME datatype?
Your insert should be
INSERT INTO Voo_Pac (codReserva, DataCont, HoraCont)
VALUES (1, '2019-08-15', '12:13:52');

see demo

A: You at least need quotes. And depending on your DB maybe a CAST to the apropiated type
INSERT INTO Voo_Pac (codReserva, DataCont, HoraCont)
VALUES 1, '15-08-2019', '12:13:52';


text:
Q: environment aligned does not align on the left side despite fleqn option I have the following code:
\documentclass[twoside,leqno]{article}

\usepackage[fleqn]{mathtools}

\setlength{\mathindent}{14bp}

\begin{document}

\begin{equation}\label{14}
\left\{

    \begin{aligned}
        \begin{split}
            T(E_1 \Fcap  E_2) &= T(E_1) \Fcap  T(E_2) \\
            T(E_1 \Fcup  E_2) &= T(E_1) \Fcup  T(E_2)
        \end{split}\\
        \begin{split}
            H(E_1 \Fcap  E_2)&=\left[ T(E_1) \Fcap  T(E_2) \right] \Fcup  \left[-(E_1 \Fcap E_2)\right] \\
                             &=\left[ T(E_1) \Fcap  T(E_2) \right] \Fcup  \left[-(E_1) \Fcup T(-E_2)\right] \\
                             &=\left[ T(E_1) \Fcap  T(E_2) \right] \Fcup  T(-E_1) \Fcup  T(-E_2)
        \end{split}\\
        \begin{split}
            H(E_1 \Fcup  E_2) &= T(E_1\Fcup E_2) \Fcup  \left[T(-E_1\Fcup E_2) \right]  \\
                              &= T(E_1\Fcup E_2) \Fcup  \left[T(-E_1 \Fcap -E_2) \right]  \\
                              &= T(E_1)\Fcup T(E_2) \Fcup  \left[T(-E_1) \Fcap  T(-E_2) \right]
        \end{split}
    \end{aligned}
  \right.

\end{equation}

\end{document}

The result is the following:
I would like to have the first two lines left-aligned. I unsuccessfully tried several solutions. Can somebody help me?

A: *

*No blank line inside equation

*No split

*Remove the redundant (and harmful) \left and \right.

I also added some vertical space to better distinguish the equation groups.
I provided dummy definitions for \Fcup and \Fcap just to make the code compilable.
\documentclass[twoside,leqno]{article}

\usepackage[fleqn]{mathtools}

\setlength{\mathindent}{14bp}
\newcommand{\Fcap}{\cap}
\newcommand{\Fcup}{\cup}

\begin{document}

\begin{equation}\label{14}
\left\{
  \begin{aligned}
    T(E_1 \Fcap  E_2) &= T(E_1) \Fcap  T(E_2) \\[1ex]
    T(E_1 \Fcup  E_2) &= T(E_1) \Fcup  T(E_2) \\[1ex]
    H(E_1 \Fcap  E_2) &=[ T(E_1) \Fcap  T(E_2) ] \Fcup  [-(E_1 \Fcap E_2)] \\
                      &=[ T(E_1) \Fcap  T(E_2) ] \Fcup  [-(E_1) \Fcup T(-E_2)] \\
                      &=[ T(E_1) \Fcap  T(E_2) ] \Fcup  T(-E_1) \Fcup  T(-E_2) \\[1ex]
    H(E_1 \Fcup  E_2) &= T(E_1\Fcup E_2) \Fcup  [T(-E_1\Fcup E_2) ]  \\
                      &= T(E_1\Fcup E_2) \Fcup  [T(-E_1 \Fcap -E_2) ]  \\
                      &= T(E_1)\Fcup T(E_2) \Fcup  [T(-E_1) \Fcap  T(-E_2) ]
  \end{aligned}
\right.
\end{equation}

\end{document}

From the comments, I guess that you want a better definition for \Fcup and \Fcap:
\documentclass[twoside,leqno]{article}

\usepackage[fleqn]{mathtools}

\setlength{\mathindent}{14bp}
\newcommand{\Fcap}{\mathbin{{}_\cap\kern-\scriptspace}}
\newcommand{\Fcup}{\mathbin{{}^\cup\kern-\scriptspace}}

\begin{document}

\begin{equation}\label{14}
\left\{
  \begin{aligned}
    T(E_1 \Fcap  E_2) &= T(E_1) \Fcap  T(E_2) \\[1ex]
    T(E_1 \Fcup  E_2) &= T(E_1) \Fcup  T(E_2) \\[1ex]
    H(E_1 \Fcap  E_2) &=[ T(E_1) \Fcap  T(E_2) ] \Fcup  [-(E_1 \Fcap E_2)] \\
                      &=[ T(E_1) \Fcap  T(E_2) ] \Fcup  [-(E_1) \Fcup T(-E_2)] \\
                      &=[ T(E_1) \Fcap  T(E_2) ] \Fcup  T(-E_1) \Fcup  T(-E_2) \\[1ex]
    H(E_1 \Fcup  E_2) &= T(E_1\Fcup E_2) \Fcup  [T(-E_1\Fcup E_2) ]  \\
                      &= T(E_1\Fcup E_2) \Fcup  [T(-E_1 \Fcap -E_2) ]  \\
                      &= T(E_1)\Fcup T(E_2) \Fcup  [T(-E_1) \Fcap  T(-E_2) ]
  \end{aligned}
\right.
\end{equation}

\end{document}


text:
Q: PrintQueue is the printer the default printer? I'm making my own dialog for printing in my application, now I have this code to put all the printers in a combobox:
        PrintServer server = new PrintServer();

        foreach (PrintQueue queue in server.GetPrintQueues())
        {
            cboPrinters.Items.Add(queue.FullName);
        }

However, I would need select the default printer, how can I see which one is the default printer?

A: var DefaultPrinter = new LocalPrintServer().DefaultPrintQueue;


text:
Q: Upgrade angular 2 dependencies inside angular2-cli project After playing around with angular2 and following angular2 guide in thier website I tryied to move to angular2-cli but angular2-cli project doesnt have the most updated dependencies so the compiler give me some errors about some commands in the code.
I want to upgrade all of the dependencies like core,router and more.
the most updated router need the most updated core but when I try to do: npm install core -g, i get a lots of errors.
What is the best and fast way to upgrade all the exsisting dependencies?
Here are the package.json of angular-cli and angular website:
angular2-cli - orginial package.json:
{
  "name": "angular2-projects",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng serve",
    "postinstall": "typings install",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "2.0.0-rc.3",
    "@angular/compiler": "2.0.0-rc.3",
    "@angular/core": "2.0.0-rc.3",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.3",
    "@angular/platform-browser": "2.0.0-rc.3",
    "@angular/platform-browser-dynamic": "2.0.0-rc.3",
    "@angular/router": "3.0.0-alpha.8",
    "es6-shim": "0.35.1",
    "reflect-metadata": "0.1.3",
    "rxjs": "5.0.0-beta.6",
    "systemjs": "0.19.26",
    "zone.js": "0.6.12"
  },
  "devDependencies": {
    "angular-cli": "1.0.0-beta.9",
    "codelyzer": "0.0.20",
    "ember-cli-inject-live-reload": "1.4.0",
    "jasmine-core": "2.4.1",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "0.13.22",
    "karma-chrome-launcher": "0.2.3",
    "karma-jasmine": "0.3.8",
    "protractor": "3.3.0",
    "ts-node": "0.5.5",
    "tslint": "3.11.0",
    "typescript": "1.8.10",
    "typings": "0.8.1"
  }
}

most updated angular2 dependencies from angular2 website:
{
  "dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",
    "core-js": "^2.4.0",
    "reflect-metadata": "0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "0.6.12",
    "angular2-in-memory-web-api": "0.0.14",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0"
  }
}

A: Once you've updated your dependencies in the packages.json, delete the node_modules directory, and then run "npm install." That will install all the packages from your configuration.

A: I'm unsure if the question has been answered but to give a direct answer, the easiest and fastest way to upgrade all existing dependencies in a package.json file is to go into the folder that houses said file (or any child thereof) and run the following:
npm update

That will update all dependencies (dev included) to the latest supported versions inside your package.json and install them for you, ready to use. Doing it this way also has the added benefit of meaning that if there are versions of libraries that don't work well together, the update process will steer clear of them.
You can even run npm outdated after the update to see what libraries you have, what you need and if there are any updates on the NPM registry.


text:
Q: IDEA start a non-existing templates? have problem with IDEA?
I create new Spring Boot project, with dependency Spring Web, Spring Security, Spring JPA and others
Create two simple class

*

*main class

*Controller Class
@Controller
public class {
@GetMapping("")
public String Home() {
    return "homes";
}

}
And simple templates "homes.html"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Code Java</title>
</head>
<body>
<h1> Welcome to home JVM</h1>

</body>
</html>

WHY MY IDEA START THIS???   https://drive.google.com/drive/folders/1dnn-IKkpaBeouyqnGU13YLf1GBPVd_jQ?usp=sharing
WHAT IS IT ???? in this link different template, not my!
but port is my, localhost 9092/
this port is  - localhost 9092/login?  where did login come from with this templates ?
my link in @GetMapping (""), not (/login)
PLS HELP !
in properties port=9092

A: You have added spring security dependency in your pom.xml and that is the reason spring is securing all the endpoints by default.
Either remove the dependency or configure it to allow access to wanted endpoints.

A: I think this happens because of Adding the dependencies of Spring Security to you pom.xml, which automatically securing the endpoints by default.
try removing this dependency or configure it to allow access to the endpoint you want.


text:
Q: CSS: different
* parent-child backgrounds and sizes

   Parent

Child1

Child2

Child3

.menu3 {
background: url(../images/menu3.png) no-repeat;
float:left;
width:134px;
height:50px;}

.menu3 a:hover {
background: url(../images/menu3-hover.png) no-repeat;
float:left;
width:134px;
height:50px;}

    ul.cssMenuA ul li {
        float:left;
        background: #FFA900;
        width: 90px;
        height:25px;
        display: inline;
    }

    ul.cssMenuA ul li a {
        background: #FFA900;
        width: 90px;
        height:25px;
        display: block;
        font-family: Arial, Times New Roman, Tahoma;
        font-size: 14px;
        color:#000000;
    }

    ul.cssMenuA ul li a:hover{
        background: #FFA900;
        width: 90px;
        height:25px;
        display: inline;
        font-family: Arial, Times New Roman, Tahoma;
        font-size: 14px;
        color:#FFF;
    }

I would like to make my Parent ul/li and child ul/li to have different, but fixed sizes. I have defined a background image for my Parent item class="menu3", but I want a different non-image Child1, 2 and 3 class="cssMenuA". But the children are using also the image, as the parent item.
I hope you understand my problem and hope to help me out with this issue. Thank you in advance.

A: Simply change from .menu3 a:hover {} to .menu3 > li > a:hover :
.menu3 > li > a:hover {
    background: url(../images/menu3-hover.png) no-repeat;
    float:left;
    width:134px;
    height:50px;
}

With this CSS, you'll search for direct
 children, and in those, direct  children (which means you don't have to care about subchildren ).


text:
Q: CSS3 or CSS 3, HTML5 or HTML 5: what should we use in question titles and body? Which is better for search and accuracy?

*

*CSS3 or CSS 3

*HTML5 or HTML 5
What should we use in question titles and content?

A: It doesn't matter: We will never get people to stick to one standard anyway.
This is where tagging comes in. There, there exists a standard: css3 and html5. It's enforced by the system - there can't be a tag named css 3 or html 5.

A: The correct names:

*

*HTML5

*CSS3
Well, to be honest, I can't find an reference to an official name of CSS3, because it seems to be splitted.


text:
Q: How to Control Padding Space Between X Axis Data Points I am trying to control the spacing between, in this case, columns on a chart. I need access to the space between each bar and the space between each set of bars (the big white space between them in the picture). I have spent a bunch of time reading other posts and the documentation but for the life of me I can't find exactly what I am looking for.
Here is the jsFiddle of this example. It's a mash of things, being used for a POC.
https://jsfiddle.net/ek6za4m7/
I have already tried this
  xAxis: {
    labels: {
      padding: 1
    }
  }

A: You can use

groupPadding:0.4

property of column to increase or decrese the gap between group of columns.

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'Monthly Average Rainfall'
    },
    subtitle: {
        text: 'Source: WorldClimate.com'
    },
    xAxis: {
        categories: [
            'Jan',
            'Feb',
            'Mar',
            'Apr',
            'May',
            'Jun',
            'Jul',
            'Aug',
            'Sep',
            'Oct',
            'Nov',
            'Dec'
        ],
        crosshair: true
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Rainfall (mm)'
        }
    },
    tooltip: {
        headerFormat: '{point.key}
',
        pointFormat: '
{series.name}: 	' +
            '{point.y:.1f} mm
',
        footerFormat: '
',
        shared: true,
        useHTML: true
    },
    plotOptions: {
        column: {
            groupPadding:0.4
        }
    },
    series: [{
        name: 'Tokyo',
        data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]

    }, {
        name: 'New York',
        data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]

    }, {
        name: 'London',
        data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]

    }]
});

API Reference: https://api.highcharts.com/highcharts/plotOptions.column.groupPadding


text:
Q: Pagination query using SQL I have a table called 'items'
It has the following columns: id, name, stock, price, and category_id.
My query is
SELECT * FROM items WHERE category_id = {$category_id} LIMIT 10;

my logic for next page is store all ids in a variable called $oldIds and the next query is:
SELECT * FROM items WHERE category_id = {$category_id} AND id NOT IN ($oldIds)  LIMIT 10

for another page is i store again the ids from 1st page and 2nd page  do again the query
SELECT * FROM items WHERE category_id = {$category_id} AND id NOT IN ($oldIds)  LIMIT 10

Do i continue using this style of query or is there a better way of querying?

A: for mysql
First statement should be:
mysql_query("SELECT * FROM {$statement} ORDER BY datetime ASC LIMIT {$limit} OFFSET {offset}

if 10 records per page is what you are looking for and you want to show records on page 2 i.e. records 11-20 your query will look like:
mysql_query("SELECT * FROM {$statement} ORDER BY datetime ASC LIMIT 10 OFFSET 10


text:
Q: How can i set query parameter dynamically to request.GET in Django OVERVIEW

A url with query parameters looks like.
http://example.api.com/search/?name=jhon&age=26

and on view if i am using django-filter all parameters are automatically extracted from request and it will return a filtered query-set .
views.py
class SearchView(TemplateView):
   template_name = "search.html"

   def get_queryset(self):
       return SearchFilter(request.GET, queryset=Model.objects.all()).qs

   def get_context_data(self, **kwargs):
      context = super(SearchView, self).get_context_data(**kwargs)
      return context

If i want to extract it manually from request.GET i can do.
def get_queryset(self):
   # extracting query parameter
   q = self.request.GET.get('name')

PROBLEM STATEMENT

My search url looks like
 http://example.api.com/search/jhon-26

I am doing this because i don't want to reveal keys like 'name' and 'age' to public, this is for security abstraction these are the column of my db table .
I am getting jhon-26 in **kwargs, I want to split it and set as query parameter to request.GET so that my filter class will work fine
QUESTION

Is there anything to set attribute to request.GET?
# may be any set function available for this
self.request.GET.set('name', 'jhon')

How can i achieve this.

A: I found solution to set query parameters to request.GET here
As request.GET QueryDict instance is immutable so we can not modify it directly so for that we need to set its _mutable property to True
if not request.GET._mutable:
   request.GET._mutable = True

# now you can edit it
request.GET['name'] = 'jhon'
request.GET['age'] = 26

A: Well, you can do what django-filter does for you by simply saying:
  result = Model.objects.filter(**dict)

However, for request.GET, you'd have to format it to make a valid dictionary since it's values are usually list. You can simply do:
  formatted = {key: dictionary.get(key)[0] for key in dict(request.GET).keys()}

And then you can add the remaining variables into it:
   formatted['age'] = 26 //As extracted from **kwargs. etc.

And then do:
  result = Model.objects.filter(**formatted)

If you do not necessarily need to use request.GET (Since there's a way around what django-filter does), then you can simply form your dictionary and use it in the model's filter method.
By the way, why are you using request.GET if you do not want the public to see your data? How did you form your url? You may want to Ignore all of that as far as your code is working fine anyway!

A: Build your filter dynamically like so;
    query_data={}
    name = request.query_params.get('name')
    age = request.query_params.get('age')
    if name is not None:
        query_data['name'] = name
    if age is not None:
        query_data['age'] = age

    return Model.objects.filter(**query_data)


text:
Q: Convert IP (string) into long in elasticsearch/kibana scripted fields I have a field in a doc that is a string representation of ipv4 ("1.2.3.4"), the name of the field is "originating_ip".
I'm trying to use the scripted fields using the painless language in order to add a new field (originating_ip_calc) to have the int (long) representation of said IPv4.
The following script works in groovy (and from what I understand this should basically work almost the same), but it seems like almost is not in this specific case.
String[] ipAddressInArray = "1.2.3.4".split("\\.");

long result = 0;
for (int i = 0; i < ipAddressInArray.length; i++) {
    int power = 3 - i;
    int ip = Integer.parseInt(ipAddressInArray[i]);
    long longIP = (ip * Math.pow(256, power)).toLong();
    result = result + longIP;
}
return result;

I also looking in this question and as you can see from the code above it is based on one of the answers there.
Also tried to work with InetAddress but no luck.

A: With Elasticsearch painless scripting you can use code like the following:
POST ip_search/doc/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "originating_ip_calc": {
      "script": {
        "source": """
String ip_addr = params['_source']['originating_ip'];
def ip_chars = ip_addr.toCharArray();
int chars_len = ip_chars.length;
long result = 0;
int cur_power = 0;
int last_dot = chars_len;
for(int i = chars_len -1; i>=-1; i--) {
  if (i == -1 || ip_chars[i] == (char) '.' ){
    result += (Integer.parseInt(ip_addr.substring(i+ 1, last_dot)) * Math.pow(256, cur_power));
    last_dot = i;
    cur_power += 1;
  }
}
return result
""",
        "lang": "painless"
      }
    }
  },
  "_source": ["originating_ip"]
}

(Note that I used Kibana console to send the request to ES, it does some escaping to make this a valid JSON before sending.)
This will give a response like this:
"hits": [
  {
    "_index": "ip_search",
    "_type": "doc",
    "_id": "2",
    "_score": 1,
    "_source": {
      "originating_ip": "10.0.0.1"
    },
    "fields": {
      "originating_ip_calc": [
        167772161
      ]
    }
  },
  {
    "_index": "ip_search",
    "_type": "doc",
    "_id": "1",
    "_score": 1,
    "_source": {
      "originating_ip": "1.2.3.4"
    },
    "fields": {
      "originating_ip_calc": [
        16909060
      ]
    }
  }
]

But why does it have to be this way?
Why does the approach with .split not work?
If you send the code from the question to ES it replies with an error like this:
      "script": "String[] ipAddressInArray = \"1.2.3.4\".split(\"\\\\.\");\n\nlong result = 0;\nfor (int i = 0; i < ipAddressInArray.length; i++) {\n    int power = 3 - i;\n    int ip = Integer.parseInt(ipAddressInArray[i]);\n    long longIP = (ip * Math.pow(256, power)).toLong();\n    result = result + longIP;\n}\nreturn result;",
      "lang": "painless",
      "caused_by": {
        "type": "illegal_argument_exception",
        "reason": "Unknown call [split] with [1] arguments on type [String]."

This is mainly due to the fact that Java's String.split() is not considered safe to use (because it creates regex Pattern implicitly). They suggest to use Pattern#split but to do so you should have regexes enabled in your index.
By default, they are disabled:
      "script": "String[] ipAddressInArray = /\\./.split(\"1.2.3.4\");...
      "lang": "painless",
      "caused_by": {
        "type": "illegal_state_exception",
        "reason": "Regexes are disabled. Set [script.painless.regex.enabled] to [true] in elasticsearch.yaml to allow them. Be careful though, regexes break out of Painless's protection against deep recursion and long loops."

Why do we have to do an explicit cast (char) '.'?
So, we have to split the string on dots manually. The straightforward approach is to compare each char of the string with '.' (which in Java means char literal, not String).
But for painless it means String. So we have to make an explicit cast to char (because we are iterating over an array of chars).
Why do we have to work with char array directly?
Because apparently painless does not allow .length method of String as well:
    "reason": {
      "type": "script_exception",
      "reason": "compile error",
      "script_stack": [
        "\"1.2.3.4\".length",
        "         ^---- HERE"
      ],
      "script": "\"1.2.3.4\".length",
      "lang": "painless",
      "caused_by": {
        "type": "illegal_argument_exception",
        "reason": "Unknown field [length] for type [String]."
      }
    }

So why is it called painless ?
Although I can't find any historical note on the naming after quick googling, from the documentation page and some experience (like above in this answer) I can infer that it is designed to be painless to use in production.
It's predecessor, Groovy, was a ticking bomb due to resources usage and security vulnerabilities. So Elasticsearch team created a very limited subset of Java/Groovy scripting which would have predictable performance and would not contain those security vulnerabilities, and called it painless.
If there is anything true about painless scripting language, is that it is limited and sandboxed.


text:
Q: Error: The page has been destroyed and can no longer be used I'm developing an add-on for the first time. It puts a little widget in the status bar that displays the number of unread Google Reader items. To accommodate this, the add-on process queries the Google Reader API every minute and passes the response to the widget. When I run cfx test I get this error:

Error: The page has been destroyed and can no longer be used.

I made sure to catch the widget's detach event and stop the refresh timer in response, but I'm still seeing the error. What am I doing wrong? Here's the relevant code:
// main.js - Main entry point
const tabs = require('tabs');
const widgets = require('widget');
const data = require('self').data;
const timers = require("timers");
const Request = require("request").Request;

function refreshUnreadCount() {
    // Put in Google Reader API request
    Request({
        url: "https://www.google.com/reader/api/0/unread-count?output=json",
        onComplete: function(response) {
            // Ignore response if we encountered a 404 (e.g. user isn't logged in)
            // or a different HTTP error.
            // TODO: Can I make this work when third-party cookies are disabled?
            if (response.status == 200) {
                monitorWidget.postMessage(response.json);
            } else {
                monitorWidget.postMessage(null);
            }
        }
    }).get();
}

var monitorWidget = widgets.Widget({
    // Mandatory widget ID string
    id: "greader-monitor",

    // A required string description of the widget used for
    // accessibility, title bars, and error reporting.
    label: "GReader Monitor",
    contentURL: data.url("widget.html"),
    contentScriptFile: [data.url("jquery-1.7.2.min.js"), data.url("widget.js")],

    onClick: function() {
        // Open Google Reader when the widget is clicked.
        tabs.open("https://www.google.com/reader/view/");
    },

    onAttach: function(worker) {
        // If the widget's inner width changes, reflect that in the GUI
        worker.port.on("widthReported", function(newWidth) {
            worker.width = newWidth;
        });

        var refreshTimer = timers.setInterval(refreshUnreadCount, 60000);

        // If the monitor widget is destroyed, make sure the timer gets cancelled.
        worker.on("detach", function() {
            timers.clearInterval(refreshTimer);
        });

        refreshUnreadCount();
    }
});

// widget.js - Status bar widget script

// Every so often, we'll receive the updated item feed. It's our job
// to parse it.
self.on("message", function(json) {
    if (json == null) {
        $("span#counter").attr("class", "");
        $("span#counter").text("N/A");
    } else {
        var newTotal = 0;
        for (var item in json.unreadcounts) {
            newTotal += json.unreadcounts[item].count;
        }

        // Since the cumulative reading list count is a separate part of the
        // unread count info, we have to divide the total by 2.
        newTotal /= 2;
        $("span#counter").text(newTotal);

        // Update style
        if (newTotal > 0)
            $("span#counter").attr("class", "newitems");
        else
            $("span#counter").attr("class", "");
    }

    // Reports the current width of the widget
    self.port.emit("widthReported", $("div#widget").width());
});

Edit: I've uploaded the project in its entirety to this GitHub repository.

A: I guess that this message comes up when you call monitorWidget.postMessage() in refreshUnreadCount(). The obvious cause for it would be: while you make sure to call refreshUnreadCount() only when the worker is still active, this function will do an asynchronous request which might take a while. So by the time this request completes the worker might be destroyed already.
One solution would be to pass the worker as a parameter to refreshUnreadCount(). It could then add its own detach listener (remove it when the request is done) and ignore the response if the worker was detached while the request was performed.
function refreshUnreadCount(worker) {
    var detached = false;
    function onDetach()
    {
        detached = true;
    }
    worker.on("detach", onDetach);

    Request({
        ...
        onComplete: function(response) {
            worker.removeListener("detach", onDetach);
            if (detached)
                return;  // Nothing to update with out data

            ...
        }
    }).get();
}

Then again, using try..catch to detect this situation and suppress the error would probably be simpler - but not exactly a clean solution.

A: I've just seen your message on irc, thanks for reporting your issues.
You are facing some internal bug in the SDK. I've opened a bug about that here.
You should definitely keep the first version of your code, where you send messages to the widget, i.e. widget.postMessage (instead of worker.postMessage). Then we will have to fix the bug I linked to in order to just make your code work!!
Then I suggest you to move the setInterval to the toplevel, otherwise you will fire multiple interval and request, one per window. This attach event is fired for each new firefox window.

A: I think if you use the method monitorWidget.port.emit("widthReported", response.json); you can fire the event. It the second way to communicate with the content script and the add-on script.

*

*Reference for the port communication

*Reference for the communication with postMessage


text:
Q: Making InputScope Property Work for Windows IoT Core What is needed in order to make the InputScope effective for Windows IoT Core development in order to limit the On-Screen Keyboard layout? I know from the following article that:

"This info applies only to the SIP. It does not apply to hardware
  keyboards or the On-Screen Keyboard available in the Windows Ease of
  Access options."

This question is more of a thought process one than asking for a code sample. What does a developer need in order to make such a major change in case it does not already exist?


text:
Q: How to open port 1973+ on Google Compute Engine Hello I would like to know how to open some ports, i already opened port 80 using this
tcp: 1-65535; udp: 1-65535
But I only managed to get some ports open, the ports I really need are:
1656, 1971, 1973, 1975, 1976, 1977
If someone could tell me which method to use, I would greatly appreciate


text:
Q: Keyboard Shortcut to select flutter widget in vs code Is there any shortcut in vs code to select all the code inside a highlighted Flutter Widget ??
and what  is it ??
because it is getting a bit messy with long code to detect the end of the widget

A: I don't know if there is a shortcut. But if your problem only is to find the end of a widget I think I might have a solution for you.
I would suggest you to use the dart code formatting. After that, your code should not only be perfectly formatted but there should also be automatically created comments at the end of the widget (e.g. // Text).
You can format your code by right clicking on it and selecting the "format code". In addition you can set Visual Studio to format your code every time you hot reload it. I found this to be immensely helpful.
I really hope I could help you with the problem.


text:
Q: iMovie - how to shorten several videos at the same time? I have like 40 videos, the lenght between between 10-12 minutes and I would need all of them shorten to 1 minute. Is there any way to shorten all videos at the same time in OS X (iMovie)?
To shorten one video by one would be a bit harder...
Thank you.

A: From the command-line, you can use ffmpeg like so:
ffmpeg -i input.mp4 -c copy -t 00:01:00 output.mp4

To do every *.mp4 in a directory, you can utilise a for loop:
for f in *.mp4; do ffmpeg -i "$f" -c copy -t 00:01:00 "${f/.mp4/-short.mp4}"; done

You can get more information about seeking with ffmpeg here.


text:
Q: How to I move Stripe/Apple Pay to the bottom of Checkout page? I'd like to move Apple Pay/GPay - Stripe from the top of the Checkout page to somewhere above the Submit order button. Possibly with woocommerce_review_order_before_submit or woocommerce_after_checkout_form, but I have no idea what to target to remove action and then to add it back in? Cannot find any available or working hooks that could do that.
I've tried this, but it doesn't work:
/*
* Adds then moves Apple Pay button on the checkout page.
*/

add_filter( 'wc_stripe_show_payment_request_on_checkout', '__return_true' );

remove_action( 'woocommerce_checkout_before_customer_details', array( WC_Stripe_Payment_Request::instance(), 'display_payment_request_button_html' ), 1 );
remove_action( 'woocommerce_checkout_before_customer_details', array( WC_Stripe_Payment_Request::instance(), 'display_payment_request_button_separator_html' ), 2 );

add_action( 'woocommerce_after_checkout_form', array( WC_Stripe_Payment_Request::instance(), 'display_payment_request_button_html' ), 2 );
add_action( 'woocommerce_after_checkout_form', array( WC_Stripe_Payment_Request::instance(), 'display_payment_request_button_separator_html' ), 1 );

Any suggestions?
Thank you


text:
Q: PHP Require file inside Static Method In my class I've got a Method, that includes diffrent Files based on the input.
The Files are included correctly => var_dump shows "true".
BUT!! If I want to access the included variable, it tells me, that it's not defined....
The included file:
<?php
$cpucooler = array(
array(
    "Name" => "Boxed CPU Lüfter",
    "Sockel" => "Alle",
    "Leistung" => 20,
    "RPM" => 2000,
    "Preis" => 0
));
?>

The Class Method:
/**
 * Get Hardware for classes
 * @param string $type Hardware type
 * @return array
 */
public static function getHardware($type) {
    switch ($type) {
        case 'cpucooler':
            require_once "hardware/cpucooler.php";
            var_dump($cpucooler); // undefined variable...
            return $cpucooler;
            break;
    }
}

Hope someone can help me

A: File was correctly included, the Problem was, that I used
require_once $file;
return $cpucooler;

instead of
require $file;
return $cpucooler;

Don't know why...

A: I get that error when I cannot include the file.
If including works, I also get the data.
In conclusion, since failing to open the file is not a fatal error (just a warning), you probably have disabled outputting warnings, so you don't see them. If you enable error reporting, you should see the warning.
The exact cause of failure is a guess. Maybe the path is incorrect, because you made a typo, or the case of the name is wrong, or the current directory is different from what you think. (try using an absolute path and/or check using the __DIR__ constant.

A: Make sure that hardware/cpucooler.php is really being included. It's a good practice to use is_file to make sure that you require file that exists in your application.
try {
    $filepath = 'hardware/cpucooler.php';
    if( ! is_file(  $filepath ) ) {
        throw new Exception( $filepath . ' do not exists.' );
    }
    // If exception is thrown, the following code is not executed.
    require $filepath;
    return $cpucooler;
} catch( Exception $e ) {
    echo $e->getMessage();
}


text:
Q: UFT How to pass different datatable for same action in different test cases How to pass different datatable for same action in different test cases
I have three actions and two test cases which calls these action differently.
TC 1 calls action 1 and action 2
TC 2 calls action 1 and action 3 with different data for action 1
I know we could pass different parameters through action call properties but how can we do the same if we are using Data Table?
Thanks in advance for any input

All three Actions are saved as seperate script.
So this is our approach towards automating the application

*

*We are trying to drive the automation from ALM and so mapping ALM parameters with UFT parameter

*We are creating modular scripts for resuability which is defined by a functionality. If same functionality is being used in more than one test case we differentiate the step by the usage of a variable.
Ex: A test case has a process to be run. Either we can use the template which was created earlier or create a new template to initiate the process.
Creation and Using template follow different steps initially but then routes through the same validation. we also have separate manual cases for these. Since only 2 steps are different, we have defined variable which differentiate these using the IF statement. So if variable has value 1, it creates template else run the existing template
Test Case 1 - Create New Template - Calling the modules with the Parameters defined during the call
RunAction "Action1 [Module_1]", oneIteration,  "Create New Template", "Parameter_1", "Parameter_2"
RunAction "Action1 [Module_2]", oneIteration,
Test Case 2 - Use Existing Template - Calling the modules with the Parameters defined during the call
RunAction "Action1 [Module_1]", oneIteration, "Use Existing Template", "Parameter_3", "Parameter_4"
RunAction "Action1 [Module_3]", oneIteration, "Parameter_5", "Parameter_6", "Parameter_7"

*We are minimizing the usage of data table. However there are cases where data table cannot be avoided. Ex: Multiple Forms where user has to add more forms with same fields over and again. These are handled using data sets for each form, from data table. However there are different cases which uses this module and there has to be different data table for each case. How can I implement it? Currently since I am using the local data table from module I am unable to use it for different test case. Is there a way to use the local data table of the Test Case and then pass on the values to module?

Even if there is a way, there are limitations as "Add of form" mentioned in the above is just a part of a large functionality. So if we are to  iterate the module for the number of data sets in the data table, we would only need to include a part of the code in it
Not sure if I am explaining it properly but do let me know if you are unable to understand and I'll try to explain it better

A: Ok, so it sounds like you are trying to do something similar to what I have done... I should add this is not an ideal solution, but for the situation I found myself in, it works!
So I'm assuming Module_1, Module_2, and Module_3 are technically QTP Tests that you never run. Test_1, and Test_2 are also QTP Tests that you DO run(!) - which include RunAction calls as you mention above, plus any other bespoke code for that test. That's fine.
NOTE:  You do not need to have any data anywhere in the datatable of any of the "Modules".
Instead, define each of the Reusable Actions in each "Module" to take input Parameters. Then keep the data for those parameters in the datasheets for Test_1, Test_2 etc - with each local (Action) datasheet with each Test having columns that correspond to the parameters for the reusable actions that are called within that Test Action.
Then call the Reusable Action:
RunAction "Action1 [Module1]", oneIteration,
    dataTable.Value("someParam", dtLocalSheet),
    dataTable.Value("someOtherParam", dtLocalSheet)

Note that it is important to understand - when using Call to Existing action, the DataTable (both dtGlobalSheet and dtLocalSheet) refer to that of the "parent" test, NOT that of the external action - even for the external code - effectively, the datasheet of the "Module" you call out to doesn't exist)
If you need to run Test_1 or Test_2 etc with different data, either:
  1. Simply just add rows to the datasheets within the test, or...
  2. Create a copy of default.xls (the one in the test, not "ReusableActions", and edit in Excel as appropriate - then before each run, copy the required data xls over default.xls, before running the test.
Better yet, if you are using QC / ALM for test management, do some googling on "Business Process Testing with QC/ALM" - and the "Business Component" for QC/ALM - I'm trying to get my current employers to go down that route. Described above is a "hack" to achieve what can be done far more cleanly using BPT....


text:
Q: PHP encode methods Is it possible to encode user's ID# to text value?
For example if the user ID# is '50624' is it possible to convert it to 7 characters text value, something like 'DEGXCVG'?
If I use MD5 for this function I get 16-byte hash value.
The result value should not be longer than 7 or 8  characters.
Edit:
I want that each user has a different text code obtained from the id number.

A: Try changing the integer into a Hexadecimal value using dechex
Anyway if u able to explain your scenario more clear, we may able to provide best solution

A: What are you trying to accomplish with this?
First of all MD5 is not "encryption" it is a one-way hash function. It cannot be reversed. If that is OK for you, why not simply hash your IDs and then take 7-8 characters from the hash? You could MD5 your ID and then take the first 8 characters of the resulting MD5.

A: what you are looking for is called base transformation ... your ID is a base 10 number with the numbers from 0 to 9 represent the digits of that base.
other common bases would be 2 (binary), 16(hexadecimal), or 64(often called base 64 encoding) but you could also take some other base if you like.
i've written a somewhat general base transform code in c# (uint to whatever base string and vice versa) ... shouldn't be that hard to port it to php:
static void Main(string[] args)
{
    foreach (var item in UintToOtherBase(0xDEADBEEF, "01").Reverse())
    {
        Console.Write(item);
    }
    Console.WriteLine();
    Console.WriteLine(OtherBaseToInt(UintToOtherBase(0xDEADBEEF, "01"), "01").ToString("X"));
    Console.WriteLine(UintToOtherBase(0xDEADBEEF, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
}

public static string UintToOtherBase(uint input, string newBaseDigits)
{
    char[] uniqueDigits = newBaseDigits.ToCharArray().Distinct().ToArray();
    uint newBase = (uint)uniqueDigits.Length;
    if (newBase < 2)
    {
        throw new ArgumentException("otherBaseDigits has to contain at least 2 unique chars");
    }
    else
    {
        StringBuilder sb = new StringBuilder();
        while (input != 0)
        {
            uint digit = input % newBase;
            sb.Append(uniqueDigits[digit]);
            input /= newBase;
        }
        return sb.ToString();
    }
}
public static uint OtherBaseToInt(string input, string otherBaseDigits)
{
    string uniqueDigits = new String(otherBaseDigits.ToCharArray().Distinct().ToArray());
    int otherBase = uniqueDigits.Length;
    if (otherBase < 2)
    {
        throw new ArgumentException("otherBaseDigits has to contain at least 2 unique chars");
    }
    else if (input.ToCharArray().Any(x => !uniqueDigits.Contains(x)))
    {
        throw new ArgumentException("an input char was not found in otherBaseDigits");
    }
    else
    {
        uint result = 0;
        int pow = 0;
        foreach (var c in input)
        {
            result += (uint)uniqueDigits.IndexOf(c) * (uint)Math.Pow(otherBase, pow++);
        }
        return result;
    }
}

//edit:
but just to point it out, this is an encoding ... no encryption

A: If a hash function such as MD5 can be used instead of encryption, you could try crc32() instead, which produces shorter (but with much higher chances of collisions) strings.

If you just care about encoding, you could do something simpler:
function encode($id) {
  $id_str = (string) $id;
  $offset = rand(0, 9);
  $encoded = chr(79 + $offset);
  for ($i = 0, $len = strlen($id_str); $i < $len; ++$i) {
    $encoded .= chr(65 + $id_str[$i] + $offset);
  }
  return $encoded;
}

function decode($encoded) {
  $offset = ord($encoded[0]) - 79;
  $encoded = substr($encoded, 1);
  for ($i = 0, $len = strlen($encoded); $i < $len; ++$i) {
    $encoded[$i] = ord($encoded[$i]) - $offset - 65;
  }
  return (int) $encoded;
}

Example:
var_dump(encode(50624)); // string(6) "TKFLHJ"

Encryption version:
define('CRYPTO_KEY', 'Secret key');

function encrypt($id) {
  return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, CRYPTO_KEY, (string) $id, MCRYPT_MODE_ECB));
}

function decrypt($encrypted) {
  return (int) base64_decode(mcrypt_decrypt(MCRYPT_BLOWFISH, CRYPTO_KEY, $encrypted, MCRYPT_MODE_ECB));
}

A: If obscuring is good enough, convert the number to base62 after permuting its bits.

A: I think you can design your own encryption method or take part of md5 hash value.
Btw, the way to encrypt an integer has been discussed in the following post.
Way to encrypt a single int


text:
Q: What does $\int_a^b x dx$ represent? For a planar region $R$, the  $x$ coordinate of centroid is given by the double integral $$\frac1A\iint\limits_R x~dA $$
Similarly is there any geometric significance for the single integral $$\frac1{b-a}\int_a^b x\,dx$$

A: $$\frac1{b-a}\int\limits_a^bxdx=\frac1{b-a}\cdot\frac12(b^2-a^2)$$$$=\frac{b+a}2$$This is the centroid of the region $[a,b]$.


text:
Q: Issues on expiration of laravel 4.2 session in my login i have created sessions, Session::put('lid','somevalue') and Session::put('ltype','somevalue') and in my default blade i did something like
@if(Session->has('ltype')

Hello

@else
//redirect to login page

in my session.php in app/config i already changed the timeout to 5 meaning 5 minutes. i timed it but its already 8 minutes when i refreshed my page it still displayed Hello where it should be redirected to the login already because the session is expired already. am i doing something wrong?

A: You can use the following code:
    @if(Session::has('ltype')

Hello

    @else

you must use :: instead of -> because Session is a static method.


text:
Q: Having different sections with List for each element I want to have different sections for each element i have in List and each different section have different data sheet to display too. This is my tried code i made my sections like i wanted but the data sheet did not display.

  struct ListsView: View {

 @State var states: [String] = ["CA", "MA"]
 @State var block1: [String] = ["John", "Emma", "Winny"]
 @State var block2: [String] = ["Supreme", "Jax", "Louis"]
var body: some View {
    List(states, id: \.self) { state in
        Section(header: Text(state)) {
            List(block1, id: \.self) { b1 in
                Text(b1)
            }
            List(block2, id: \.self) { b2 in
                Text(b2)
            }
        }
    }
  }
 }

A: You do not need sub lists inside your first List. Instead you can achieve this design with a condition logic plus one section inside the first List.
Code is below the image:

struct ListsView: View {
@State var states: [String] = ["CA", "MA"]
@State var block1: [String] = ["John", "Emma", "Winny"]
@State var block2: [String] = ["Supreme", "Jax", "Louis"]
 var body: some View {
    List(states, id: \.self) { state in
        Section(header: Text(state)) {
            ForEach(state == "CA" ? block1 : block2, id: \.self) { b in
                Text(b)
            }
        }

    }
  }
}


text:
Q: To remove bullets in a ul class I am trying to remove the bullets in the left module but with no success.
I have created a class for the ul called .menuxxx and then added the below code to my css file although this does not work still. this can be viewed at http://www.safisafihotels.com/testimonials
.menuxxx ul{

  list-style:none !important;
  list-style-type:none !important;

}

Please guys assist

A: Your menu (ul) has the class menuxxx, not its parent.
It should be:
ul.menuxxx {
    list-style:none !important;
    list-style-type:none !important;
}

A: That is not bullets, its background:

ul li {
  background: url(../images/style1/bodyli.gif) no-repeat 0px 7px;
}

Remove it, then you can see effect.

A: Your css selector is incorrect. Since you want to style a specific menu, use:
ul.menuxxx {
  list-style:none;
  list-style-type:none;
}

which will select it properly.

As for the !important tag, now you have corrected your selector, you can remove it.

If, in fact, you wish to remove the triangles from the "SAFI SAFI HOTELS" section, since they are generated from the declaration:
ul li {
background: url(../images/style1/bodyli.gif) no-repeat 0px 7px;
}

and not, in fact, a list styling element, you can remove that from your declaration.

A: Remove the bullet (background-image)
ul.menuxxx li {
    background: none;
}


text:
Q: HTTP GET request is not triggering an action on website I'm wrote a bot that used selenium to scrape all needed data and performed a few simple tasks. I don't know why I didnt use http requests instead from the start but I am now trying to switch to that. One of the selenium functions used a simple driver.get(url) to trigger an action on the site. Using requests.get, however, does not work.
This selenium code worked
import time
from selenium import webdriver

AM4_URL = 'https://www.airline4.net/?gameType=app&uid=102692112805909972638&uid_token=8adee69e774d89fb6e9f903e7d2afc70&mail=bsgpricecheck@gmail.com&mail_token=286f8bd25bcc32f49a02036102ce072c&device=ios&version=6&FCM=daf5d0d8bf4d7962061eac3a8e4bffa770d6593f31fd5b070d690f244dfb40d1#'

def depart():
    # Load driver and get login url
    if pax_rep > 80:
    driver = webdriver.Firefox(executable_path='C:\webdrivers\geckodriver.exe')
    driver.get(AM4_URL)
    driver.minimize_window()

    driver.get("https://www.airline4.net/route_depart.php?mode=all&ids=x")
    time.sleep(100)

def randfunc():
    depart()

But now im trying to switch over to requests because all the other bot functions work with it. I tried this and it doesn't perform the action.
import requests

# I was able to combine the URLs into one. It still performs the action when on a browser.
dep_url = 'https://www.airline4.net/route_depart.php?mode=all&ids=x?gameType=app&uid=102692112805909972638&uid_token=8adee69e774d89fb6e9f903e7d2afc70&mail=bsgpricecheck@gmail.com&mail_token=286f8bd25bcc32f49a02036102ce072c&device=ios&version=6&FCM=daf5d0d8bf4d7962061eac3a8e4bffa770d6593f31fd5b070d690f244dfb40d1#'

requests.get(dep_url)

I figured this code would work because the url doesnt return any content. I thought it was using a GET request as a command.
I would also like to note, I got the route_depart.php url from an ajax button.
Here's the HTML from that

    <button class="btn" style="display:none;" onclick="Ajax('def227_j22.php','runme');"></button>
    <button class="btn w-100 btn-danger btn-xs" onclick="Ajax('route_depart.php?mode=all&ids=x','runme',this);">
         Depart 5</button>