text:
Q: How colSpan and row Span added to material table Header Angular 7? I'm trying to add rowSpan and colSpan in Angular material Table header. Can anyone help me to achieve  it.
Below is the Attached Header I want to get using material table

A: I have the sample task like you. I just easy to display none with second header.
  <ng-container matColumnDef="position">
     No.
     {{element.position}}
  </ng-container>

  <ng-container matColumnDef="No">
    No
  </ng-container>

Here is my result

You can follow my link to know more:
StackBlitz

A: I ran into the same issue and, using some inspiration from previous answers, found the following to work perfectly.
To achieve the example provided in the question, you will need two table headers. The first will contain the State, Utilities company and Summer Period columns, while the second will contain the data1, data2 & data3 columns. To do this, start with the following:

This piece of code creates a table with two table header rows and, for each data point in your dataSource, one row with 5 cells which use the columns provided.
To properly style these header rows, we need to use rowSpan and colSpan. For each column, we create our ng-container:
<ng-container matColumnDef="state">
  State
  State name here (e.g. {{data.state}})
</ng-container>

<ng-container matColumnDef="company">
  Utilities company
  Utilities company here
</ng-container>

<ng-container matColumnDef="summer">
  Summer

</ng-container>

<ng-container matColumnDef="data1">
  Data 1
  {{data.yourFirstDataPoint}}
</ng-container>

<ng-container matColumnDef="data2">
  Data 2
  {{data.yourSecondDataPoint}}
</ng-container>

<ng-container matColumnDef="data3">
  Data 3
  {{data.yourThirdDataPoint}}
</ng-container>

This creates the desired result for you. If you want, you can add mat-sort definitions to your columns, as well. I hope this makes sense, if not, let me know and I'll try to expand my answer.

A: For your exemple try this

  <ng-container matColumnDef="state">
    state
    alabama
  </ng-container>

  <ng-container matColumnDef="utility">
    utility company
  company1
</ng-container>

  <ng-container matColumnDef="data1">
    {{'data1' | translate}}
    3.45
 </ng-container>

  <ng-container matColumnDef="data2">
    {{'data2' | translate}}
    1.73
  </ng-container>

  <ng-container matColumnDef="data3">
    {{'data3' | translate}}
    0.58
  </ng-container>

  <ng-container matColumnDef="summer">
    {{'summer period' | translate}}

  </ng-container>

I just reverse the order of the summer row because seem to not work this way

A: I just used [attr.colspan] and [attr.rowspan] on my material table

 <ng-container matColumnDef="{{displayedColumns[0]}}">

 </ng-container>
        .............

A: If you want to use native-table features such as colspan and rowspan you will need to use:

  ...

Ref: Native table element tags
For example:

Ref: Serendipity CRM


text:
Q: Correct subproperty relation of OWL data properties I'm building an ontology and I need to create the same semantic relation (the name of the relation is the same as well as the meaning in the domain) between different classes of elements. For example:
 o:ClassA o:hasSemanticRelation xsd:string
 o:ClassB o:hasSemanticRelation xsd:string
 o:ClassC o:hasSemanticRelation xsd:string

My first approach was to create multiple domains for the property but this actually means the intersection of the concepts which is not correct in the domain.
My second approach was to have a super property
 owl:Thing o:hasSemanticRelation xsd:string
 o:hasSemanticRelationA owl:subPropertyOf o:hasSemanticRelation
 o:ClassA o:hasSemanticRelationA xsd:string

Because of the meaning of the hasSemanticRelation I want that every time it is used it can be linked to the same property, i.e., o:hasSemanticRelation
Could anyone give ideas how can I best represent this situation?

A: You might be able to achieve what you're trying to do with a union of classes for the domain; so that instead of multiple domains (which is equivalent to domain intersection) you'd have one single domain which is a union. This can be named or unnamed, depending on your requirements.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add custom css to the leads tab In my custom tabs i simply add the following code to the component:
<ltng:require styles="{!$Resource.globalcss}"/>
and it loads a static resource css file.
How can i load the same css file for "Leads" or "Contacts" tabs in lightning?

A: You cannot.
ltng:require only works in context of Custom Lighting Aura Components. You can load static resources that can be used within your custom components. You cannot utilize this to inject styling into the Standard Tabs.
If you want to customize the look and feel of the Tabs, your only option is to create a Custom Lightning Aura Component and utilize that in a Custom Tab.

A: If you want to customize the appearance of tabs, your have to create a custom Aura Lightning component and use it in a Custom tab.


text:
Q: GCP Error: error: bucket name validation failed I was trying to create a bucket on gcp and I got this error:
Error: error: bucket name validation failed bkt-dlkh-sx-cicd-proj-gcp-projects-build-artifacts--prj-dlkh-sx-b-cicd-o7qz
The message is not very explicit on why is failing, I though it was a regex problem based on https://stackoverflow.com/a/62349388/13686796 but not really.

A: It turned out it was too long. The limit on GCP is 63 characters

A: Yes, @valcapp is correct. The bucket name you have given seems to be 76 characters.
Please check the docs for more information about the limits
https://cloud.google.com/storage/docs/buckets#naming


text:
Q: Jquery Ajax how to do polling on Clientside I am familiar with using Jquery Ajax for to make webservice calls. I am trying find some simple code examples that will poll based on some condition. (ie, request data for webpage or download a file and check every few seconds and process the results or wait until  process is complete).
Is there any step by step Examples ? How does it handle, if takes 30 sec to 10 mins or longer? How is the polling handled for long periods? and show it on the dashboard/user on how far is lefts before completion.
I'm familiar with how to use AJAX in jQuery, I just can't seem to find the "proper" way of getting  about to execute using a timer and exit outwhen the process is done or there is failure.


text:
Q: Making development with Ext JS fast Ext JS is a nice framework for web UI, but I found that building and putting stuff together takes a long time and painfully slow.
This might be a general problem when working with JavaScript, but does anybody have any way to speed things up?
What can I use? Better IDE with good JavaScript suppport? GUI designers? Code generators?
I need some way to speed up common things like building grids and forms but yet let me do complex things like creating custom components easily.
I'm using ASP.NET MVC. Coolite seems nice at first, but I feel that I'll be having trouble when creating any custom components later on.

A: There's always Ext GWT, which lets you use Eclipse tooling (and all of the advantages that gives you, such as refactoring, swift code navigation, etc.) to create your Ext/JavaScript app.

A: When you download the ExtJs library, you find lot of sample applications for common requirements like Grid panel, forms, form elements etc.
Regarding IDEs, you dont find mature productive tools, but check the below link and wish it could be of help to you
http://www.extjs.com/blog/2008/02/01/ides-plugins-and-tools-for-ext-js-20/
But if you really wish to develop custom components, you need to get through knowledge,start approaching with ExtJs-provided sample apps.

A: If you want to get faster at anything, practice it until you fully understand how it works and how to make it do what you want.  If you are just starting out,  why would expect to be able to work as quickly as you do when you are working on something that you are very familiar with?

A: Things I use to make ExtJS less painful

*

*Chrome, for it's developer tools, or Firefox with Firebug.

*snipMate: snippets for Vim, so I can quickly produce boiler plate code for classes.

*JSLint as a command line tool. Especially good for detecting rogue commas.

*Sencha forums.

*ExtJS IRC chat (Server: irc.freenode.net Room: #extjs).

*API documentation.

*Sencha and Saki's ExtJS examples.

*Beer.

A: ExtJS is building a designer right know so you can look forward it, the only problem I think is not gonna be free.
you can see a video demo there, in term of release date I think this is due to the first quarter of this year.

A: I say learn the framework.  But to develop apps, I use IntelliJ IDEA, which has partial code completion, etc.  It costs money though.

A: Once you have some practice and understanding of how ExtJS works, you'll get faster at it.  By using the examples for reference, and building up my application in small pieces, I've gotten much better (and faster) at developing stuff with ExtJS.  A great way to get started is to find an example (or two) that kind of do what you need, and modify (or combine) them to see how they work together.


text:
Q: Datacenter Power Consumption Table Does anyone know of a good centralized resource that contains a consolidated list of server specifications relevant to the data center?
Looking for Rack U sizing, power consumption, etc. for different branded servers directly from vendor web sites proves difficult - especially for legacy equipment.

A: Vendor provided information is usually "absolute maximum", and therefore is largely useless. You need to measure under your conditions and workloads.

A: It would be very, very hard to tell as so much of power consumption depends on the specifics of your server hardware.
That said, I highly recommend every sysadmin have a wattmeter in their toolkit, like the kill-a-watt.

(source: typepad.com)
Only twenty bucks and it makes this kind of stuff so easy to figure out!
For example, I learned that the web tier servers this very website is running on (Lenovo RS110, specs here), pull:

Idle: doing nothing at windows desktop (unusual, but depends on the server role.. some are light)
96w, 0.85 amp
Full New Install Windows Update: 20% on CPU, plus lots of disk activity (I would consider this more or less a typical load)
120w, 1.0 amp
Full Load: Prime95 + Update. 100% all 4 CPU cores, plus disk activity (this would be extraordinary load, rare)
175w, 1.55 amp

Of course you need to own the server to turn it on and use this tool on it, but perhaps you can use the tool on similar servers you already own to get an idea of what the power consumption might be of other servers you're planning to buy.

A: I've seen hardware and Datacenter technicians use Clamp-on Ammeters to measure the actual amperage on a circuit. It will clamp around a wire, so no need to unplug a wire.
Craftsman sells one for $40. I haven't tried this in a Datacenter myself, but I used one to measure the energy used by my fridge, toaster & microwave.
For server rooms and datacenters, I like to use a metered PDU (power strip) which shows current power usage. Yes they are expensive, but it saves staff time and reduces the need to move power cables from circuit to circuit. They are very handy after racking 20 new servers, or when moving the SAN from one circuit to another.
Some of these are network-capable, so you could monitor power usage over the network (Perhaps using Cacti). Again, I haven't done this myself--- but I've seen others do this, and I wish I had the time.

A: Vendors will list a worst-case nameplate rating, but given the range of configuration options as well as workloads (busy servers draw more power) in just about any server, the actual draw will be widely variable. Best approach is to measure the power use of your gear under a variety of conditions -- the Kill-A-Watt is cheap, and great for 120V gear you can bench-test. You can use a clamp-on meter, but you'll need a breakout cable to do that -- using a standard clamp meter on a normal cable will read pretty close to zero, as the hot and neutral have current flowing in opposite directions, so their magnetic fields cancel out. Megger (and others) make clamp meters designed to work on cables without needing the individual conductors broken out, but it's been my experience that they are far less accurate.

A: The APC link above is great.  If you have mostly Dell, this is a great resource as well.

A: APC has a UPS selector that might help you. You can select servers. telecom gear, etc.

A: It doesn't help that there are two different loads you need to be concerned about. The first one, running load, is what most datacenters are engineered around. The second, startup load, is of concern in datacenters where the presence of power is not guaranteed. Generally speaking, most devices have a power-consumption spike as they start up.
As an example of this, I recently installed a new disk-shelf for one of our disk arrays. Running load was in the neighborhood of 300 watts, but startup-load was 540 watts as all those disk drives spun up. Combine that with five other shelves, and you've got a rack that draws 1500 watts during normal usage, and 2700 watts during startup. 1500 can be handled by a normal 15 amp circuit (in 120v areas), but 2700 watts isn't enough even for a 20 amp 120v circuit. If this disk array ever has to power-cycle, I have to make sure that the power is connected to more than once circuit; preferably three to guarantee I won't pop breakers if the power-supplies all chose to draw from the same circuit.

A: I've used a product suite for years by http://www.21cii.com/.  The IT Studio suite includes a libraray of specification for most commercial and enterprise computing hardware and appliances.  The tool has way more capabilities than you will likely ever need to use, but the libraries are the real find.  You can even override some values and enter your owen, when you need a customized configuration.  The tool builds your environment virtually and performs analysis' such as W/SF or BTU total over entire rooms or a sub-zones.  The tool even publishes PDU Schedules, checks your breaker to outlet compatibility, and computes total PDU Load, as you build PDUs and RPP panel in the virtual data center. Because it works off an AutoCAD driver, your 'Data Center' can be viewed in real-time scale three dimensionally.  It's a little pricey, but a it's a big time saver and ensures fat finger mistakes don't cost you big down the road.


text:
Q: How do I concatenate and rename split file pairs with a loop? I have a directory that looks like this:
S-100-1-54359386-left.fastq.gz
S-100-1-54469454-left.fastq.gz
S-20-1-54356384-left.fastq.gz
S-20-1-54468477-left.fastq.gz
S-40-1-54343370-left.fastq.gz
S-40-1-54465479-left.fastq.gz
S-100-2-54359386-left.fastq.gz
S-100-2-54469454-left.fastq.gz
S-20-2-54356384-left.fastq.gz
S-20-2-54468477-left.fastq.gz
S-40-2-54343370-left.fastq.gz
S-40-2-54465479-left.fastq.gz

Each pair of consecutive files need to be concatenated and given a unique name.  I can use the following for each pair:
zcat S-40-2-54343370-left.fastq.gz S-40-2-54465479-left.fastq.gz | \
gzip -c > S-40-2.left.fq.gz

...but I would like something more elegant.  Notice that the number after the second dash also changes.  The number after the third dash (54359386, etc.) makes each file unique, but doesn't need to be preserved after they are concatenated.  Any advice?  I'm not sure how to make a loop structured to identify the pairs.

A: Assuming that each group can contain only 2 files.
complex pipeline:
echo S-*.fastq.gz | tr ' ' '\n' | sort -t'-' -k1,3n | xargs -n2 bash \
-c 'fn=$(cut -d"-" -f1-3 <<<$0)".left.fq.gz"; zcat "$0" "$1" | gzip -c > "$fn"'

*

*sort -t'-' -k1,3n - sort file list by the first 3 fields treating - as field separator

*-n2 - xargs option, tells to use at most 2 arguments per command line


text:
Q: Convert timestamp column in a csv I have a tab separated csv. The rows look like following:
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59+02  2
57767500    some@email.com  3784    text_value  2016-04-25 07:30:49+02  2

How do i remove the +02 (i assume it can be any number, not only +02) bit from the timestamp column for all the rows?
P.S. What if I there where two timestamps in one row? Like
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59+02  2016-04-25 07:56:59+02  2

?

A: Give this one-liner a try, I didn't test, but should work
awk 'BEGIN{FS=OFS="\t"}{sub(/[+][0-9]+$/,"",$(NF-1))}7' file

A: Try this:
sed -i 's|+[0-9]\+\([[:space:]]\+[0-9]\+\)$|\1|' file

Here I used regexp to replace +02  2 at the end of the line to just 2
Important: it would work with any numbers after plus sign, but it's important to have this plus sign, without it it wouldn't work.
Updated:

P.S. What if I there where two timestamps in one row? Like

In this case it wouldn't work and you could use another approach, that is based on replacing date with timestamps by dates without it:
sed -i 's|\([0-9]\+:[0-9]\+:[0-9]\+\)+[0-9]\+|\1|g' file

But dates should be in the format like 07:56:59+02.

A: Since + followed by a number doesn't occur in any other field (column) we don't have to worry about which field we affect:
$ cat file
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59+02  2
57767500    some@email.com  3784    text_value  2016-04-25 07:30:49+02  2
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59+02  2016-04-25 07:56:59+02  2
$
$ sed 's/+[0-9]*//' file
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59  2
57767500    some@email.com  3784    text_value  2016-04-25 07:30:49  2
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59  2016-04-25 07:56:59+02  2
$
$ sed 's/+[0-9]*//g' file
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59  2
57767500    some@email.com  3784    text_value  2016-04-25 07:30:49  2
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59  2016-04-25 07:56:59  2
$
$ awk '{sub(/+[0-9]*/,"")}1' file
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59  2
57767500    some@email.com  3784    text_value  2016-04-25 07:30:49  2
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59  2016-04-25 07:56:59+02  2
$
$ awk '{gsub(/+[0-9]*/,"")}1' file
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59  2
57767500    some@email.com  3784    text_value  2016-04-25 07:30:49  2
57760234    some@email.com  3791    text_value  2016-04-25 07:56:59  2016-04-25 07:56:59  2

If that's not what you need then edit your question to include some more truly representative sample input and expected output.


text:
Q: EclipseLink @GeneratedValue(strategy = GenerationType.AUTO creates already exist id I am developping a java application with postgresql database, I made  a manual insert into a table, and now when i try to insert from the application I get the following error:
Detail: Key (id)=(1092770) already exists
I am using eclipseLink as JPA framework and the Id generation strategy is the following:
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")
protected long id = 0L;

Clearly the eclipseLink is not considering the max(Id) in the table, and creates an Id less than the current max(Id).
Is there a way to fix this please
Thanks


text:
Q: Bringing up to the front a program's secondary window without changing focus from the primary window So I have a main window/form for my program, and a partner-in-crime window/form, shown/hidden on request. I would like both of them to be in the front when the main window is called to the front (e.g by Alt-Tab).
Trying to use the main window's Activated function and using the partner window's Focused or Activate functions calls focus to the partner window when said partner window is Visible, and the problem is that at that point, every time I try to click on the main window (y'know, to use it), I focus on it, meaning that it brings focus to the partner window instead.
How do I bring a partner window up to the front while keeping focus on the main window?
With hope,
radzo73

A: I have found this first-line solution that works but can certainly be improved or adapted:
private Timer ActivatedTimer;
private bool ActivatedMutex;

public FormTest()
{
  InitializeComponent();
  ActivatedTimer = new Timer();
  ActivatedTimer.Interval = 10;
  ActivatedTimer.Tick += (sender, e) =>
  {
    ActivatedTimer.Stop();
    try
    {
      ActivatedMutex = true;
      BringToFront();
    }
    finally
    {
      ActivatedMutex = false;
    }
  };
}

private void FormTest_Activated(object sender, EventArgs e)
{
  if ( ActivatedMutex ) return;
  try
  {
    ActivatedMutex = true;
    foreach ( Form form in Application.OpenForms )
      if ( form != this && form.Visible )
        form.BringToFront();
    ActivatedTimer.Start();
  }
  finally
  {
    ActivatedMutex = false;
  }
}

Perhaps there are some Win32APIs to do that better.


text:
Q: Identify groups of congruent points I have two sets of points in lists list1 and list2 given below
list1 = [['a',[1.2,3.6,4.5]],['b',[3.2,-5.4,6.6]],['c',[1.1,2.2,9.9]],['d',[5.5,12.5,2.9]],['e',[3.5,6.5,22.9]]]
list2 = [['v',[11.2,3.6,4.5]],['x',[13.2,-5.4,6.6]],['y',[11.1,2.2,9.9]],['z',[15.5,12.5,2.9]]]

If all the points in list1 are rotated and/or translated, points a, b, c and d align with points v, x, y and z respectively. Currently I have written Python code that can output the groups of pairs provided two input lists using a pairwise distance comparison method. It computes intralist combinatorial distances within list1 and list2 and compares these distances between the lists to identify the pairs. For eg. distance(ab) ~= distance(vx), distance(ac) ~= distance(vy) and so on. The code is given below. My code works but is slow for larger lists. I would like to know if there is any faster or easier way to solve this problem.
Thanks
def calculate_distance(point1,point2):
        #function calculates distance
        dis = 0
        dis += math.pow((point2[0]-point1[0]),2)
        dis += math.pow((point2[1]-point1[1]),2)
        dis += math.pow((point2[2]-point1[2]),2)
        distance = math.sqrt(dis)
        return distance

def make_masterdict(list1,list2):
        # calculate interalist combinitorial pairs of points with
        # their distances and store into dicts
        list1pairs = {}
        list2pairs = {}
        for i in range(len(list1)):
                p1 = list1[i][1]
                for p2 in list1[i:]:
                    if list1[i][0] != p2[0]:
                        dist = calculate_distance(p1,p2[1])
                        #store both the pairs in the dictionary
                        list1pairs.update({list1[i][0]+'_'+p2[0]:dist})
                        list1pairs.update({p2[0]+'_'+list1[i][0]:dist})

        for i in range(len(list2)):
                p1 = list2[i][1]
                for p2 in list2[i:]:
                    if list2[i][0] != p2[0]:
                        dist = calculate_distance(p1,p2[1])
                        list2pairs.update({list2[i][0]+'_'+p2[0]:dist})
                        list2pairs.update({p2[0]+'_'+list2[i][0]:dist})

        # calculate interlist pairs between list1 and list2
        masterlist = []
        for i in list1:
                for j in list2:
                        masterlist.append([i[0],j[0]])

        masterdict = {}
        # for each combinatorial pair in masterlist
        for i in range(len(masterlist)-1):
                c1 = masterlist[i]
                key1 = c1[0]+'_'+c1[1]
                masterdict.update({key1:[]})
                for j in range(i+1,len(masterlist)):
                        c2 = masterlist[j]
                        # if the same point is not repeated in the pairs
                        if c1[0] != c2[0] and c1[1] != c2[1]:
                                #collect and compare the distances
                                p1 = c1[0]+'_'+c2[0]
                                p2 = c1[1]+'_'+c2[1]
                                dis1 = list1pairs[p1]
                                dis2 = list2pairs[p2]
                                if abs(dis1-dis2) < 0.1:
                                        #if same distance, then store in masterdict
                                        key2 = c2[0]+'_'+c2[1]
                                        masterdict[key1].append(key2)
        return masterdict

def recursive_finder(p1,list1,masterdict,d,ans):
        # if lenght of d is more than 2, store that list in ans
        if len(d) > 2:
                ans.append(d)

        # if lenght of list is 0, do not do anything
        if len(list1) == 0:
                pass
        else:
                other = []
                nextlist = []
                #loop through each value in list1 as p1
                for i in list1:
                        if i in masterdict[p1]:
                                #make empty list
                                newl = []
                                #store old group in newl
                                newl.extend(d)
                                #add new member to old group
                                newl.append(i)
                                #store this list
                                other.append(newl)
                                #store new member
                                nextlist.append(i)
                #repeat for each successful value in nextlist
                for i in range(len(nextlist)):
                        #collect p1 and dnew
                        p1 = nextlist[i]
                        dnew = other[i]
                        #repeat process
                        recursive_finder(p1,nextlist[i+1:],masterdict,dnew,ans)

def find_groups(list1,list2):
        #make master dictionary from input lists
        masterdict = make_masterdict(list1,list2)
        ans = []
        #use recursive function to identify groups
        for mainkey in masterdict:
                if len(masterdict[mainkey]) > 1:
                        for i in range(len(masterdict[mainkey])):
                                p1 = masterdict[mainkey][i]
                                recursive_finder(p1,masterdict[mainkey][i+1:],masterdict,[mainkey,p1],ans)

        return ans

#define two lists with a,b,c and d matching v,x,y, and z respectively
list1 = [['a',[1.2,3.6,4.5]],['b',[3.2,-5.4,6.6]],['c',[1.1,2.2,9.9]],['d',[5.5,12.5,2.9]],['e',[3.5,6.5,22.9]]]
list2 = [['v',[11.2,3.6,4.5]],['x',[13.2,-5.4,6.6]],['y',[11.1,2.2,9.9]],['z',[15.5,12.5,2.9]]]
answer = find_groups(list1,list2)
print(answer)

Upon running the code, the correct answer is output. Groups larger than size of 3 are output.
[['a_v', 'b_x', 'c_y'], ['a_v', 'b_x', 'c_y', 'd_z'], ['a_v', 'b_x', 'd_z'], ['a_v', 'c_y', 'd_z'], ['b_x', 'c_y', 'd_z']]


text:
Q: HP Procurve 2910 Inter VLAN routing partially working I'm in the middle of slowly trying to solve my inherited ip range issue.
Currently everything is on 100.100.100.x. I am slowly moving things over to a 10.12.x.x range. Currently my Watchguard firewall on 100.100.100.222 is doing my for users, I want to change so the Procurve on 100.100.100.79 does the routing instead.
The first stage has been to set up a second connection to the firewall on VLAN 99 10.12.99.1 so internet access works and I've got it working on VLAN 123.
Here is my vlan setup.
VLAN ID Name                 | Status     Voice Jumbo
------- -------------------- + ---------- ----- -----
1       DEFAULT_VLAN         | Port-based No    No
20      ISCSI                | Port-based No    No
99      DMZ                  | Port-based No    No
121     Client_PCs           | Port-based No    No
122     Production           | Port-based No    No
123     Servers              | Port-based No    No

I can ping between VLAN 1 and 123.
I can't ping between VLAN 122 and 123.
Here is my running config
    ; J9145A Configuration Editor; Created on release #W.14.38
hostname "AKS-BROX-SW2"
module 1 type J9145A
interface 24
   name "LINK TO FP"
exit
trunk 19-22 Trk1 LACP
trunk 6-9 Trk2 LACP
ip default-gateway 100.100.100.222
ip routing
vlan 1
   name "DEFAULT_VLAN"
   untagged 1-3,5,10,24,Trk1-Trk2
   ip address 100.100.100.79 255.255.255.0
   no untagged 4,11-18,23
   exit
vlan 20
   name "ISCSI"
   untagged 11-18
   ip address 172.16.230.253 255.255.255.0
   tagged Trk1
   exit
vlan 121
   name "Client_PCs"
   ip address 10.12.1.254 255.255.255.0
   tagged Trk2
   exit
vlan 122
   name "Production"
   ip address 10.12.2.254 255.255.255.0
   tagged 1-2,5,10-11,Trk2
   exit
vlan 123
   name "Servers"
   ip address 10.12.3.254 255.255.255.0
   tagged 1-2,4-5,10-11,Trk2
   exit
vlan 99
   name "DMZ"
   untagged 23
   ip address 10.12.99.254 255.255.255.0
   exit
fault-finder bad-driver sensitivity high
fault-finder bad-transceiver sensitivity high
fault-finder bad-cable sensitivity high
fault-finder too-long-cable sensitivity high
fault-finder over-bandwidth sensitivity high
fault-finder broadcast-storm sensitivity high
fault-finder loss-of-link sensitivity high
fault-finder duplex-mismatch-HDx sensitivity high
fault-finder duplex-mismatch-FDx sensitivity high
timesync sntp
sntp unicast
sntp server priority 1 192.146.137.13 3
ip route 0.0.0.0 0.0.0.0 10.12.99.1
ip route 10.12.1.0 255.255.255.0 10.12.99.1
ip route 10.12.2.0 255.255.255.0 10.12.99.1
ip route 10.12.3.0 255.255.255.0 10.12.99.1
ip route 100.100.100.0 255.255.255.0 10.12.99.1
snmp-server community "snmp-public" operator
snmp-server community "monitor" operator
spanning-tree
spanning-tree 4 path-cost 41000
spanning-tree Trk1 priority 4
spanning-tree Trk2 priority 4
spanning-tree priority 7
no autorun
password manager

And last but not least the routing...
                               IP Route Entries

  Destination        Gateway         VLAN Type      Sub-Type   Metric     Dist.
  ------------------ --------------- ---- --------- ---------- ---------- -----
  0.0.0.0/0          10.12.99.1      99   static               1          1
  10.12.1.0/24       Client_PCs      121  connected            1          0
  10.12.2.0/24       Production      122  connected            1          0
  10.12.3.0/24       Servers         123  connected            1          0
  10.12.99.0/24      DMZ             99   connected            1          0
  100.100.100.0/24   DEFAULT_VLAN    1    connected            1          0
  127.0.0.0/8        reject               static               0          0
  127.0.0.1/32       lo0                  connected            1          0
  172.16.230.0/24    ISCSI           20   connected            1          0

I can't get VLAN 122 and VLAN 123 to talk to each other, so I assume the route is wrong, but if I try to add a route...
ip route 10.12.2.0/24 10.12.3.254
I get this error.
    10.12.3.254 can not be switch IP address and route gateway at the same time.
I must have something configured wrongly, but I can't work out what it is.
Thanks

A: A 2910 with activated ip routing routes from and to any VLAN that it has an IP address assigned in.
So, if a node can't reach one VLAN subnet from another it's likely not in the correct VLAN.
ip route 10.12.2.0/24 10.12.3.254 can't work since 10.12.2.0/24 is already connected locally and 10.12.3.254 is the switch itself - you can't tell it to route back to itself.
Additionally,
ip route 0.0.0.0 0.0.0.0 10.12.99.1
ip route 10.12.1.0 255.255.255.0 10.12.99.1
ip route 10.12.2.0 255.255.255.0 10.12.99.1
ip route 10.12.3.0 255.255.255.0 10.12.99.1
ip route 100.100.100.0 255.255.255.0 10.12.99.1

don't make sense. All these subnets are local and can't be routed elsewhere.
btw: firmware version 14.38 is ancient (before 2011 when we bought 2910s)...
PS: You're binding IP addresses to all VLANs, including iSCSI and DMZ - as stated above, the 2910 will route into and out of all these networks which is most surely not intended. You'll need to either remove these IP addresses and route/filter between these VLANs elsewhere or configure ACLs that allow the traffic you want while filtering everything else. Note that the 2910 doesn't allow VLAN ACLs, only port ACLs.


text:
Q: How will added from SD card Specific folder URL path "Universal Image Loader " Has i am create sample Gallery using "Universal Image Loader" i will given one by one static image path !! How to added  images path in dynamically using Universal Image Loader concept.
Sample Code Contants.java :
   public final class Constants {

public static final String[] IMAGES = new String[] {
        // Heavy images
            "file:///sdcard/DCIM/IMG_20151026_172237570.jpg", // Image from SD card with encoded symbols
            "file:///sdcard/DCIM/IMG_20151026_172241845.jpg", // Image from SD card with encoded symbols
            "file:///sdcard/DCIM/IMG_20151026_172251959.jpg", // Image from SD card with encoded symbols
            "file:///sdcard/DCIM/IMG_20151026_172255739.jpg", // Image from SD card with encoded symbols
            "file:///sdcard/DCIM/IMG_20151026_172258063.jpg", // Image from SD card with encoded symbols
        "file:///sdcard/DCIM/IMG_20151026_172258063.jpg", // Image from SD card with encoded symbols
        "file:///sdcard/DCIM/IMG_20151026_172258063.jpg", // Image from SD card with encoded symbols

};

private Constants() {
}

public static class Config {
    public static final boolean DEVELOPER_MODE = false;
}

public static class Extra {
    public static final String FRAGMENT_INDEX = "com.nostra13.example.universalimageloader.FRAGMENT_INDEX";
    public static final String IMAGE_POSITION = "com.nostra13.example.universalimageloader.IMAGE_POSITION";
}
}

This is the code .... How to given on dynamically different in run time access its , given me solutions friends!!

A: --Here is the solutions you can see
string imgPath = "/file:///sdcard/DCIM/IMG_20151026_172237570.jpg";

String decodedImgUri = Uri.fromFile(new File(imgPath)).toString();
ImageLoader.getInstance().displayImage(decodedImgUri, imageView);


text:
Q: how to query nested maps inside an array field in firebase I have structured my data in Firebase such that I have a collection of 'users' and each user has various fields as well as a 'skillsIndustry' Array field which contain Maps items (that have fields 'experience' and 'industry').

Now I would like to query my collection of users so that I can ask for all users that have worked in 'Airlines' with experience code of >= 1
Is this possible at all?  Or do I have to create sub collections and then use Collection Group Queries?
Many thanks

A: No, this is not possible. You can use array-contains to query for the entire object, as explained in this SO answer, but not to query with > or <.
You could create a subcollection, but you can probably find a solution based on the duplication of the data in the same document, which is a common approach in the NoSQL world.
For example, you could have some extra fields named airlinesExperience, shippingExperience, etc. Then you use the skillsIndustry Array field when you want to display all the skills and years of experience, but you use the xxxExperience fields when you want to query.

Another possibility would be to use a map of key/value pairs like
key = "Airlines" / value = 1

key = "Shipping" / value = 3

Then you can query with:
  firebase
    .firestore()
    .collection('users')
    .where('skillsIndustry.Shipping', '>', 2)


text:
Q: writing files in a subdirectory to a csv file and save it to parent directory in linux command line I have a directory called 'dir', and there is a subdirectory in it called 'subdir'. Subdir has many files in it. I would like write to list of these files on a CSV file and save it to in 'dir' directory with a command line on linux. My code creates the csv file but saves it in subdir but not dir. Where do I do wrong? I am in dir directory;
dir$ ls subdir >names.csv

A: As an easier alternative you could cd to subdir and use
printf "%s\n" * >../list.csv

This will give you a newline separated and newline terminated list with no commas involved. You can see it as a degererated csv file with only one column.
If you want to include hidden files (files with names that begin with a dot), you can use * .* instead of the sole *. If you want to exclude the . and .. directory names, use * .[^.]* ..?* instead. In total:
printf "%s\n" *             >../list.csv   # For non-hidden files.
printf "%s\n" * .*          >../list.csv   # For all files.
printf "%s\n" * .[^.]* ..?* >../list.csv   # For all files but `.` and `..`.

But keep in mind that filenames in Linux may contain newlines by themselves. In fact, the only unique single byte separator for filenames is the null byte.

Update due to this comment:
Let us assume that you have any number of subdirs whose non-hidden contents you want to catalog in separate files in the common parent directory. (Collecting all names in one file is much shorter, see this elegant solution. And, to tell the truth, I have not read your comment carefully enough.) This can be achieved in that parent directory (dir in your case) by
find . -mindepth 1 -maxdepth 1 -type d -exec bash -c 'cd {}; printf "%s\n" * >../$(basename {}).csv' \;

This requires the programs find, bash, and basename.
Using it you should take extra care, that dir does not contain files whose names conflict with the automatically generated csv lists.
Here is how it works: find considers each file that lies exactly one directory level below the current directory (.)—that is what -mindepth 1 -maxdepth 1 does—: If it is a directory (-type d) it executes (-exec) the command between -exec and the trailing \; after substituting the empty braces ({}) by the name of that directory. If we denote this name by <SUBDIR>, this results in
bash -c 'cd <SUBDIR>; printf "%s\n" * >../$(basename <SUBDIR>).csv'

This starts bash in a subprocess, causing it to execute the argument of the -c option as a shell script, namely
cd <SUBDIR>;
printf "%s\n" * >../$(basename <SUBDIR>).csv

which is pretty much the same as above. Here, the expression
$(basename <SUBDIR>)

is expanded to the basename of <SUBDIR>. This is necessary because <SUBDIR> will iterate through ./subdir1, ./subdir2, etc in your case. The corresponding basenames are subdir1, subdir2, etc.

A: You should achieve it by using the for loop.
If my understanding is right, you want to get a list of files in the subdir. So do something like this:
$ cd dir
$ for files in subdir/*;do echo $files|cut -d '/' -f 2 >>filelist.csv;done

Now, you can see there is a file called "filelist.csv" has been created under your dir directory.


text:
Q: What could prevent NServiceBus from moving messages to the error queue if there are exceptions when processing? I have an application using NServiceBus to process messages, and while debugging I'm finding that exceptions may be thrown, and the message is lost. I've checked both the main and error queues, and the message was only attempted once.
Are there any common pitfalls that could cause this to happen?
I use NServiceBus 2.0.0.1219 (2.0 RTM) on Windows 7 64 bit. Other question with same issue on older version:
What could prevent NServiceBus from moving messages to the error queue if there are exceptions when processing?
The website Bus.Send a command to the command handler endpoint.
Website Config File:
<MsmqTransportConfig InputQueue="WebAppTest_InputQueue" ErrorQueue="ErrorQueue" NumberOfWorkerThreads="1" MaxRetries="5"/>

<UnicastBusConfig ForwardReceivedMessagesTo="AuditQueue">
  <MessageEndpointMappings>
    <add Messages="ABC.ServiceBus.Commands" Endpoint="CommandProcessor_InputQueue"/>
  </MessageEndpointMappings>
</UnicastBusConfig>

<DBSubscriptionStorageConfig>
  ...
</DBSubscriptionStorageConfig>

Command Handler Config File:
<MsmqTransportConfig InputQueue="CommandProcessor_InputQueue" ErrorQueue="ErrorQueue" NumberOfWorkerThreads="1" MaxRetries="5" />

<UnicastBusConfig ForwardReceivedMessagesTo="AuditQueue">
  <MessageEndpointMappings>
    <add Messages="ABC.ServiceBus.Commands" Endpoint="WebAppTest_InputQueue"/>
  </MessageEndpointMappings>
</UnicastBusConfig>

<DBSubscriptionStorageConfig>
  ...
</DBSubscriptionStorageConfig>

A: Since the message forwarding is part of the same transaction as the receipt of the message, if the receive fails, the forwarding fails.  I'm thinking that if an exception is thrown you probably want it to go to the error queue and not the audit queue since it wasn't received correctly.  If you want to see everything that flows through irregardless, journaling might be a better bet.


text:
Q: Asking for a faster method for extraction of data from Images Currently im writing a code where i extract images RGB Values using Opencv/PIL (tried both).
Then i put them through a function to calculate their mean and median and also the mean and median of the upper and lower parts.
Currently my code takes about 1 image per second and i need to do this for 10,000+ images that are stored in different subfolders of their categories.
I use numpy functions for mean and median.
Is there a faster way i can do this?
Edit : The images are all different sizes and have dimensions varying from say 1x1 to 1000x100 and are of the formats jpg, png and bmp
As for the code, i know accessing the image shouldn't take long but the problem lies in computing the mean and median of those arrays. Ill add a code snippet below of what it looks like (I apologize in advance if it looks bad)
I also write all of these mean and median values to an excel sheet in the end using xlwt which I hope shouldnt take long either.
I use os.walk to traverse the directory after which i use
img = os.path.join(dirName,fname)
and get values from a function defined in another file
values  = rgbavg(img)
image = cv2.imread(image_path)
    img = np.array(image)
    img = img.transpose(2,0,1).reshape(3,-1)
    x, size = img.shape
    avg = np.mean(img, axis = 1)

    for i in range(0,3):
        upper = np.array([])
        lower = np.array([])
        for ele in img[i]:
            if ele > avg[i]:
                upper = np.append(upper,ele)
            else:
                lower = np.append(lower,ele)

        if upper.size != 0:
            mean = np.mean(upper)
            avg = np.append(avg,mean)
        else:
            avg = np.append(avg,0)
        if lower.size != 0:
            mean = np.mean(lower)
            avg = np.append(avg,mean)
        else:
            avg = np.append(avg,0)

A: What is possible is that your program is spending a lot of time just waiting for read write operations and a lot of loops.
actual answer under updated
The waiting part you can mitigate by making use of multiple processes. Easiest way for you I think would be using a Pool. This also can increase your code speed by however many cores you have available.
First you would prepare your data (gather a list of all the files/file paths)
Then you would pass that as an argument so Pool creates processes and saves results
import multiprocessing
import time

files = ["img1.jpeg", "img2.jpeg", "img3.jpeg", "img4.jpeg"]

def process_image(path):
    # process image and return your data
    # time.sleep is only here to show that a different process is running as it executes faster than pool starts processes
    time.sleep(1)
    return [[0,0,0], [14,14,14], multiprocessing.current_process().name]

if __name__ == '__main__':
    with multiprocessing.Pool(processes=4) as pool:
        results = pool.map(process_image, files)
        print(results)

Updated:
After inspecting the original code I found the filtering is what takes a long time (in this case separating above and below average values in the array). Numpy has a faster filter:
boolean_array = img_array <|>|= value  # returns a boolean array
and
filtered = img_array[boolean_array]  # returns the filtered list
import multiprocessing
import numpy
import cv2

def process_image(xyz):
    img = numpy.random.randint(255, size=(1000,1000,3),dtype=numpy.uint8)
                      .transpose(2,0,1).reshape(3,-1)
    avg = numpy.mean(img, axis = 1)

    x, size = img.shape

    for i in range(0,3):
        upper = img[i][img[i] >= avg[i]]
        lower = img[i][img[i] < avg[i]]
        if upper.size != 0:
            # Why you are saving these idk but ok
            mean = numpy.mean(upper)
            avg = numpy.append(avg,mean)
        else:
            avg = numpy.append(avg,0)
        if lower.size != 0:
            mean = numpy.mean(lower)
            avg = numpy.append(avg,mean)
        else:
            avg = numpy.append(avg,0)

    return [avg, mean, multiprocessing.current_process().name]

if __name__ == '__main__':
    with multiprocessing.Pool(processes=4) as pool:
        results = pool.map(process_image, range(0,12))
        print(results)

This is with multiprocessing added


text:
Q: Unable to get required zoomlevel in google map v2? I am working on an application in which map zoom level set on the basis on seekbar move say
   seekbar progress is 10 mile then calculate exact zoom level of map by which cover 10 mile distance on mobile screen map.more explanation in attached image
my seekbar initial position is 1 mile and max position is 50 miles when I move seekbar max position say 50 map cover only 30 km area while it should be cover 80 km area.I am using code for achieve this is -
private int zoomLevel(double _distance) {
    int newzoomlevel = 1;
    double distance = _distance * 1609.34;
    double equatorLength = 40075004; // in meters
    double widthInPixels = screenWidth();
    double metersPerPixel = equatorLength / 256;
    int zoomLevel = 1;
    while ((metersPerPixel * widthInPixels) > distance) {
        metersPerPixel /= 2;
        ++zoomLevel;
    }
    Log.i("current zoom level", "zoom level = " + zoomLevel);
    if (zoomLevel <=19) {
        newzoomlevel = zoomLevel;
    } else {
        newzoomlevel = zoomLevel - 2;
    }
    return newzoomlevel;

}

I am passing seekpar position as a parameter since it is in mile in method I convert it into meter by multiplying 1609.34. but my over all out come is not correct please any one guide me thanks in advance.


text:
Q: iOS 7 Critical failure: the LastResort font is unavailable When my app first launches I create a bunch of custom UIFonts (they are correctly added into the .plist). The custom fonts work perfectly until I try to create more than 9 to 10 of them. After the 9 or 10th custom font is created, I get this warning "Critical failure: the LastResort font is unavailable." I only get this warning on my iOS 7 devices and I can't seem to figure out why. This has to be a bug with iOS 7 because every custom font works on my iOS 6 devices, and I'm only using 1 project. Any idea what is causing this warning, and how to fix it?

A: It happened to me with iOS 7..I removed all the fonts and added carefully one by one to the plist. There was a font that was "bad" for iOS 7 and caused the mess. I hope this help)
Of course a bug in Apple's Matrix


text:
Q: Retrieve DateTime doesn't Load EF Core I have the following model.
public class Customer
{
     [Key]
     public int CustomerId { get; set; }
     public string CustomerName { get; set; }
     public DateTime RegisteredDate { get; set; }
}

From the model, I generate scaffold controller. Then I have the following code:
public async Task<IActionResult> Edit(int? id)
{
     if (id == null)
     {
          return NotFound();
     }
     var obj = await _db.Customers.FindAsync(id);
     if (obj == null)
     {
         return NotFound();
     }
     return View(obj);
}

It will triggered when user clicked the edit link on the table. But, the RegisteredDate didn't retrieved to the view. I have the following view:
<input asp-for="CustomerId" hidden />
<input asp-for="CustomerName" />
<input asp-for="RegisteredDate" />

Why the RegisteredDate didn't load to the view? But If I add type="datetime", the data is loaded. The problem is, DateTime picker dropdown is not appears.

1st pic is without type="datetime" and 2nd pic is with type="datetime" (notice there's no datetime picker icon on it).
please advice.
thank you.

A: in your customer class add Datatype to RegisteredDate like this
public class Customer
{
 [Key]
 public int CustomerId { get; set; }
 public string CustomerName { get; set; }

 [DataType(DataType.Date)]
 public DateTime RegisteredDate { get; set; }
}


text:
Q: Can't get music to play in java I'm trying to get background music to play in a text adventure I am making. However, I cant get the sound class to work.
import sun.audio.*;

import java.io.*;

public class Sound {

    public static void music()
    {
        AudioPlayer MGP = AudioPlayer.player;
        AudioStream BGM;
        AudioData MD;

        ContinuousAudioDataStream loop = null;

        try
        {
            InputStream test = new FileInputStream(new File "TrainerRedMusic.wav");
            BGM = new AudioStream(test);
            AudioPlayer.player.start(BGM);

        }
        catch(FileNotFoundException e){
            System.out.print(e.toString());
        }
        catch(IOException error)
        {
            System.out.print(error.toString());
        }
        MGP.start(loop);
    }
}

I have scoured the internet looking for a simple guide, but nothing works for what I am doing. I am just trying to run a .wav file in the background of my text adventure. Any help?


text:
Q: how to mock overload method in jest? I'm using jsonwebtoken library to validate tokens in my module. jsonwebtoken exports verify method more than one time (overloaded).
export function verify(token: string, secretOrPublicKey: Secret, options?: VerifyOptions): object | string;

export function verify(
    token: string,
    secretOrPublicKey: Secret | GetPublicKeyOrSecret,
    callback?: VerifyCallback,
): void;

export function verify(
    token: string,
    secretOrPublicKey: Secret | GetPublicKeyOrSecret,
    options?: VerifyOptions,
    callback?: VerifyCallback,
): void;

My module:
private validateToken(token: string): void {
        const publicKeyToPem = this.convertPublicKeyToPEM(this.ssoPublicKey);
        try {
            this.decodedToken = jwt.verify(token, publicKeyToPem);
        } catch (e) {
            throw new Error(e);
        }
    }

I tried to mock verify method in unit test.
    test('should return true if token is correct', () => {

        const verifyResponse = { 'test': 'test' };
        jest.spyOn(jwt, 'verify').mockReturnValue(verifyResponse);

        ........
    });

I get following error: Argument of type '{ test: string; }' is not assignable to parameter of type 'void'.ts(2345)
It seems last exported method (verify) is used and it returns void.
I tried with jest.spyOn(jwt, 'verify').mockImplementationOnce(() => verifyResponse); it seems to be fine but how to mock specific overloaded method?

A: Instead of jest.spyOn you should use jest.mock like this
const jwt = require('jwt-library');
const myMod = require('./myModule');

// it will replace all of the methods with jest.fn()
jest.mock('jwt-library')

describe('my module', () => {
  const mockDecodedToken = { 'test': 'test' };
  describe('calling a public method that calls validateToken', () => {
    beforeAll(() => {
      jwt.verify.mockReturnValue(mockDecodedToken);
      myMod.aPublicMethodThatCallsValidateToken()
    })

    it('should have called jwt.verify', () => {
      expect(jwt.verify).toHaveBeenCalledWith(
        expect.any(String)
        expect.any(Secret)
        expect.any(VerifyOptions)
      )
    })

    it('should have assigned decodedToken to my module', () => {
      expect(myMod).toHaveProperty(decodedToken, mockDecodedToken)
    });
  })
})


text:
Q: Mysql Select Max Consecutive Records (with gaps) I'm having trouble selecting consecutive records and I think I've pin pointed the problem. I'm thinking it was something to do with a jump in the id field.
I have set up some sample data here:
https://www.db-fiddle.com/f/fqSixe8TBPu7s7Ko22ySmr/0
Basically, I am using the following code to return a players max consecutive wins:
set @player=0, @count=0;
select max(@count := if(outcome = 2 and player = 785, @count+1, 0))
from cc6_MensLeague_rounds use index(maxcon);

The result in the above sample data is 13 (it's supposed to be 24).
It works fine with most players but I get unexpected results with a select few. After digging around I noticed that it could possibly be a jump in the id fields of certain records. I need to ignore the gaps somehow.
If anyone has a solution, or can point me in the right direction, that would be awesome.
Thanks.

A: The following query seems to work for me:
SET @count=0;

SELECT max(@count := if(outcome = 2, @count+1, 0)) AS MAX_CONSECUTIVE_WINS
FROM
 (SELECT *
  FROM cc6_MensLeague_rounds
  WHERE player = 785
  ORDER BY date ASC) AS Temp

Let me know if it doesn't always work :)


text:
Q: YASMIN CPU simulator instruction set, RISC-based but what does #h mean? I'm working through a set of problems related to the YASMIN CPU/OS simulator with a RISC-like instruction set.  (Editor's note, possibly this one or another version of it).   I just cant seem to find the answer to the following:

*Add the following code and run:

STB #h41, 16
LDB 16, R03
ADD #1, R03
STB R03, 17

What is the significance of h in h41 above?
There seems to be no information anywhere to reference. I have tried pairing different numbers with h to distinguish a pattern but to no avail. See my attempt below.

A: #h41 means literal value hex 41. h prefix simply means the following number is a hex number. As simple as that.

A: refer to their tutorial (Investigating Programming Model 2) , where they gave an example on page 5 where they said :

MSF
PSH #h60 -> puts the number hex 60 on top of the stack
CAL $Label2
HLT

that means that h is indication that this number in HEX format and # means that it's a immediate value, so in the example you provided :
STB #h41, 16

#h41 is a HEX number which is equivalent to 65 in decimal number systems.


text:
Q: Circular linked list crashes when displayed I'm trying to make a circular linked list. When I try to display the list after creating it, the program keeps on crashing. Here is my code:
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int data;
    struct node * next;
} node;

node * createList(int);
void display(node * head);

int main() {
    struct node * head;

    head = createList(5);
    display(head);

}

node * createList(int n) {

    int i = 0,data = 0;
    struct node * head = NULL;
    struct node * temp = NULL;
    struct node * p = NULL;

    for (i = 0; i < n; i++) {
        temp = (node*)malloc(sizeof(node));
        temp->data = data++;
        temp->next = head;

        if (head == NULL) {
            head = temp;
        } else {
            p = head;
            while (p->next != NULL) {
                p = p->next;
            }
            p->next = temp;
        }
    }
    return head;
}

void display(node * head) {
    struct node * temp = head->next;
    while (temp != head) {
        printf("%d-> \t",temp->data);
        temp = temp->next;
    }
    printf("\n");
}

What am I doing wrong?

A: *

*You have set every temp's next to head in temp->next = head; but did it too early (the first is just NULL). Then you tested p->next against NULL in while (p->next != NULL) { but you should have tested against head. Alternatively, you can continue to test against NULL but then you need to initialize temp->next to NULL and assign head to temp->next only after the for loop.

*Your display code started from the second link.
Here is a fixed code using the first option in 1. above:
    for (i = 0; i < n; i++) {
        temp = (node*)malloc(sizeof(node));
        temp->data = data++;

        if (head == NULL) {
            head = temp;
        } else {
            p = head;
            while (p->next != head) {
                p = p->next;
            }
            p->next = temp;
        }
        temp->next = head;
    }

Here is a fixed code using the alternative option in 1. above. You still need to initialize temp->next to NULL since malloc() does not  initialize.
    for (i = 0; i < n; i++) {
        temp = (node*)malloc(sizeof(node));
        temp->data = data++;
        temp->next = NULL;

        if (head == NULL) {
            head = temp;
        } else {
            p = head;
            while (p->next != NULL) {
                p = p->next;
            }
            p->next = temp;
        }
    }
    if (temp != NULL) {
        temp->next = head;
    }

But in reality, there is no need to "walk" from the head on every creation. You can simply keep the previous and link it to the next:
    for (i = 0; i < n; i++) {
        temp = (node*)malloc(sizeof(node));
        temp->data = data++;

        if (head == NULL) {
            head = p = temp;
        } else {
            p = p->next = temp;
        }
    }
    if (temp != NULL) {
        temp->next = head;
    }

Here is a fix for the display():
void display(node * head) {
    struct node * temp = head;
    if (temp != NULL) {
        do {
            printf("%d-> \t",temp->data);
            temp = temp->next;
        } while (temp != head);
    }
    printf("\n");
}

A: The problem is on the first node you initialize:
    struct node *head = NULL;
    ...
    for (i = 0; i < n; i++) {
        ...
        temp->next = head;

So tmp->next == NULL on the first iteration leaving head->next == NULL. That will not work for a circular list. When you attempt to insert the 2nd node:
            p = head;
            while (p->next != NULL) {

What was head->next again?? (oh, NULL) Dereferencing a NULL pointer (BOOM Segfault!)
Do your circular list correctly. On insertion of the first node set:
        if (head == NULL) {
            head = temp;
            head->next = temp;              /* you must set head->next to temp */
        } ...

So on the insertion of the remaining nodes you simply need:
        } else {
            p = head;
            while (p->next != head) {       /* iterate to last node */
                p = p->next;
            }
            p->next = temp;                 /* now set p->next = temp */
        }

Now, you handle your display() function the same way, e.g.
void display (node *head)
{
    if (!head) {                            /* validate list not empty */
        puts ("(list-empty)");
        return;
    }

    struct node *temp = head;

    do {                                    /* same loop problem fixed in display() */
        printf ("%d-> \t", temp->data);
        temp = temp->next;
    } while (temp != head);

    putchar ('\n');
}

If you make the changes, then you can test your list with:
int main (void) {
    struct node *head, *tmp;

    head = createList(5);
    display (head);

    puts ("\niterate from mid-list");
    tmp = head;
    tmp = tmp->next;
    tmp = tmp->next;
    display (tmp);
}

Example Use/Output
$ ./bin/lls_circular_fix
0->     1->     2->     3->     4->

iterate from mid-list
2->     3->     4->     0->     1->

Lastly, you are not multiplying the type node by head in struct node * head = NULL; Write it as struct node *head = NULL; (the same for all your function declarations as well) Much more readable.
When you go to delete a note from the list, you must create a special case for both head and tail (the last node). In this sense, the singly-linked list takes a bit more effort than a doubly-linked list due to not having a prev node pointer to track the prior node.
Look things over and let me know if you have questions.
A full example would be:
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int data;
    struct node *next;
} node;

node *createList (int);
void display (node *head);

int main (void) {
    struct node *head, *tmp;

    head = createList(5);
    display (head);

    puts ("\niterate from mid-list");
    tmp = head;
    tmp = tmp->next;
    tmp = tmp->next;
    display (tmp);
}

node *createList (int n)
{
    int i = 0,data = 0;
    struct node *head = NULL;
    struct node *temp = NULL;
    struct node *p = NULL;

    for (i = 0; i < n; i++) {
        if (!(temp = malloc (sizeof *temp))) {
            perror ("malloc-temp");
            return NULL;
        }
        temp->data = data++;
        temp->next = head;                  /* head is NULL on 1st node insertion */

        if (head == NULL) {
            head = temp;
            head->next = temp;              /* you must set head->next to temp */
        } else {
            p = head;
            while (p->next != head) {       /* iterate to last node */
                p = p->next;
            }
            p->next = temp;                 /* now set p->next = temp */
        }
    }
    return head;
}

void display (node *head)
{
    if (!head) {                            /* validate list not empty */
        puts ("(list-empty)");
        return;
    }

    struct node *temp = head;

    do {                                    /* same loop problem fixed in display() */
        printf ("%d-> \t", temp->data);
        temp = temp->next;
    } while (temp != head);

    putchar ('\n');
}


text:
Q: Making an emoji-enabeling app for the iPhone I know they sell a lot of apps in the App Store that claim to "unlock" emoji keyboards. How would I go about doing this?
I want to made an app that enables emoji keyboards. I have paid the 100 dollar developers license fee if this makes a difference.

A: Based on one of the samples provided in the links above you can do the following:
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:
                  @"../../Library/Preferences/com.apple.Preferences.plist"];
NSMutableDictionary *dict =
    [NSMutableDictionary dictionaryWithContentsOfFile:path];
[dict setObject:[NSNumber numberWithBool:YES] forKey:@"KeyboardEmojiEverywhere"];
[dict writeToFile:path atomically:NO];

A: See iPhone devs, access Emoji for free with Freemoji.


text:
Q: Appending new key to a dictionary I am trying to add elements to a dictionary in the following way:
a = {}
a['b'] = 1
a['a'] = 2

Finally a looks like:
{'a': 2, 'b': 1}

But actually I wanted the dictionary to contain keys in the order:
{'b': 1, 'a': 2}

Can anyone explain me this? Why are the keys getting sorted alphabetically when actually dictionaries (hashmaps) don't have any order?

A: You are correct in that dictionaries are not ordered, but hashed. As a result, the order of a dictionary should not be relied on.
You can use the OrderedDict to help you achieve your goal:
from collections import OrderedDict
a = OrderedDict()
a['b'] = 1
a['a'] = 2

 > a
 > OrderedDict([('b', 1), ('a', 2)])


text:
Q: VIM Sendscreen and behind the scenes buffer I'm currently using vim via cygwin in conjunction with screen and screen-vim. Screen-vim has SendScreen which takes the entire current buffer and sends it to the attached screen. While this is nice, for my application I really need a line by line solution. Currently I'm using the following mapping:
map <leader>d "kyy<cr>:tabe<cr>"kp<ESC>:ScreenSend<cr>:q<cr>

This does the job but feels kind of wonky. Is there a better solution? I'm specifically looking for something that either opens a buffer so that the user doesn't notice or implements the same functionality in a neater manner.

A: From the README:

Once you have the shell open, you can then send visual selections to it using the command :ScreenSend.

And from :help screen:

:ScreenSend
Send the visual selection or the entire buffer contents to the running gnu screen shell window.

So…
V:ScreenSend<CR>

or
:.ScreenSend<CR>


text:
Q: The origin of Gauss' law for magnetism What is the physical axiom leading us to the Gauss' law for magnetism?

A: The physical axiom leading us to Gauss' law is that magnetic monopoles (equivalent to electric charges) do not exist.


text:
Q: Big query table on top of bigtable taking too long to read in google dataflow job I have a dataflow job that reads from bigquery table( created on top of big table). The data flow job is created using custom template in java.
I need to process around 500 million records from bigquery.
The issue I am facing is even to read 1 million record big query read is taking 26 min and dataflow job is taking 36 min.
The read is too slow in big query.
Any suggestions on how to improve the read performance .
Do apache beam programming model provide support to read from source in parallel ? Any IO connector available for parallel read from bigtable.
Any help will be highly appreciated


text:
Q: How can I track down why the rpm DB on my servers keeps getting corrupted? Running Centos 7 (various versions)
The rpm DB on my servers keeps getting corrupted. It seems like every few weeks I have to do an rpm rebuild on a server or two.
Where should I look to see what could be the culprit? I know how to fix this when it happens, but how can I identify if this is a specific package I'm installing or if something is triggering this?

A: There's an endless row of bugs where BDB environment getting corrupted, some of which have been BDB bugs (several found just in the last couple of years) that have been patched in Fedora/RHEL libdb but upstream BDB 5.x does not have, dunno about 6.x but there you run into the licensing side.
This one is well know issue that has no permanent solution.
Root Cause:
If rpm or yum does not exit cleanly the lock files are left behind. The files (__db001 - __db005) are left behind in /var/lib/rpm. We can see the pid that left the files with. The problem tends to be that we have no logs or audit configure for what actually killed the process. The most common reason being an automation tool timed out and abruptly ends the process without letting rpm clear the lock files.
One possible workaround is to force use of private environment. That also means practically no locking, but at least it means queries will not corrupt anything (however queries themselves could return garbage if run in middle of write-operation). That's what happens if you run queries as non-privileged user, but since you can control permissions with sandboxing you can achieve the same by disallowing open of /var/lib/rpm/.dbenv.lock, which causes rpm to fall back to a private environment - meaning it wont open, much less write to those __db.* files.
The developers statement is that it won't be fixed completely:

"Making BDB more reliable would require using transactions there, but
this would be an incompatible change, which is the last thing we want
to do at this point when we're basically just about to deprecate BDB.
Which means we cannot do anything about this, on Berkeley DB backend,
unfortunately."

They provide a suggestion to use dcrpm utility.

dcrpm ("detect and correct rpm") is a tool to detect and correct
common issues around RPM database corruption. It attempts a query
against your RPM database and runs db4's db_recover if it's hung or
otherwise seems broken. It then kills any jobs which had the RPM db
open previously since they will be stuck in infinite loops within
libdb and can't recover cleanly.

You can download it from Git repo.
The official guide is available at the same place.
Here is what you need to do for instalaltion:
# git clone https://github.com/facebookincubator/dcrpm.git
# cd dcrpm
# python setup.py install

After the installation you can run the tool and add it to cron:
# dcrpm

Unfortunately the installation always failed for me on CentOS 7 because of python dependencies never installed properly.
error: Setup script exited with error in psutil setup command: 'extras_require' must be a dictionary whose values are strings or lists of strings containing valid project/version requirement specifiers.

This is despite psutil got installed successfully.
But some other people reported dcrpm worked well for them, so give it a try.
I have used another official solution from Red Hat (RHEL 7).
# curl https://people.redhat.com/kwalker/repos/rpm-deathwatch/rhel7/rpm-deathwatch-rhel-7.repo -o /etc/yum.repos.d/rpm-deathwatch.repo
# yum install -y kernel-{devel,headers}-$(uname -r) systemtap && debuginfo-install -y kernel
# yum install rpm-deathwatch
# systemctl start rpm-deathwatch
# systemctl status rpm-deathwatch


text:
Q: Site loads Sprite Image twice I have been trying to speed up my website, and in doing so I combined a number of my images into a sprite file. Everything works great now, however, when I run the site, either locally or on the test site it loads the sprite file twice, and I can't for the life of me figure out why. I am using masterpages with asp.net, and I only have one css file, not including the css files that some of my telerik controls use, and I have not tampered with any of the telerik css files or sprites. You can venture to our test site at: http://www.myheadpiece.com/test and take a look. The name of the sprite file is ms1.png. I can also provide other code/answers where necessary, I am just not sure what/where to look. If anyone has any ideas please let me know. Thanks.

A: Check the case of the paths to the sprite, you have
http://www.myheadpiece.com/test/Images/Structure/ms1.png
and
http://www.myheadpiece.com/test/images/Structure/ms1.png
One is with a capital "I" the other one with a small "i". So in you CSS you should refer to the sprite either with "Images" or with "images".

A: Your css should look like this:
.Sprite { background-image: url("../Images/Structure/ms1.png"); background-color: transparent; background-repeat: no-repeat; }

.HeaderLogo { background-position: 0 -768px; ... other styles ... }

.CartButton { background-position: -818px -754px; ... other styles ...}

And both HeaderLogo and CartButton should have second css class assigned ('Sprite') so you load an image only once for Sprite class and all the elements that are going to use it change it position only.


text:
Q: Turn on Wifi and connect to a protected SSID on ios with react native I am working on IOT project with react native in which Phone must connect to a protected WiFi(no internet connection). I should programmatically turn on WiFi and connect to the protected ssid. So, I used the following library:  https://github.com/JuanSeBestia/react-native-wifi-reborn.
On android, I have full control on device and everything works like a charm. On the other hand, on ios, I can't turn wifi on and even after that user turns the wifi on, it seems defined functions in library like connectToProtectedSSID just doesn't work.
Any advice would be appreciated.
P.s. I exactely followed the document in the library including location access in both platforms.

A: Finally, the solution for both platforms:
iOS:
with the following approach app will turn on WIFI and connect to the specific SSID (at least for iOS 13):
You should add these capabilities to your app :

*

*Access WiFi Information

*Hotspot Configuration ( this is missed in the README ! )

*(iOS 13) "Privacy - Location When In Use Usage
Description" or "Privacy - Location Always and When In Use Usage
Description" in Settings -> info

 import WifiManager from "react-native-wifi-reborn";
 ConnectToNetwork = async () => {
       WifiManager.connectToProtectedSSID("YourSSIDName", "YourPassword", false)
                .then(
                  () => {
                    //console.log("connectToProtectedSSID successfully!");
                      },
                  (reason) => {
                  //console.log("connectToProtectedSSID failed!");
                  //console.log(reason);
              }
              );
  }

Android:
Don't forget to turn on location!
disconnecting from the current SSID and connecting to the desired one:
import RNAndroidLocationEnabler from 'react-native-android-location-enabler';
import WifiManager from "react-native-wifi-reborn";
     ConnectToNetwork() {
    WifiManager.setEnabled(true);
    WifiManager.disconnect();
    //WifiManager.forceWifiUsage(true);
    PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        title: '',
        message:'',
        buttonNegative: '',
        buttonPositive: '',
      },
      ).then((granted) => {

        //console.log(granted);
        if (granted === PermissionsAndroid.RESULTS.GRANTED)
        {
            //console.log("granted");
            RNAndroidLocationEnabler.promptForEnableLocationIfNeeded({interval: 10000, fastInterval: 5000})
            .then(data => {
              WifiManager.connectToProtectedSSID("YourSSIDName", "YourPassword", false)
              .then(
                () => {
                  //console.log("connectToProtectedSSID successfully!");
                    },
                (reason) => {
                //console.log("connectToProtectedSSID failed!");
                //console.log(reason);
            }
            );
                //console.log("location enabled");
                //WifiManager.connectToProtectedSSID("", "", false)
             WifiManager.getCurrentWifiSSID().then(
              ssid => {
                if(ssid =="YourSSIDName"){
                }
                 else {
                }
                //console.log("Your current connected wifi SSID is " + ssid);
              },
              () => {
                //console.log("Cannot get current SSID!");
              }
            );
            }).catch(err => {
              //console.log("not permitted to enable location");
            });
        }
        else
        {
    //console.log("not granted");
    // Permission denied
        }
        // expected output: "Success!"
      });
  }

A: There is no public API to control the Wifi on iOS.
Method setEnabled is only for android.


text:
Q: Algorithm to convert film negative RGB to positive RGB Assuming I have a photographic film negative scanned as an RGB image, I'm trying to find an algorithm that will convert the color values to an RGB positive.
Due to the orange bias ( http://photo.net/learn/orange-negative-mask ) if I simply say redPositive = 255 - redNegative I get a final image that has a strong cyan tint to it, and is very washed out.  That means the answers given here: Convert negative image to positive are NOT correct.
So how would I craft the following routine:
struct RGB
{
    unsigned byte red;
    unsigned byte green;
    unsigned byte blue;
};

void FilmNegativeToPositive(RGB const &negative, RGB &positive)
{
    // What goes here?
}

A: I don't have data to test, but according to the link you gave, the negative is a mixture of cyan, magenta and yellow dyes that are impure:

The yellow dye layer is the most pure. The magenta dye layer has a noticeable amount of yellow in it. The cyan dye layer has noticeable amounts of both yellow and magenta in it.

Therefore, you want to do something like this (untested pseudocode):
Let I_MY be the ratio of yellow impurity to pure magenta dye
Let I_CY be the ratio of yellow impurity to pure cyan dye
Let I_CM be the ratio of magenta impurity to pure cyan dye

Given R, G, B in [0, 255]
Convert to CMY:
  C = 1.0 - R/255.0
  M1 = 1.0 - G/255.0
  Y1 = 1.0 - B/255.0

Calculate the impurities in the cyan dye and remove them, since we assume no other dye has cyan impurities:
  M = M1 - I_CM×C
  Y2 = Y1 - I_CY×C

Now the amount of magenta dye is correct, so subtract its yellow impurity:
  Y = Y2 - I_MY×M

Convert the corrected CMY values back to RGB:
  R' = 255×(1.0-C)
  G' = 255×(1.0-M)
  B' = 255×(1.0-Y)

If it turns out there's more complicated contamination than that, you get a linear algebra problem:
[   1 I_MC I_YC]   [C']   [C]
[I_CM    1 I_YM] × [M'] = [M]
[I_CY I_MY    1]   [Y']   [Y]

Where you want to solve for C', M', and Y', then convert back to the RGB color space.


text:
Q: How is energy balanced in the Primakoff effect for axions? In the presence of a strong magnetic field, (theoretical) axions are converted to high energy photons via the Primakoff effect.
How is energy balanced in this process? Is the mass of the axion being converted directly to energy, or does some energy come from the transverse magnetic field?
Assuming the energy to drive the B-field is sufficiently low, is it possible to extract energy via the outgoing photons? In current experiments (ABRACADABRA, ADMX), the ratio of the power the machine consumes to the potential signal power in the detected photons is likely many orders of magnitude.

A: In the Primakoff process $\gamma + a \to \gamma$, energy is conserved, i.e.
$$E_0 + E_a = E_1.$$
Since $E = \hbar \omega$, this can also be written as
$$\omega_0 + \omega_a = \omega_1.$$
Most axion experiments consider a static background field, $\omega_0 = 0$, so all the energy comes from the axion field. But in some proposed experimental setups, $\omega_0$ is nonzero, so that $\omega_1$ can be increased. (Disclaimer: I helped write that paper.)
Thus, energy extraction from axion dark matter is possible in principle. The axion power absorbed in a typical resonant cavity is, in natural units,
$$P_{\text{sig}} \sim \frac{g_{a \gamma \gamma}^2 \rho_{\mathrm{DM}}}{m_a} \, (B^2 V Q).$$
For a typical cavity haloscope along the lines of ADMX, we have cavity parameters $B \sim 10 \, \mathrm{T}$, $V \sim 1 \, \mathrm{m}^3$, $Q \sim 10^6$. The local dark matter density is $\rho_{\mathrm{DM}} \approx 0.4 \, \mathrm{GeV}/\mathrm{cm}^3$ and the typical axions targted by ADMX have $g_{a \gamma \gamma} \sim 10^{-16}\, \mathrm{GeV}^{-1}$ and $m_a \sim 10^{-6} \, \mathrm{eV}$. Plugging these numbers in gives the astoundingly small power
$$P_{\text{sig}} \sim 10^{-22} \, \mathrm{W}$$
which is of course the reason these experiments are difficult.
As a fun but incredibly unrealistic final calculation, note that the rate of dark matter mass flow through the Earth is $\mu \sim \rho_{\mathrm{DM}} v R_E^2$ where $v \sim 10^{-3} c$. If you can only capture the kinetic energy, the maximum possible rate of power harvested is roughly $\mu v^2 \sim 1 \, \mathrm{GW}$, which is the output of a typical power plant. If you can capture the full mass-energy, it's $\mu c^2 \sim 10^3 \, \mathrm{TW}$, which dwarfs total human power consumption.


text:
Q: tt_news pagebrowser - How to disable page selector how can I show only "next" and "prev" links under the tt_news list? The typoscript already contains:
plugin.tt_news {
 pageBrowser {
   maxPages = 10
   showResultCount = 0
   showPBrowserText = 1
   dontLinkActivePage = 0

   showFirstLast = 0
   showRange = 0
   hscText = 1

   browseBoxWrap =
|

   activeLinkWrap =
|

   disabledLinkWrap =
|

   inactiveLinkWrap =
|

  }
}

Oh and what does "hscText" stands for?

A: The solution gives Daimi's Skinnablepagebrowser (currently alpha!) which provides additional parameters for the next and prev button. With that and by clearing the normal pagebrowser link wrappers you can only show the next and prev buttons ;D


text:
Q: Why is the time complexity of factorization $2^n$? Can somebody explain to me why, given the factor value N, the time complexity of a factorization algorithm (N / 2, N / 3, N / 4, ...) is $2^n$ rather than n?

A: The time complexity of factorization is $O(N)$*.
However, the complexity class of an algorithm is expressed in terms of the "input size". $N$ is not the input size, the number of (binary) digits $n$ required to express it is.
As $N\le 2^n$, the time complexity is $O(N) = O(2^n)$.

Note*: Assuming integer division is O(1).


text:
Q: mod_rewrite rules to force www and https over main domain, ignoring 1 folder and 1 other domain I've tried tons (probably in excess of 250) different rewrite rules but none of them are having the desired effect.

Rules for maindomain.com which is a wordpress website with SSL & should run with the prefix www.

*

*Check and force www. to the entire domain/folders/subfolders...etc (not just wordpress) EXCEPT the folder testfolder

*Check and force https. to the entire domain/folders/subfolders...etc (not just wordpress) EXCEPT the folder testfolder

Rules for test.otherwebsite.com which is a custom set of pages hosted in /testfolder/ on the server

*

*Check and forcefully remove www. from the domain test.otherwebsite.com

*Check and forcefully changed https to http from the domain test.otherwebsite.com
These rules shouldn't be needed I don't think... if the first set of rules work correctly.

A: No need to use rewrite engine if you have access to main configuration files.
(1) Redirect non www to www. A simpler solution is using VirtualHost directive instead of rewrite engine.
<VirtualHost *:80>
    ServerName maindomain.com
    Redirect permanent / http://www.maindomain.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName www.maindomain.com
    # ... Your www served here
</VirtualHost>

For https, you could just simply copy them and replace the port to 443.
(2) Serve /testfolder in a separate VirtualHost directive
<VirtualHost *:80>
    ServerName test.otherwebsite.com
    # ... anything else
</VirtualHost>

For https, change port to 443.
Note that those won't make exception to /testfolder if accessed from www.maindomain.com/testfolder.
A solution is to move the testfolder outside directory served by www.maindomain.com. For example
/var/www/maindomain <--- directory for www.maindomain.com
/var/www/testfolder <--- directory for test.otherwebsite.com

There is a <DirectoryMatch> directive to prevent that as explained here https://stackoverflow.com/a/214908/779320. But I'm afraid it apply globally and so can't be served in any VirtualHost. But you can test it anyway.

A: 1) You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule !^testfolder/ https://www.maindomain.com%{REQUEST_URI} [NE,NC,R=301,L]

2) Then you can use this code in your /testfolder/.htaccess file:
RewriteEngine On

RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ http://test.otherwebsite.com%{REQUEST_URI} [NE,R=301,L]


text:
Q: How to specify "one at a time" in UML? I'm making a class diagram with a Classroom and a Course class.
How can I indicate that a Classroom can only have one Course in it at a time?  I know I can use multiplicities to specify that a classroom can have exactly one course, but that doesn't exactly specify that there can be other courses than that one course at different times.

A: First solution and temporal issues
Bruno's solution with a 0..1 multiplicity satisfies your explicit requirement: a Classroom can then indeed hold at most one Course at any given time. But it has as consequence that at this given time:

*

*the Classroom doesn't know any other Course that has or will taken place in it.

*Any other Course that will take place in this Classroom in future does not know at this moment where it will take place.

So if you're in the business of time-table and resource scheduling,  this solution will not fulfil the other implicit needs that you didn't mention so far.
Where is the time in your design?
UML provides only limited built-in temporal semantics. You need to add time explicitly in your model. What is missing here is therefore the time slots:

*

*the time slot is not necessarily bound to the Course;  An "Initiation to C++" course may need several lessons, that could take place in several rooms at different times.

*the time slot is obviously not either bound to the Classroom.

An intuitive solution
A TimeSlot can be viewed as related to the association of a Course and to a Classroom. For every course taking place in a room, you'll have to manage the start and end time. This is very natural to model as an association class:

This does not address your "unicity" requirement, but it facilitates its expression with a constraint expressed in natural languate: {Timeslots for a same Classroom cannot overlap}.  You may also express it more formally in OCL.
An alternative approach
You may also analyse the time problem differently, and consider the Classroom as a service offer, composed of RoomSlots that correspond to time intervals. Each RoomSlot would then associated to 0..1 course as Bruno suggested:

This approach makes the management of the time slots more obvious and independent:

*

*you may use fixed time slots of 1 hour, you may allow dynamic time slots by adding, splitting and merging time slots of a same room as needed, always enforcing absence of overlaps.

*the management of the room availability can be analysed and implemented independently of the room usage

*Unassociated RoomSlots explicitly shows available rooms (offer) at a given time, and unassigned Courses shows the needs (demand).

A: The multiplicity is the right way to do, and in your case it is 0..1 because a classroom can be unused => no associated course. A course can be made in different classrooms or even none if outside so I use *.

that doesn't exactly specify that there can be other courses than that one course at different times

I disagree, the association Classroom --- Course does not specify the associated course (and classroom(s)) cannot change, so without additional constraint or setting it readOnly it can change


text:
Q: run GitLab with docker image in windows 10 on localhost I have installed a docker image "gitlab/gitlab-ce" on windows 10 and I try to run with following command.
docker run --detach --hostname https://localhost/ --publish 40443:80 --name GitLab --restart always --volume d:\gitlab\config:/etc/gitlab --volume d:\gitlab\logs:/var/log/gitlab --volume d:\gitlab\data:/var/opt/gitlab gitlab/gitlab-ce:latest

but when it doesn't accessible in browser.
"This site can't be reached.
localhost unexpectedly closed the connection."
I don't known what is wrong here in GitLab document the host name is "gitlab.example.com" and I don't known what is domain refer to.

A: You should use your own ip instead of "localhost" word.Because localhost IP is different for the docker.So you should check your ip address with ipconfig cmd command.And set the docker run command with your ip address.
I have write step by step at this comment : https://stackoverflow.com/a/66357935/11040700

A: Your docker container is exposed on :40443 port
Ref.: https://docs.docker.com/config/containers/container-networking/
P.S. hostname should be without https://


text:
Q: "List elements that take up more than one line are not permitted" error with complex IF statement I'm new to ABAP coding in APDs.  How would I write a statement like this in ABAP code?
if ((ls_source-VHMODEL == 'M1' OR ls_source-VHMODEL == 'M2') AND (ls_source-CREATE_DATE <= '2016-01-01' AND ls_source-CREATE_DATE >= '2014-01-01'))
{
// do stuff
}
else if ((ls_source-VHMODEL == 'H1' OR ls_source-VHMODEL == 'C3') AND (ls_source-CREATE_DATE <= '2015-01-01' AND ls_source-CREATE_DATE >= '2014-02-01'))
{
// do stuff
}

I tried this:
  if ( ( ls_source-VHMODEL EQ 'M1' OR ls_source-VHMODEL EQ 'M2')  AND
(ls_source-CREATE_DATE > '20120122' AND ls_source-CREATE_DATE < '20120922')).
    MOVE 'Segment 2' TO ls_target-SEGMENT.
  else.
    MOVE 'Other' TO ls_target-SEGMENT.
  endif.

But that gave me the error

Syntax error: List elements that take up more than one line are not permitted.

A: Try this:
if (  ( ls_source-vhmodel eq 'M1' or ls_source-vhmodel eq 'M2' ) and
      ( ls_source-create_date le '20160101' and ls_source-create_date ge '20140101' )
   ).
* Do something
elseif (
          ( ls_source-vhmodel eq 'H1' or ls_source-vhmodel eq 'C3' ) and
          ( ls_source-create_date le '20150101' and ls_source-create_date ge '20140201' )
       ).
*Do something
endif.

Be aware of the parentheses how they are separated in the code.
Hope it helps.

A: Could you check that your parenthesis are preceded and followed by a space ?.
The ABAP compiler is notoriously sensible for such things, since parenthesis may mean somthing else (ie. offset in data).

A: Your problem is parentheses and also spacing before and after ( and ).
This code compiles:
if ( ls_source-vhmodel eq 'M1' or ls_source-vhmodel eq 'M2' )  and
  ( ls_source-create_date > '20120122' and ls_source-create_date < '20120922' ).
  move 'Segment 2' to ls_target-segment.
else.
  move 'Other' to ls_target-segment.
endif.

A: The problem is that you haven't left a space between the parentheses.  Unlike other languages ABAP requires a space between the parentheses and the rest of the statement.
(ls_source-CREATE_DATE > '20120122' AND ls_source-CREATE_DATE < '20120922')).
^^^                                                                       ^^^


text:
Q: MySQL Database Connection Problems I recently set up a a database, and made a code that allowed people to register for a members page on this website I'm building. The code I used has worked before, many times, but for some reason I keep getting this error message when I try to submit data as a test:
Failed to connect to server: Lost connection to MySQL server at 'reading initial communication packet', system error: 111

I've tried everything I know, but nothing works. I think I'm just missing something, here's the php code that sends the data (however, nothing in the code seems to be wrong or out of place):
<?php

session_start();

require_once('config.php');

$errmsg_arr = array();

$errflag = false;

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

$db = mysql_select_db(DB_DATABASE);
if(!$db) {
    die("Unable to select database");
}

function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}

$fname = clean($_POST['fname']);
$lname = clean($_POST['lname']);
$login = clean($_POST['login']);
$password = clean($_POST['password']);
$cpassword = clean($_POST['cpassword']);

if($fname == '') {
    $errmsg_arr[] = 'First name missing';
    $errflag = true;
}
if($lname == '') {
    $errmsg_arr[] = 'Email';
    $errflag = true;
}
if($login == '') {
    $errmsg_arr[] = 'Login ID missing';
    $errflag = true;
}
if($password == '') {
    $errmsg_arr[] = 'Password missing';
    $errflag = true;
}
if($cpassword == '') {
    $errmsg_arr[] = 'Confirm password missing';
    $errflag = true;
}
if( strcmp($password, $cpassword) != 0 ) {
    $errmsg_arr[] = 'Passwords do not match';
    $errflag = true;
}

if($login != '') {
    $qry = "SELECT * FROM members WHERE login='$login'";
    $result = mysql_query($qry);
    if($result) {
        if(mysql_num_rows($result) > 0) {
            $errmsg_arr[] = 'Login ID already in use';
            $errflag = true;
        }
        @mysql_free_result($result);
    }
    else {
        die("Query failed");
    }
}

if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: register-form.php");
    exit();
}

{
    mkdir("somedirectory//$login") or die ("Could not make directory");
}

{
    $ourFileName = "somedirectory/$login/verify.txt";
    $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
    fclose($ourFileHandle);

    $ourFileName = "somedirectory/$login/name.txt";
    $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
    fclose($ourFileHandle);

}

{

    $myFile = "somedirectory/$login.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = "$login\n";
    fwrite($fh, $stringData);
    fclose($fh);
}
{

    $file = '000001.php';
    $newfile = "somedirectory/$login/$login.php";

    if (!copy($file, $newfile)) {
        echo "failed to copy $file...\n";}

}

$qry = "INSERT INTO members(firstname, lastname, login, passwd) VALUES('$fname','$lname','$login','".md5($_POST['password'])."')";
$result = @mysql_query($qry);

if($result) {
    header("location: register-success.php");
    exit();
}else {
    die("Query failed");
}
   ?>

Any ideas what is causing the MySQL connection error?

A: System error 111 is ECONNREFUSED, so there isn't anything listening on the specified host; either the host is incorrect or MySQL isn't running on it.


text:
Q: magento 2: 'i18n:collect-phrases' command creates different csv files php bin\magento i18n:collect-phrases -o "C:\xampp\htdocs\magento\app\design\i18n\xx_YY.csv" -m

collects all phrases in the magento application and outputs a csv file with 4 columns:

php bin\magento i18n:collect-phrases -o "C:\xampp\htdocs\magento\app\design\i18n\xx_YY2.csv" C:\xampp\htdocs\magento\app\design\frontend

collects all phrases in app\design\frontend and outputs a csv file with 2 columns:

What is the difference in the two files ?
Also I'm currently using de_DE.csv from https://github.com/splendidinternet/Magento2_German_LocalePack_de_DE
which (i think) translates the whole magento application. Why does this file have 2 columns instead of 4 (like the xx_YY.csv I created) ?
Also, when I install a new theme , can I just collect all phrases from that theme into a csv file (2 columns) -> then copy and paste it's content into the end of the file de_DE.csv and everything will work ?

A: The CSV with 4 columns is the global CSV for all modules. That's why it contains 3rd column as module and 4th column as Module_Name.This file should be placed in i18n folder parallel to app.
The CSV with 2 columns is the CSV required for each module. That's why module name is not specified in it. This file is located under i18n folder of each module.

A: The csv with 4 columns is used to create language package with composer.
In official doc http://devdocs.magento.com/guides/v2.1/config-guide/cli/config-cli-subcommands-i18n.html#config-cli-subcommands-xlate-dict :

-m | --magento
  Required to create a language package from this translation dictionary. If used, searches the directories that contain bin/magento. This option adds themes or modules to each line in the dictionary.

A: You will get all the text with module and theme name with this command :
bin/magento i18n:collect-phrases --output="<csv file path and name>" --magento

In this first you have to create a csv file on any path of your magento directory and set full path (absolute path) of your file here "". It will export all the text with module/theme name.


text:
Q: link for max characters in javascript not working Ive got a js that runs to see if a maximum amount of characters is reached. Its got text along with href, but when the max amount of characters is reached, the link doesnt work and converts it to just text. When the limit of less then 580 characters, link works. When it does reach the limit, the read more link does work. Any advice or help please and thanks
$(document).ready(function () {
var stylistText = $('#stylistText');
var stylistText2 = document.getElementById("stylistText").innerHTML;
var countActualText = stylistText2.valueOf().length;
var maxLength = 580;
var aElement = document.createElement('a');
var linkText = document.createTextNode(" ...Read more");
aElement.appendChild(linkText);
aElement.href = "#";

if (countActualText > maxLength) {
    stylistText.text(stylistText.text().substring(0, 580));
    stylistText.append(aElement);
   }
});

here is the html

            This is supposed to be a link Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.

A: Change stylistText.text(stylistText.text().substring(0, 580));
to stylistText.html(stylistText.html().substring(0, 580));
However, truncating a block of text that contains HTML may cause other problems, especially if the truncation occurs in the middle of an element.  I would recommend rethinking your whole strategy on this.


text:
Q: How to use token id(value) from html response in jmeter correlation Just leaning correlation, Please help me how to user token id under jmeter , i am using token id then getting error,
Please help me.
Website link is : https://opensource-demo.orangehrmlive.com/
and credentials : ( Username : Admin | Password : admin123 )
Attached images for reference purpose.

A: The response is not JSON, it's normal HTML so you should be using CSS Selector Extractor in order to get the value of the _csrf_token hidden input field
Design your test plan as follows:

*

*Add HTTP Request sampler which will send simple GET request to the https://opensource-demo.orangehrmlive.com/ page

*Add CSS Selector Extractor as a child of the above request

*Configure it as follows:

*

*Name of created variable: tokenid

*CSS Selector Expression: form[id=frmLogin] > input[id=csrf_token]

*Attribute: value
Demo:

*Add the request which is at your screenshot to be after the first GET request

See How to Handle Correlation in JMeter article to learn more about handling dynamic data in your JMeter tests.


text:
Q: Jupyter notebook: when using twinx() the first plot disappears. What am I doing wrong? I would like to simply plot in the same figure two graphs with different scales. Following the standard example http://matplotlib.org/examples/api/two_scales.html, I tried this on the jupyter notebook adding the lines
import matplotlib as mpl
%matplotlib inline
import matplotlib.pyplot as plt
import mpld3
mpld3.enable_notebook()

This doesn't work. I get a figure without the plot for the first graph. This was also in https://github.com/mpld3/mpld3/issues/188 noted as a problem but it is surely old, isn't it? Is there anything I can do? This is probably a very basic question, but I don't understand what I'm doing wrong and I don't find any solution!
Thanks for any comment!