text:
Q: The equation of a sphere tangent to a plane at a point and also tangent to another plane
Determine the equation of the sphere that is tangent to the plane
$$(P):6x-3y-2z-35=0$$ at $M(5,-1,-1)$ and also tangent to the plane
$$(Q):6x-3y-2z+63=0$$

My solution:
Let $d$ be the line passing through $M$, $d$ orthogonal to $(P)$. The parametric equations of the line $d$ are:
$$x = 5+6t$$
$$y=-1-3t$$
$$z=-1-2t$$
So the center of the sphere is of the form $C(5+6t, -1-3t,-1-2t)$. The center of the sphere must belong to the line $d$ and the plane $(Q)$, so it is the intersection point between the line and the plane.
$$6(5+6t)+3(1+3t)+2(1+2t)+63=0$$
From this relation we get $t=2$, so the center has the coordinates $C(17,-7,-5)$. Now since it's stated that the plane $(Q)$ is tangent to the sphere, the distance from the center to the plane is equal with the radius. The radius $r=14$, so now we have the equation of the sphere:
$$(x-17)^2+(y+7)^2+(z+5)^2=14^2$$
Is this correct? I'm not sure if my initial condition for the center to belong to the line $d$ and the plane $(Q)$ is right, but I based my assumption off of the fact that they are both tangent to the sphere and so the distance from the center to each plane is equal with the radius.
EDIT: Okay, so my assumption was definitely wrong, I somehow didn't notice the normal vectors were identical

A: Hint
Your sentence

The center of the sphere must belong to the line $d$ and the plane $(Q)$...

is not correct. As the sphere is supposed to be tangent to the plane $(Q)$ its center does not lie in $(Q)$.
However, you can use the fact that the center of the sphere lies on the line $d$ and that its distance to the plane $(P)$ should be equal to its distance to the plane $(Q)$.

A: No, that is not correct. You already know that the center of the sphere is of the form $(5+6t,-1-3t,-1-2t)$, for some real $t$. Since the planes $P$ and $Q$ and parallel, $C$ has to be the midpoint between $M$ and the point $M'$ which belongs to the line $(5+6t,-1-3t,-1-2t)$ and to $Q$. But $M'=(-7,5,3)$, and therefore $C=(-1,2,1)$ (and the radius is $7$).

A: (New user here, so I don't have enough reputation to comment)
Why should $Q$ contain the center of the sphere? In fact, if it does, is $Q$ still tangential?
Here's some motivation for a possible solution: Start with the line $d$. Since the two given planes are parallel, can you see why $d$ must contain the center of the sphere? Now try to use this fact, along with the distance between the planes (which is standard computation) to figure out the center/radius of the sphere.


text:
Q: Use deployment contributor with schema compare Is it possible to use a custom deployment contributor with the SSDT schema compare tool in Visual Studio?
In the msbuild targets file I can see the SqlSchemaCompareTask supports additional deployment contributors, but I can't see in the scmp file where I would specify any contributors.

A: When running Schema Compare from the command line MSBuild task, this is possible. From inside Visual Studio, it is not supported at this time.
The AdditionalDeploymentContributors and other properties on the MSBuild task are command line overrides that update the deployment engine, but there are no built-in options for Schema Compare to use a deployment contributor. Hence there is no way to make this work when using Schema Compare in VS.
A note on what the contributors do in this scenario: the deployment contributor could modify the final deployment plan generated by Schema Compare, once the user chooses to update/script the results. It will not change what shows up in the Schema Compare added/deleted/changed list but could alter how they actually get deployed.
If you see a scenario where this would be useful to you and other consumers of Schema Compare, the best way to raise this is by opening a Connect DCR at https://connect.microsoft.com/SQLServer/feedback/CreateFeedback.aspx and use the category "Developer Tools(SSDT, BIDS,etc.)".
Disclosure: I work on the SSDT team.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should we use integer strictly when we layout controls in iOS? Why? I need to draw a line on the screen. The designer tell me to set the height of line to 2.5 pt. I'm wondering if it's acceptable to use decimal here.
I know it will be better if we use integer as the size or position of a UIView. But I can't tell why. I didn't find any convincing document about it.
So could anyone explain it or find something for me?
The only problem I know is UILabel with decimal size will be blurry. Is there any other problem like performance problem would happen?

A: As per your case it's just about half point which in my opinion should be ok. I often find that in storyboards my frames get moved 0.5 point up or down when I have lot of UI elements and sometimes constraints just get confused.
Additionally: the easiest scenario when your frame could be positioned at "some 0.5 point" is if you use a constraint to centre your view in it's superview. In this case the default x or y frame position could easily end up being "some 0.5 point". So it can happen often times and could be done by Xcode itself, so that's why I think your view will be just fine.
As stated previous in comments those points are CGFloat. What we have now is 1x, 2x and 3x resolutions. So there will always be the need for some calculations for at least one of the devices.
You may also look at this Screen resolutions guide to see all the time when up sampling and downsampling occurs.


text:
Q: Why is the network not learning as effective (Tensorflow - LSTMs for text generation)? When I initially ran a 2 LSTM network (each 512 units) on the Shakespeare corpus, I got a pretty decent output after 2 epochs of training (where each epoch = one cycle through the dataset).
Here it is:
best ward of mine
him that you a man of make the pein to the noble from his day?
DUKE VINGEN:
So that man be, mure the this more to the part that the tongue were an one shall you an every wall.
HALLES:
Why, your hall thou to the good word to my sole mister of the men and the twouse to your ever and me the appice to be a forting would the crease.
HARLET:
I would not the ching and not the good souls as be be he of the seement that is dead mone stains to me the ufber me do and with the sures and to conforn the tre
It was still learning, with loss of 1.73 and the graph of loss was not levelling off. However, in all subsequent runs (10) it has not been able to achieve anywhere as near as good results - after 6 epochs, for example, in my best run subsequently it had a loss of 2.43 and was levelling off -
this is the output:
friar?
How doth my l mo toee  or inrou
 o  inain  me c ahes oisteese an th thet  ot spr  h
 sat t heooi to  yerton dhe  tha   dou tr hum es teride t an  Mose lhre moud wilh the will  add toe  exereaasne op ther sa e  and ho m reevion
hatd tik  t e thane ofore te,t
hhe serined   o chane the   ertrs  aine thele aelt  To tee  g te
 ou so yos we tiie be rere th livt hir but at jnt hu
As   ehmug te to fare t ce
To tha mhn hi did r t ter  oe hir  rat ft thr ionyoee wh  eoo that e cade tientta To
tike  a r  hee  ta t he
This is similar to the outputs after 4, 5, 6 epochs. Most commonly, in the runs subsequent to the initial run, the network would level off learning after a loss of 2.70.
This is the graph of the loss
 and I have also posted the code:
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import tflearn
from tflearn.data_utils import *
from tflearn.layers.estimator import regression

inputs, targets, char_dict = \
    textfile_to_semi_redundant_sequences("shakespeare_input.txt", seq_maxlen=20) #helper - vectorises text

LSTM = tflearn.input_data([None, 20, len(char_dict)])
LSTM = tflearn.lstm(LSTM, 512, return_seq=True, restore=True, dropout = 0.5)
LSTM = tflearn.lstm(LSTM, 512, restore=True, dropout = 0.5)
LSTM = tflearn.fully_connected(LSTM, len(char_dict), activation='softmax')

LSTM = tflearn.regression(LSTM, optimizer= 'adam', loss='categorical_crossentropy',
                       learning_rate=0.001)

LSTMmodel = tflearn.SequenceGenerator(LSTM, dictionary=char_dict,
                              seq_maxlen=20,
                              clip_gradients=5.0, tensorboard_verbose=0,tensorboard_dir='pathfile/logs')

#LSTMmodel.load('/pathfile/LSTMmodel.tfl')
for i in range(10):
    print("-- TESTING...")
    starting = random_sequence_from_textfile("shakespeare_input.txt", 20)
    output_path = 'pathfile/epoch_' + str(i) + '_output.txt'
    generated_output = LSTMmodel.generate(500, temperature=1.0, seq_seed=starting)
    text_file = open(output_path, "w") #save the outputs to a text file - allows us to view progress of model
    text_file.write("With temperature 1.0: \n \n \n") #two different temperatures - higher temp = more novel
    text_file.write(generated_output)
    generated_output = LSTMmodel.generate(500, temperature=0.5, seq_seed=starting) #lower temp = more accurate to original text
    text_file.write("\n \n \n With temperature 0.5: \n \n \n")
    text_file.write(generated_output)
    text_file.close()
    print("-- TRAINING...")
    LSTMmodel.fit(inputs, targets, batch_size=200, n_epoch=1, run_id='Shakespeare_Generator',shuffle = True)
    print("-- SAVING MODEL...")
    if (i%2==0):
        LSTMmodel.save("pathfile/LSTMmodel.tfl")
    else:
        LSTMmodel.save("pathfile//LSTMmodel2.tfl")
    print("-- EPOCH " + str(i+1) +" COMPLETE...")

Since I am running this on an old dual core i3 with 4gb of RAM, the network takes 6 hr 45 mins to go through one epoch. And of course, it will take at least two epochs to see results. So unfortunately, I cannot keep tweaking the code and running and re-running. I am also limited by the memory of my computer, as 1gb of the 4 is allocated to Ubuntu - the other 3 allocated to Windows. Therefore, I can only train a small network.
I would really appreciate if someone could provide a link to a pre-trained network

A: I don't have an answer for this model, but have you tried starting with an existing example for a Shakespeare-generating LSTM, like this one?
https://github.com/sherjilozair/char-rnn-tensorflow
It should be a bit quicker to train, and if you're starting from a working example it might be easier to debug where it's going wrong.


text:
Q: Android: Your content must have a ListView whose id attribute is android.R.id.list I'm getting this run-time error and I'm really struggling to get to the bottom of it: "Your content must have a ListView whose id attribute is android.R.id.list".
Here is my code:
public class ShowAllJobsInArea extends ListActivity{

    Context context;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_jobs_in_area);
        context=getApplicationContext();

        String area=Cookie.getAreaSelected();

        final ProgressBar thinger=(ProgressBar) findViewById(R.id.progressBar2);
        TabHost tabHost=(TabHost)findViewById(android.R.id.tabhost);
        tabHost.setup();

        TabSpec spec1=tabHost.newTabSpec("Tab 1");
        spec1.setContent(R.id.tab1);
        spec1.setIndicator("Starting");

        TabSpec spec2=tabHost.newTabSpec("Tab 2");
        spec2.setContent(R.id.tab2);
        spec2.setIndicator("# Days");

        TabSpec spec3=tabHost.newTabSpec("Tab 3");
        spec3.setContent(R.id.tab3);
        spec3.setIndicator("Rate");

        tabHost.addTab(spec1);
        tabHost.addTab(spec2);
        tabHost.addTab(spec3);

        Handler handler = new Handler() {
             public void handleMessage(Message message) {
                  switch (message.what) {
                      case HttpConnection.DID_START:
                          thinger.setVisibility(View.VISIBLE);
                          break;
                      case HttpConnection.DID_SUCCEED:
                          String response = (String) message.obj;
                          Log.i("EOH",response);

                          ArrayList<String> startDates=new ArrayList<String>();
                          ArrayList<String> ns=new ArrayList<String>();
                          ArrayList<String> rates=new ArrayList<String>();
                          HashMap<String, JSONObject> countyObjs=new HashMap<String, JSONObject>();

                          JSONObject object = null;
                          try {
                              object = (JSONObject) new JSONTokener(response).nextValue();

                              for(int i=0;i<object.length();i++){
                                  String area="";
                                  String endDate="";
                                  String endTimes="";
                                  String id="";
                                  String startDate="";
                                  String startTimes="";
                                  String rate="";
                                  String alreadyApplied="";
                                  String n="";
                                  JSONObject countyObj=object.getJSONObject(String.valueOf(i));
                                  countyObjs.put(id, countyObj);

                                  area=countyObj.getString("area");
                                  endDate=countyObj.getString("endDate");
                                  endTimes=countyObj.getString("endTimes");
                                  id=countyObj.getString("id");
                                  startDate=countyObj.getString("startDate");
                                  startTimes=countyObj.getString("startTimes");
                                  rate=(countyObj.getString("rates").split(","))[0];
                                  alreadyApplied=countyObj.getString("alreadyApplied");
                                  n=countyObj.getString("n");

                                  startDates.add(startDate+","+id);
                                  ns.add(n+","+id);
                                  rates.add(rate+","+id);
                              }
                          }catch (JSONException e) {
                              e.printStackTrace();
                          }

                          Collections.sort(startDates);
                          Collections.sort(ns);
                          Collections.sort(rates);

                          String[] startDates_str = new String[startDates.size()];
                          startDates.toArray(startDates_str);

                          setListAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, startDates_str));
                          //setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
                          ListView lv = getListView();
                          lv.setTextFilterEnabled(true);

                          thinger.setVisibility(View.INVISIBLE);

                          break;
                      case HttpConnection.DID_ERROR:
                          thinger.setVisibility(View.INVISIBLE);
                          break;
                      default:
                          break;
                  }
             }
        };

        List<NameValuePair> params = new ArrayList<NameValuePair>(1);
        params.add(new BasicNameValuePair("area", area));
        new HttpConnection(handler).post("http://www.xlhi.com/ajax/getJobsInArea.php",params);
    }
}

show_jobs_in_area.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <TabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent">
        <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
            <TabWidget android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/tabs"></TabWidget>
            <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@android:id/tabcontent">
                <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tab1" android:orientation="vertical">
                    <ProgressBar android:id="@+id/progressBar2" android:layout_height="wrap_content" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="25dip"></ProgressBar>
                    <ListView android:id="@+id/listView1" android:layout_height="wrap_content" android:layout_width="match_parent"></ListView>
                </LinearLayout>
                <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tab2"></LinearLayout>
                    <ListView android:id="@+id/listView2" android:layout_height="wrap_content" android:layout_width="match_parent">
                </ListView>
                <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tab3">
                    <ListView android:id="@+id/listView3" android:layout_height="wrap_content" android:layout_width="match_parent"></ListView>
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</LinearLayout>

list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

I've tried changing the id to android.id="@android:id/list" to no avail - still getting the same error. I was thinking it's something to do with the asynchronous request I'm doing... I'm really stuck now and hope someone can help.
Many thanks in advance,

A: If you have more than one ListView in your layout you should not extend ListActivity but rather extend Activity and handle the ListViews yourself like;
ListView list1 = (ListView) findViewById(R.id.myList1);
list1.setAdapter(...);

ListView list2 = (ListView) findViewById(R.id.myList2);
list2.setAdapter(...);

ListActivity is a shorthand helper class that makes life easier when you are working with only one ListView in your layout.

A: In you show_jobs_in_area.xml one of the list id to:

A good example is here
Listview error: "Your content must have a ListView whose id attribute is 'android.R.id.list'"

A: if you use getListView(); make sure that the target list\s id is "list".


text:
Q: Jquery/YUI - Find image and set CSS to display:none I have the following image in a CMS that I want to hide, I dont really want to change source code but would like to hide a specific image which does not have a class applied.
Here is the HTML:

I want to hide the  and the , bare in mind the title and alt tag can be different so cant use that as an identifier.
I presume I could use .find() and then use .parent() to set the  to display: none; thus hiding the img?
Im inlcuding the jQuery library, however the CMS has YUI included out of the box so if anyone has a YUI method it would be appreicated.

A: YUI 2.x (w/ Selector)
YAHOO.util.Dom.setStyle(YAHOO.util.Selector.query(".right.side a:first"), "display", "none");

YUI 2.x (w/o Selector)
var rightSide = YAHOO.util.Dom.getElementsByClassName("right", "td")[0],
    a = rightSide.getElementsByTagName("a")[0]

YAHOO.util.Dom.setStyle(a, "display", "none");

YUI 3.x
Y.all(".right.side a:first").setStyle("display", "none");

A: The jQuery method would be:
$(".right.side a:first").hide();

This gets the first  underneath the class="right side" element and sets it to display: none.  Be sure to replace $ with jQuery if using no conflict :)

A: If you are needing to hide the http://vl3.co.uk/iphone/pix/i/one.gif image everywhere it shows up on the page you can do this:
$("img[src*='iphone/pix/i/one.gif']").parent('a').hide();


text:
Q: please I don't understand the second and third line of the code below I saw this in someones code and i'm trying to understand what it means
 if(output=="" && history!=""){
            if(isNaN(history[history.length-1])){
                history = history.substr(0, history.length-1);
            }
        }

A: 'history' is an Array
the secound line is checking if the last item of 'history' array is not a number, if so, the third line deletes the last item in  the array


text:
Q: CLI select default printer for xrdp-connected users according to user's IP A few users connect to the server via XRDP. I need to write a script (on login to MATE) to assign a default printer (via lpoptions -d) for each user but depending on the IP address from which the user is connected to server.
To do this, I need to determine from which IP address each user is connecting. But so far I have not found a way to determine IP addresses of connected users. Any ideas?


text:
Q: Prevent refresh of @FetchRequest if view's @State changes Scenario
I have implemented a parent view which contains a list of CoreData objects (populated using a predicate and @FetchRequest) and a toolbar. If the user scrolls down in the list, the toolbar is hidden in any case. If the user scrolls up, the toolbar is shown again. As the user can also scroll to the top by tapping the App's title bar (iOS default behaviour), the list in the subview reports "firstElementIsVisible = true" once its first element has appeared. This is my current code:
Main view (parent view)
struct MainViewTabItem: View, Equatable { // Equatable is used for other purposes (identifying tabs)
@Environment(\.horizontalSizeClass) var horizontalSizeClass
@StateObject var modelTab: MainViewTabItemViewModel // ViewModel which contains search predicates

@State var lastHandledMainViewScrollGestureTime: Date?
@State var hideToolBar: Bool = false
@State var firstElementIsVisible: Bool = true

var body: some View {
    GeometryReader {geo in
        ZStack(alignment: .top) {
            VStack{
                // MARK: Toolbar
                if !hideToolBar {
                    MainViewToolbarView(modelTab: modelTab)
                }
                // MARK: - List (subview)
                MainListView(modelMain: MainViewModel.shared,
                             predicate: Card.predicate(searchText:              modelTab.searchText,
                                                       isPinned:                modelTab.filterIsPinned),
                             sortDescriptor: CardSort(sortType: modelTab.cardSortType, sortOrder: modelTab.cardSortOrder).sortDescriptor,
                             firstElementIsVisible: $firstElementIsVisible.onChange(firstElementIsVisibleChanged))

                .simultaneousGesture(DragGesture().onChanged({ gesture in
                    // Hide/Show toolbar if scrolled up/down
                    if let lastHandledMainViewScrollGestureTime = lastHandledMainViewScrollGestureTime, gesture.time == lastHandledMainViewScrollGestureTime {
                        // Don't handle gesture as it has been handled before
                    }
                    let isScrollingDown = gesture.location.y > gesture.predictedEndLocation.y
                    hideToolBar = isScrollingDown
                }))
            }
        }
    }
}

func firstElementIsVisibleChanged(to value: Bool) {
    // Uses this great Binding-Extension: https://www.hackingwithswift.com/quick-start/swiftui/how-to-run-some-code-when-state-changes-using-onchange
    if value {
        hideToolBar = false
    }
}}

List (subview)
struct MainListView: View {
@StateObject var modelMain: MainViewModel

@FetchRequest(
    entity: Card.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \Card.dateCreated, ascending: false)
    ]
)
private var result: FetchedResults<Card>

@Binding var firstElementIsVisible: Bool

init(modelMain: MainViewModel,
     predicate: NSPredicate?,
     sortDescriptor: NSSortDescriptor,
     firstElementIsVisible: Binding<Bool>) {

    _modelMain = StateObject(wrappedValue: modelMain)

    let fetchRequest = NSFetchRequest<Card>(entityName: Card.entity().name ?? "Card")
    fetchRequest.sortDescriptors = [sortDescriptor]

    if let predicate = predicate {
        fetchRequest.predicate = predicate
    }
    _result = FetchRequest(fetchRequest: fetchRequest)
    _firstElementIsVisible = firstElementIsVisible
}

var body: some View {ScrollViewReader { proxy in
        ScrollView{
            LazyVStack {
                    ForEach(result) { (card: Card) in
                        Text(card.idNumber.description
                        .onAppear{
                            if let firstItem = result.first, firstItem.id == card.id {
                                firstElementIsVisible = true
                            }
                        }
                    }
                }
        }

    }
}}

Question
The above code works, however, a new FetchRequest fires each time the "hideToolBar" State of the parent view changes despite the MainViewModel's parameters used for the fetch predicate not changing (in some cases even leading to an endless loop). Is there any way to prevent these fetches or is this the way SwiftUI views work (e.g. a FetchRequest fires if the view moves)?
Many thanks!


text:
Q: How to convert slice of string to slice of float in Golang I am trying to convert a slice of string into float but the result isn't a slice. Is there a way to convert the elements within a slice of string to float64 to return a slice of float64?
func main() {

a := []string{"20.02", "30.01"}

fmt.Println("This is a single slice of string:", a)

for i, element := range a {
    element, _ := strconv.ParseFloat(element, 64)
    //This result converts each element to float64 but no longer holds them in a slice.
    fmt.Printf("%v, %v\n", i, element)
}

}
Go playground: https://go.dev/play/p/LkNzgvDJw7u

A: Create a slice of float64 and append each element to it.
package main

import (
    "fmt"
    "strconv"
)

func main() {

    a := []string{"20.02", "30.01"}

    fmt.Println("This is a single slice of string:", a)

    // Creates a float64 slice with length 0 and capacity len(a)
    b := make([]float64, 0, len(a))

    for _, element := range a {
        element, _ := strconv.ParseFloat(element, 64)
        b = append(b, element)
    }

    fmt.Println(b)
}


text:
Q: Six channel output with NAudio? (Or suggestions for other .NET library that supports it?) I've written a method in C# using NAudio that successfully outputs 2 channel sound, but fails at 6 channel sound.
When using WaveOut, I get 'MmException was unhandled: InvalidParameter calling waveOutOpen'
Here's my code:
    public class AudioOutput {
    private WaveOut latestAudioOut = null;
    private WaveMemoryStream latestMemoryStream = null;
    public void PlayAudio (byte[][] buffers, WaveFormat format) {
        if (latestAudioOut != null) {
            latestAudioOut.Stop();
            latestAudioOut.Dispose();
        }
        latestAudioOut = new WaveOut();
        if (latestMemoryStream != null) {
            latestMemoryStream.Dispose();
        }
        int longestChannelLength = 0;
        foreach (byte[] b in buffers) {
            if (b != null) if (b.Length > longestChannelLength) longestChannelLength = b.Length;
        }
        byte[][] finalisedbuffers = new byte[buffers.Length][];
        for (int i = 0; i < buffers.Length; i ++) {
            finalisedbuffers[i] = new byte[longestChannelLength];
            if (buffers[i] != null) buffers[i].CopyTo(finalisedbuffers[i], 0);
        }
        buffers = finalisedbuffers;
        byte[] interLeavedBuffer = new byte[longestChannelLength * buffers.Length];
        int bytesPerSample  = format.BitsPerSample / 8;
        int frameLength = buffers.Length * bytesPerSample;
        int numberOfFrames = longestChannelLength / bytesPerSample;
        int position = 0;
        int frameStart = 0;
        for (int f = 0; f < numberOfFrames; f ++) {
            for (int c = 0; c < buffers.Length; c ++) {
                for (int b = 0; b < bytesPerSample; b ++) {
                    interLeavedBuffer[position] = buffers[c][frameStart + b];
                    position ++;
                }
            }
            frameStart += bytesPerSample;
        }
        MemoryStream bufferStream = new MemoryStream(interLeavedBuffer);
        latestMemoryStream = new WaveMemoryStream(bufferStream, format);
        latestAudioOut.Init(latestMemoryStream);
        latestAudioOut.Play();
    }

A: I would suppose you need to use WaveFormatExtensible instead of WaveFormat.

A: I know this might appear to be a glib response that doesn't actually tackle your particular problem but I had a requirement to provide extensive audio support in my own project a few years ago.
After evaluating all the C# compatible libraries I could find (including NAudio) I opted to use BASS Library from Un4seen Developments This library is amazing and has full and extensive support for C#.
It can handle everything I've ever thrown at it and supports a rich plugin environment and VST support as well.  Achieving what you need using BASS should be very straight forward and the support forums are very good.


text:
Q: Invoking a RESTFul WebService using WinHttp I am totally new with VB6 and REST architecture. Nevertheless I would like please to know if there is any HelloWorld example for a REST Client which invokes a RESTFul webService using Windows HTTP Services API. Many thanks in advance.

A: Here's the solution :
Sub SendAsynchMessage()

Dim objHTTP As New WinHttp.WinHttpRequest
Dim doc As New MSXML2.DOMDocument
Dim root As MSXML2.IXMLDOMNode
Dim success As Boolean
Dim str As String
On Error GoTo ErrorHandler
success = doc.Load(App.Path & "\flow.xml")
Set root = doc.selectSingleNode("/root")
str = CStr(root.childNodes.Item(0).xml)
URL = "http://ipAddress:8081/messageAsynch"
objHTTP.Open "POST", url, False
objHTTP.SetRequestHeader "Content-Type", "text/xml; charset=utf-8"
objHTTP.Send (str)
Debug.Print objHTTP.Status
Debug.Print objHTTP.ResponseText
Exit Sub
ErrorHandler:
Dim E As ErrObject: Set E = Err

End Sub

The "flow.xml" file could look like in this case :
<?xml version="1.0" encoding="utf-8" ?>
<root>
  <!-- your xml flow to be send via http -->
</root>


text:
Q: How to read JSON {"success": true} in Retrofit 2? In normal JSONObject jsonResponse, I simply use boolean success = jsonResponse.getBoolean("success"); . Now, I am required to use Retrofit library.
I know that the response is in GSON format. That's why I'm having a hard time figuring out how to deal with the $response["success"] in my php file.
I tried this:
   call.enqueue(new Callback<User_Account_Model>() {
        @Override
        public void onResponse(Call<User_Account_Model> call, Response<User_Account_Model> response) {

            try {
                JSONObject jsonResponse = new JSONObject(new Gson().toJson(response));
                boolean success = jsonResponse.getBoolean("success");
                Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }

but what's inside the try and catch seems not to be executed. No Toast messages showing. Is my method correct and just missing something or it's completely wrong?

A: Add key in User_Account_Model for success like
public class User_Account_Model{
    @Expose
    private boolean success;

    // Add Getter and setter for **success**
}

Now in onResponse method add like
try {
    String json =response.body().string();
    JSONObject jsonResponse = new JSONObject(json);
    boolean success = jsonResponse.getBoolean("success");
    Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
    e.printStackTrace();
}

A: Make a Class with only one boolean value
public class MyResponse{
  @SerializedName("success")
  private boolean success;

  public boolean getSuccess(){
   return success;
  }
  public void setSuccess(boolean _success){
   success = _success
  }

}

Use this class in enqueue method.
   call.enqueue(new Callback<MyResponse>() {
    @Override
    public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {

        try {
              int statusCode = response.code();
              Log.d("Response Code: ", "status Code: " + statusCode);
              if (response.isSuccessful()){
                MyResponse mResponse = response.body();
              }
        } catch (JSONException e) {
            e.printStackTrace();
        }

If you response only contain one node "success" then it will work.


text:
Q: How to share gradients and variables in Adam optimizer when using bucketing in Tensorflow? All,
I used bucketing-like technology for seq2seq task:
# For different length in encoder and decoder
model_map = {}
for i in encoder_shape:
    for j in decoder_shape:
        with variable_scope.variable_scope(variable_scope.get_variable_scope(),
                                 reuse=True if tt > 0 else None):
            model = Seq2SeqModel()
            model.build(encoder[:i], decoder[:j])
            model_map[i*100+j] = model

And get shared model's parameters:
for t in tf.all_variables():
    print t.name, t.get_shape()

Print:
embedding_attention_seq2seq/RNN/EmbeddingWrapper/embedding:0 (50000, 256)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Matrix:0 (1056, 1600)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Bias:0 (1600,)

Model's optimizer is like below:
#every model have an optimizer
params = tf.trainable_variables()
opt = tf.train.AdamOptimizer(1e-3)
gradients = tf.gradients(self.loss, params)
self.optimizer = opt.apply_gradients(zip(gradients, params))

But I find that the optimizers don't share variable:
embedding_attention_seq2seq/RNN/EmbeddingWrapper/embedding/Adam:0 (50000, 256)
embedding_attention_seq2seq/RNN/EmbeddingWrapper/embedding/Adam_1:0 (50000, 256)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Matrix/Adam:0 (1056, 1600)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Matrix/Adam_1:0 (1056, 1600)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Bias/Adam:0 (1600,)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Bias/Adam_1:0 (1600,)
embedding_attention_seq2seq/RNN/EmbeddingWrapper/embedding/Adam_2:0 (50000, 256)
embedding_attention_seq2seq/RNN/EmbeddingWrapper/embedding/Adam_3:0 (50000, 256)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Matrix/Adam_2:0 (1056, 1600)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Matrix/Adam_3:0 (1056, 1600)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Bias/Adam_2:0 (1600,)
embedding_attention_seq2seq/RNN/MultiRNNCell/Cell0/GRUCell/Gates/Linear/Bias/Adam_3:0 (1600,)

With the growth of the number of buckets, the GPU memory will grow too. And meanwhile I get a larger model in tf.train.Saver.save().
So is it possible to share gradient in bucketing in tensorflow?

A: I believe sharing a single optimizer instance across all your models will do the thing you want.


text:
Q: Does "give up" in this sentence mean quitting smoking? I have researched the exact meaning of give up as in dictionaries.
But give up in the sentence below seems to have no object words, which means it is used as an intransitive phrasal verb.

We surveyed 500 smokers and found that over three quarters would like to give up.

And in the Macmillan dictionary as in the answer below which Mike added the link in, the intransitive version of give up means to stop doing something that you are trying hard to do, which seems to be inappropriate in this case. And also in Oxford dictionaries there are similar explanations regarding give up.
So I wonder if, also in this case, "give up" can mean quitting smoking.

A: In this case, Smokers is the object. The only thing specified about these people who were surveyed is that they smoked, thus 'give up' refers to smoking.  The sentence could be written

We surveyed 500 smokers and found that over three quarters would like to give up smoking

and be perfectly correct, but also redundant and repetitive. The use of smokers implies that give up refers to smoking. Other examples:

Only one in twenty Londoners said they wanted to move away.
We invited bipedal aliens to try chairs built for those with more legs.
Of those who eat chocolate, only a minority prefer the dark kind.

In each case, it's the earlier object that implies the later.

A: http://www.macmillandictionary.com/dictionary/british/give-up
give up: [TRANSITIVE] to stop doing something that you do regularly.

*

*His wife finally persuaded him to give up smoking.

*Giving up his job was the last thing we expected him to do.

So, in short, yes, 'give up' in this context means to quit smoking.


text:
Q: memory issue with a NSMutableString Im having problems filtering an array using a predicate. My code is this one:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
NSString *filename=[NSString stringWithFormat:@"%@/%lld-%@.jpg",[paths objectAtIndex:0],[TRIP surrogateKey], ms];

NSArray *dirContents = [fm contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error];
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"SELF beginsWith %lld-%@",[TRIP surrogateKey], ms];
NSArray *registros=[dirContents filteredArrayUsingPredicate:fltr];

in the debug session i found that i have a problem performing the last line of the code (NSArray *registros=[dirContents filteredArrayUsingPredicate:fltr]) and it gives me the following error:
-[__NSCFString objCType]: unrecognized selector sent to instance 0x7e67200 2013-02-01 16:37:59.132 GastosApp[4462:11303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objCType]: unrecognized selector sent to instance 0x7e67200'

In the debug section i saw that the memory 0x7e67200 is occupied by the ms variable which is  declared:
NSMutableString *ms = [[NSMutableString new] autorelease];

Does anyone see any mistake?
Thanks and regards

A: May be error because NSPredicate make automatic quotation for format variables like %@.
For example, this:
[NSPredicate
    predicateWithFormat:@"SELF like[c] %@*%@", prefix, suffix];

Will be as: SELF LIKE[c] "prefix" * "suffix"
Right way:
[NSPredicate
    predicateWithFormat:@"SELF like[c] %@",
    [[prefix stringByAppendingString:@"*"] stringByAppendingString:suffix]];

Which give us a correct result: SELF LIKE[c] "prefix*suffix"


text:
Q: Не могу читать с файла в android В моем проекте имеются классы: MainActivity, DAO, Question и 1 layout -  activity_main. В классе DAO я считываю с файла situations.txt и передаю данные в Question. Потом в MainActivity я меняю текст одного TextView и двух кнопок на те, что лежат в соответствующих переменных в Question. Дебаг показал что ошибка(приложение вылетает) происходит на том месте, где меняется текст кнопок и TextView. Также в массиве arr с данными из txt ничего нет. Отсюда понятно что считывания не происходит. Также ошибка происходит при объявлении txt файла.
Код MainActivity:
public class MainActivity extends AppCompatActivity {
TextView situation;
Button button1;
Button button2;
Question q;
DAO dao;
ArrayList<Question> arr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    situation = (TextView) findViewById(R.id.situation);
    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    dao = new DAO(this);
    //вылет приложения после строк выше
    arr = dao.getAll();
    q = arr.get(0);
    situation.setText(q.text);
    button1.setText(q.button1);
    button2.setText(q.button2);
}}

Код DAO:
public class DAO {
Context context;
public DAO(Context context) {
    this.context = context;
}
public ArrayList<Question> getAll() {
    ArrayList<Question> array = new ArrayList<Question>();
    AssetManager am = context.getAssets();
    try {
        InputStream is = am.open("situations.txt");
        //сверху выдает ошибку
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line, "$");
            while (st.hasMoreTokens()) {
                Question q = new Question();
                q.text = st.nextToken();
                q.button1 = st.nextToken();
                q.button2 = st.nextToken();
                q.b1 = Integer.parseInt(st.nextToken());
                q.b2 = Integer.parseInt(st.nextToken());
                q.life = Boolean.parseBoolean(st.nextToken());
                array.add(q);
                Log.v("a", "read");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return array;
}}

Situation.txt:
ttt$ff$ff$1$2$true
hh$6h$h8$1$2$true

Поля Question:
public class Question {
String text;
String button1;
String button2;
int b1;
int b2;
boolean life;}

XML:
<TextView
    android:id="@+id/situation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Situation"
    android:layout_marginRight="10dp"
    android:layout_marginLeft="10dp"
    android:gravity="center"
    android:textSize="20sp"
    android:layout_marginTop="20dp"
    android:textColor="#ffffff"/>

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

<Button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="button2" />

A: Полностью повторил ваш код - в Genymotion ошибка не воспроизвелась, обе строки из файла читает корректно - вероятно файл у вас лежит не в assets? Обратите внимание на структуру файлов на скриншотах:


text:
Q: Kendo Ui Grid Date time Convertion Issue I'm Ussing Kendo Grdi with Jquery. That grid has DateTime column. Data in that column shows like "/Date(1377196200000)/" . Help me to arrange this to proper format.
this is script of my grid;
function LoadGridView() {
var dataSource = GetDataSource();

$("#batchgrid").kendoGrid({
    dataSource: dataSource,
    editable: "inline",
    selectable: "row",
    toolbar: ["create"],
    autobind: true,
    reorderable: true,
    pageable: {
        refresh: true,
        pageSizes: [5, 10, 20, 50, 100]
    },
    sortable: {
        mode: "multiple"
    },
    sort: { field: "PrjNm", dir: "asc" },
    groupable: {
        messages: {
            empty: "Drop columns here"
        }
    },
    columnMenu: {
        sortable: true,
        filterable: true,
        messages: {
            columns: "Hide/Show Columns",
            filter: "Apply filter",
            sortAscending: "Sort (asc)",
            sortDescending: "Sort (desc)"
        }
    },
    resizable: true,
    dataBinding: function () {
        record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
    },
    filterable: {
        messages: {
            and: "And",
            or: "Or",
            filter: "Apply filter",
            clear: "Clear filter",
            info: "Filter by"
        },
        extra: false, //do not show extra filters
        operators: { // redefine the string operators
            string: {
                contains: "Contains",
                doesnotcontain: "Doesn't contain",
                startswith: "Starts With",
                endswith: "Ends"
            },
            number: {
                eq: "Is Equal To",
                neq: "Not equal to",
                gte: "Greater than or equal to",
                lte: "Less than or equal to",
                gt: "Greater than",
                lt: "Less than"
            }
        }
    },
    navigatable: true,
    columns: [
                    { title: "No", template: "#= ++record #", width: 45 },
                    { field: "ItemCode", title: "Item Code", width: "150px" },
                    { field: "ItemName", title: "Item Name", format: "{0:c}", width: "300px" },
                    { field: "PreviousDate", title: "Previous Date", type: "date", format: "{0:dd/MM/yyyy}" },
                    { field: "PreviousValue", title: "Previous %", width: "110px", format: "{0:2}" },
                    { field: "Value", t`enter code here`itle: "%", width: "150px", format: "{0:2}" },
    { command: ["edit"], title: " ", width: "175px" }
    ]
});

}

A: Make sure your DataSource defines the date field type correctly (as date) in the model as is shown here :
model: {
    fields: {
        PreviousDate: { type: "date" },
            }
       }


text:
Q: undefined method `should_receive' for subject I have class similar to this:
class SomeClass
  attr_accessor :numbers

  # (...)

  def external_method
    numbers.each do |variant, duration|
      duration.each do |duration, value|
        internal_method(variant, duration, value)
      end
    end
  end

  def internal_method(variant, duration, value)
    # do something with these arguments
  end

end

And I try to check, If external_method calls internal_method with proper arguments.
describe("#external_method") do
  let!(:numbers) do
    {
      1 => {
        1 => 0.1,
        2 => 0.2
      },
      2 => {
        1 => 0.3,
        2 => 0.4
      }
    }
  end

  it "should call internal method for all values" do
    value = 0
    (1..2).each do |variant|
      (1..2).each do |duration|
        value += 0.1
        subject.should_receive(:internal_method).with(variant, duration, value).once
      end
    end
    subject.external_method
  end
end

What I get is:
 Failure/Error: subject.should_receive(:internal_method).with(variant, duration, value)
 NoMethodError:
   undefined method `should_receive' for #<SomeClass:0x007fabb2321ff8>

What am I doing wrong?


text:
Q: how to add multiple "actual" element objects in JQuery selector I am working on Google Apps Script and using JQuery. I want to put multiple actual elements in the JQuery selector. I want to put actual elements in the selector.
I want:
$(kojiNameElem, tankaElem, suryoElem, unitElem)

not like(it works though):
$(".kojiName, .tanka, .suryo, .unit")

Please see this code followed:
var kojiNameElem = $("#koji_"+koji_id).find(".kojiName");
  var tankaElem = $("#koji_"+koji_id).find(".tanka");
  var suryoElem = $("#koji_"+koji_id).find(".suryo");
  var unitElem = $("#koji_"+koji_id).find(".unit");

  $(kojiNameElem, tankaElem, suryoElem, unitElem).on("focusin",function(e) {
    console.log("focusin");
  });

It works only on kojiNameElem. The other elements don't.
I know it works with one single element in the JQuery selector as below.
$(kojiNameElem).on("focusin",function(e) {
        console.log("focusin");
      });

Could you help me please?

A: You can do it like

var koji_id=1;
  var kojiNameElem = $("#koji_"+koji_id).find(".kojiName");
  var tankaElem = $("#koji_"+koji_id).find(".tanka");
  var suryoElem = $("#koji_"+koji_id).find(".suryo");
  var unitElem = $("#koji_"+koji_id).find(".unit");

  $("#koji_"+koji_id).on("click", '.kojiName,.tanka,.suryo,.unit',function(e) {
    console.log($(this).text());
  });

  kojiName
  tanka
  suryo
  unit

You can also use add method

  var koji_id=1
  var koji= $("#koji_"+koji_id);
  var kojiNameElem = koji.find(".kojiName");
  var tankaElem = koji.find(".tanka");
  var suryoElem = koji.find(".suryo");
  var unitElem = koji.find(".unit");

  $(kojiNameElem).add(tankaElem).add(suryoElem).add(unitElem).on("click",function(e) {
    console.log($(this).text());
  });

  kojiName
  tanka
  suryo
  unit

A: There's no way to combine multiple jquery objects in a single selector - the method to do this is .add()
Demonstration:

var a = $("#a");
var b = $("#b");
var c = $("#c");

var arr = a.add(b).add(c).map((i, e)=>$(e).text()).toArray();
console.log(arr)

a

b

c


text:
Q: biff exception: unrecognizedOLE Just trying to read from an ordinary excel file which I craeted using microsoft excel starter 2010 and saved as an excel 97-2003 file because I originally thought the exception was due to the file format. Apparently this exception means there is something embedded in the file that cannot be read, but for the life of me I dont know how or why that is. It's just a simple excel file I typed out myself. The stacktrace is as follows:
[CDATA[jxl.read.biff.BiffException: Unable to recognize OLE stream
at jxl.read.biff.CompoundFile.<init>(CompoundFile.java:116)
at jxl.read.biff.File.<init>(File.java:127)
at jxl.Workbook.getWorkbook(Workbook.java:221)
at jxl.Workbook.getWorkbook(Workbook.java:198)
at test.ExcelClass.updateTestResultsSpreadsheet(ExcelClass.java:1707)
at test.Internal_TestSuite.afterSuite(Internal_Virgin_TestSuite.java:846)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:543)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:212)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:309)
at org.testng.SuiteRunner.run(SuiteRunner.java:241)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1169)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1094)
at org.testng.TestNG.run(TestNG.java:1006)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:107)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:199)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:170)
]]>

I have used similar files without this exception being thrown. Any ideas?? Thanks in advance!
UPDATE: I solved the problem by removing another MS excel starter 2010 (.xlsx) file I was using elsewhere in my testNG class and making it a .xls file. It appears the stacktrace was not pointing at the correct location of the problem? Or at least it didn't change when I removed the first file? Anyway it's fixed, the JExcel api isn't compatible with other excel formats.


text:
Q: Crystal Reports, Cross tab I am not getting correct results on Google as I am not able to put correct keywords for my query. Same applies for Stackoverflow too. So I am putting in my question.
In report footer of crystal reports, I am using cross tab. I am expecting output as shown below,
             | Count of units    |      Rent
-------------|-------------------|----------------------------------------------
Unit Type A  |      10           |     sum of rent of all units under unit type A
--------------------------------------------------------------------------------
Unit Type B  |      20           |     sum of rent of all units under unit type B
--------------------------------------------------------------------------------

So far I was able to achieve as shown below but that is not helping,
             |Count of units       |   Rent
----------------------------------------------------------
Unit Type A  |      10             |  sum of rent of UT A
             | sum of rent of UT A |  10
----------------------------------------------------------
Unit Type B  |      20             |  sum of rent of UT B
             | sum of rent of UT B |  20
----------------------------------------------------------

Is it possible to achieve what I am expecting through cross-tab? If not, any other solutions?
Thanks in advance for all your Help!

A: To answer your question: Yes, it is possible to achieve what you are trying to do. The easiest way is to have one row (unit type) and two summarized fields (count of units, sum of rent. No Columns. You will need to customize the label.
Hope that helps,
Chris


text:
Q: Obj-C has @available. Swift has #available. What can I use in C/C++? If your code requires a feature that is only available in macOS 10.12 or newer, but you want your code to also deploy to earlier system versions, you can use @available in Objective-C:
if (@available(macOS 10.12, *)) {
    // Code that requires 10.12 APIs
} else {
    // Code that doesn't require 10.12 APIs
}

You can do the same thing in Swift using #available:
if #available(macOS 10.12, *) {
    // Code that requires 10.12 APIs
} else {
    // Code that doesn't require 10.12 APIs
}

But what can you use if you write C or C++ code?

A: In C and C++ you can use the Clang compiler extension __builtin_available:
if (__builtin_available(macOS 10.12, *)) {
    // Code that requires 10.12 APIs
} else {
    // Code that doesn't require 10.12 APIs
}

That is if you have at least Clang 5 available (Xcode 5.0 or newer).
Keep in mind that you will have to set a deployment target to make this feature work correctly (e.g. -mmacosx-version-min=10.9). The reason is that the linker requires this information to decide when to perform weak linking. Setting the deployment target to 10.9 for example tells the linker that if your code is using any symbols that were not already available in 10.9, these symbols must be weakly linked.
Normally an executable or library will try to resolve all referenced symbols at load and fail to load if any such symbol cannot be found. However, when a symbol is weakly linked, being unable to resolve a symbol will not cause loading to fail, instead any reference to that symbol becomes a NULL reference at runtime. Needless to say, if you try to call a function that was weakly linked and has not been found at load, your app will crash (you are trying to call NULL as a function). And that's where __builtin_available comes to the rescue.
if (__builtin_available(macOS 10.12, *)) {
    // ...
} else {
    // Symbols only available in 10.12 or newer are all NULL when
    // you reach this code block but you wouldn't use any of them
    // in this code block, would you? So, no problem.
}

If you don't use -mmacosx-version-min, the __builtin_available construct will still work correctly, yet as the linker doesn't know what system you are targeting, it assumes the current system and won't perform any weak linking. If you then try to run your app on an earlier system version, some symbols won't be found and your app even refuses to load, despite the fact that it would have alternative code paths for that system.


text:
Q: Bootstrap Nav pills not working as spected using flexbox justify-content:space-between property I am trying to use Bootstrap' nav-pills components with flexbox's  justify-content:space-between:
here is what I get as result:

while i expected this:

Here is the code: http://jsbin.com/qihekuteze

A: This is happening because of Bootstrap's clearfix. There are ::before and ::after psuedo elements being added that are also counting as children of the flexbox.
If you add:
.nav::before,
.nav::after {
  display: none;
}

And make sure it's still justify-content: space-between;, then it will fix it.
New bin: http://jsbin.com/zipigociqi/1/

A: So after a fair amount of fiddling the issue is content: " " that bootstrap applies to :before and :after styles to the nav classes. So your css should be:
.nav::after,
.nav::before {
    display: none;
}


text:
Q: Paginate by most recent post with kaminari I'm using the rails gem kaminari (https://github.com/amatsuda/kaminari) in order to paginate my posts database. Currently I have the code @posts = Post.order('id').page(params[:page]).per(5) in my controller, but this orders the pages from earliest to most recent. How do I reverse this and order from most recent to earliest?

A: in your model you can do:
default_scope order("created_at DESC")

or
default_scope order("created_at ASC")

A: def index
    @all = Model.all
    @all = Model.order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page])
end

def sort_column
    Model.column_names.include?(params[:sort]) ? params[:sort] : "updated_at"
end

def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "DESC/ASC"
end


text:
Q: Bigquery Time as duration, convert to second i have a problem with time from string
overall, my goal is want to get how many seconds from duration AS string that containing HH:MM:SS
00:01:00 -> 60
00:02:30 -> 150
01:00:00 -> 3600

my query is like this
TIME_DIFF(CAST(duration AS TIME), '00:00:00', SECOND)

However, query above does not work with duration that more than 24:00:00
is there any different solution to get

A: I assume the duration column is a string representing time in following format HHHH:MM:SS where HHHH can be any value of hours even above 24. If this is a case  - consider below solution
select duration,
  3600 * cast(regexp_extract(duration, r'^\d*') as int64) +
  time_diff(cast(regexp_replace(duration, r'^\d*', '00') as time), '00:00:00', second) as seconds
from `project.dataset.table`

below is example of output

A: If you want to split "time" values longer than 24 hours, then I must assume that your source data is a string and not a time.  In BigQuery, time values must be less than 24 hours.
So, use string operations:
select (cast(split(hhmmss, ':')[ordinal(1)] as int64) * 60 * 60 +
        cast(split(hhmmss, ':')[ordinal(2)] as int64) * 60 +
        cast(split(hhmmss, ':')[ordinal(3)] as int64)
       ) as seconds
from (select '00:01:00' as hhmmss union all
      select '00:02:30' union all
      select '01:00:00') x

A: You can try out an alternative way to parse TIMESTAMP DATA:-
WITH DATA AS(
SELECT '2019-05-03T00:01:00' AS F_DATE
UNION ALL
SELECT '2019-05-03T00:02:30'
UNION ALL
SELECT '2019-05-03T01:00:30'
)
select F_DATE, EXTRACT(HOUR FROM CAST( F_DATE AS TIMESTAMP))  * 60 *60 + EXTRACT(MINUTE FROM CAST(F_DATE AS TIMESTAMP)) * 60 + EXTRACT(SECOND FROM CAST(F_DATE AS TIMESTAMP)) AS DATE_SEC FROM DATA


text:
Q: Is it considered a bad coding practice to use, at the same time, css commands at the .css file and inline css commands at the .html file? I'm new to web design and I'm realizing that it's possible to use the html just for the page structure and the css for the page design. Is it ok to use inline commands like style="display: block" or style="background-image: url(image.com), in the html file? Or is it considered a bad practice?

A: Using CSS within a <style> tag or importing in from a .css file provides all of your selectors with a specificity range that will be overridden by any CSS provided through the style attribute.
As a general rule you want to try to keep as much CSS as possible within your .css files or <style> tags.
I try to keep over 90% of all CSS in files and I only put css into the style attribute when I am changing specific values that are difficult to code in a CSS file. Like rotation angle, top and left positions of things that are drug around the screen, etc.

A: It's best to insert css in the css file, because as a developer, you'll have a lot of code in your html file and if you add inline css then it could get messy. Adding css in the css file is easier to read and easier to edit.

A: Keeping all your css inside a .css file will give you much cleaner html file and enable you to make changes to your styling much easier as everything is in one place.
There will be times where it is much easier to add an inline style attribute to an element but even this can be avoided with couple extra lines of code on the css side to make your html look as clean as possible.

A: I think that anyway that helps you achieve your style goal is ok to use as long as it works for you.
That said, I usually try to keep all the styles that affect the site in general in a .css file and link it in globally to the site pages.
In some cases, there may be a page or two that need styles that are not needed by the rest of the site, therefore I add the <style> tag with the style rules in those few pages.
When an inline element in the html needs a special distinction using a style not defined in the locations mentioned above, I added it there inline with the style attribute. In these cases I have to make a note that, those elements will not change when the other css changes throughout the site.
Of course there are other things like the !important directive, etc, that can affect or override the inline style.
As mention by others in this post, there are other considerations to take into account, on where to place your css for individual reasons deemed by the designer.


text:
Q: Does it "rile" you? I live in India and am a Doctorate (in Maths, not English). A few years back, my social circle consisted purely of Mathematicians/Physicists. Just about time, cause I happened to join a trekking club mainly of non-academics but successful professionals nevertheless.
My language probably reflected my limited social circle and I drew wide eyes for my "pretentious" jargon, which left me bewildered. Not any more ... I have moved far away from that cloistered group (cabal?) but I still cause mirth sometimes.
I want to talk about two of my conversations with few "first contacts".

*

*In a very casual chat, I used the word "rile". I instantly got a feedback from my friend that it was the first time he had heard someone use this word in real world. My friend is a much traveled globe trotter, someone who would be described as a "world professional". He probably expected me to use "upset" or "annoy".

*You probably know that calling India multi-lingual is an understatement. As a matter of routine, I hear no less than four languages each and everyday. And it is not obvious from first acquaintance/appearance about anybody's real linguistic affiliation (my mother tongue is Hindi). English is a common lingua franca (as is Hindi). So I asked this (in English) to a group of 15 new acquaintances - "could we have our linguistic subscription as a part of our introductions please?" ... Yes I really said it! No one was sure of what I said. They looked at me as a sort of zoo specimen.
What would be your reactions?


text:
Q: IntelliJ IDEA, PyCharm, PHPStorm, etc. - cursor / caret stuck, jumps back to previous position, sticks to scroll i am really annoyed by weird caret / cursor behaviour inside IntelliJs editor.
The caret sometimes get stuck at some line at the beginning. If you try to navigate by arrow-keys or something else despite the mouse when this happens, the caret will instantly jump back to the previous position. Only way to set it free is to click with the mouse somewhere else in the editor window.

In addition to it, if the caret is stuck and you scroll, the caret moves the same amount of lines you scroll in the editor and will select all text on its way.

So the question is: what can i do about it?
env: macOS 10.12.4, recent JetBrains IDEs (tried several versions)


text:
Q: Distribute 32 and 64 bit compiled applications Most of the software you can download over the internet for free, provide both 32 bit and 64 bit versions. But since most of them do not require to address so much memory, what is the advantage to this double distribution, since the moment 32 bit application runs perfectly on 64 bit systems? Do I miss something?
thank you

A: Even though there might be no technical reason to have a 64-bit version right now 32-bit apps support will slowly decline and so it's time to start porting. If they just refuse to have a 64-bit version until it is absolutely required they will have to port it very fast (not only change the code but also test that everything works which is far from trivial and far from fast). So it's kind of a way to have a slow transition - they already ported the code and now they are kind of testing it so that when 32-bit code can no longer run they are fully prepared.


text:
Q: Font Awesome Icons in DropDownList Items I want a select box with the font awesome icon and the name of the icon.
I build my ListItems for the DropDownList in Code behind dynamically and want to show the icon with the unicode.
Here is my output:

The decleration of the DropDownList looks like this:
 <asp:DropDownList ID="ddl_Icons" CssClass="form-control select2 fontawesomeselect" runat="server"></asp:DropDownList>

The font-family should be correct but there is still no icon displayed.
Any tips how I can display the icons?
I'm using select2 and have made two CSS classes containing the following code:
<style type="text/css">
    .fontawesomeselect {
        font-family: 'FontAwesome', 'Arial';
    }

    .select2-selection__rendered{
        font-family: 'FontAwesome', 'Arial';
    }
</style>

A: I did a workaround with the awesome Bootstrap Iconpicker plugin.
Simply add an button (with popover from the right side) to your page:
<button id="btn_iconchoser" class="btn btn-default"data-iconset="fontawesome" data-icon="glyphicon-arrow-right" data-search-text="Choose Icon" data-placement="right" role="iconpicker"></button>

Import the following files:
Header:
<!-- Bootstrap Iconpicker -->
<link rel="stylesheet" href="/plugins/bootstrap-iconpicker-1.7.0/bootstrap-iconpicker/css/bootstrap-iconpicker.min.css"/>

Footer:
<!-- Bootstrap-Iconpicker Iconset for Font Awesome -->
<script type="text/javascript" src="/plugins/bootstrap-iconpicker-1.7.0/bootstrap-iconpicker/js/iconset/iconset-fontawesome-4.2.0.min.js"></script>
<!-- Bootstrap-Iconpicker -->
<script type="text/javascript" src="/plugins/bootstrap-iconpicker-1.7.0/bootstrap-iconpicker/js/bootstrap-iconpicker.min.js"></script>

In my case I'm using the font awesome iconset (v4.2) but you can also use one of the following iconsets:

*

*glyphicon

*ionicon

*fontawesome

*weathericon

*mapicon

*octicon

*typicon

*elusiveicon

Maybe this helps somebody with a similar problem.


text:
Q: Second item in listview doesn't render the first time properly So I have this problem that I have a listview and when I add the first item it renders, but the second one doesn't render but the panel the listview is on grows as if it did. Afterwards if a third item is added both the second and the third render. After that, each new item added renders instantly. This problem is only with the second item.
XAML:
<ListView Name="DownloadList" Background="WhiteSmoke" PreviewMouseLeftButtonUp="DownloadList_PreviewMouseLeftButtonUp" Width="649" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="140" Header="Name" DisplayMemberBinding="{Binding Name}"/>
            <GridViewColumn Width="80" Header="Status" DisplayMemberBinding="{Binding Status}"/>
            <GridViewColumn Width="60" Header="Size" DisplayMemberBinding="{Binding FormattedSize}"/>
            <GridViewColumn Width="70" Header="Speed" DisplayMemberBinding="{Binding FormattedSpeed}"/>
            <GridViewColumn Width="170" Header="Progress">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                            <Grid>
                                <ProgressBar Name ="dlPrgrs" Height ="20" Width="150" Maximum="100" Value="{Binding FormattedProgress}" Foreground="{Binding ForColor}"/>
                                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding ElementName=dlPrgrs, Path=Value, StringFormat={}{0:0}%}"/>
                            </Grid>
                        </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Width="65" Header="Time Left" DisplayMemberBinding="{Binding FormattedTime}"/>
            <GridViewColumn Width="60" Header="Peers" DisplayMemberBinding="{Binding Peers}"/>
         </GridView>
     </ListView.View>
</ListView>

behind code
list creation and binding:
List<FileDownload> wpfDownloads = new List<FileDownload>();
DownloadList.ItemsSource = wpfDownloads;

adding new item:
wpfDownloads.Add(download);

thanks

A: Just use ObservableCollection<FileDownload> instead of List<FileDownload>.
Cause ObservableCollection<T> has implemented INotifyCollectionChanged interface.
As MSDN says:

INotifyCollectionChanged notifies listeners of dynamic changes, such
  as when an item is added and removed or the whole list is cleared.

Simple advice about your UI:
I suggest you to create you resizable XAML, not static. I mean it is bad:
<Grid>
   <ListView HorizontalAlignment="Left" Margin="10">
       ...The code omitted for the brevity...
   </ListView>
   <Button Margin="50" Name="btn_add" Click="btn_add_Click" Content="Add new item"/>
</Grid>

However, it is better and this UI(XAML) is resizable:
<Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="5*">
      </RowDefinition>
    </Grid.RowDefinitions>
    <ListView HorizontalAlignment="Left">
       ...The code omitted for the brevity...
    </ListView>
    <Button Grid.Row="1" Name="btn_add" Click="btn_add_Click" Content="Add new item"/>
</Grid>


text:
Q: ReactNative-Expo: Dropped frames with brand new app Brand new Expo App is showing that some frames are being dropped, is this normal/expected behavior? (It doesn't feel like performance is hindered).
I am running this on actual physical device (Android OnePlus8, Snapdragon 865 chip).

A: This is absolutely normal.
If you app is faster/smotther your app will drop less frames. But also keep in mind that, if you are emulating the phone on a slow computer then you will notice much more frames dropped due to lower performance.
Same as all of our physical devices have performance differences. So, its normal that some frames will be dropped.
I am running this brand new expo project on actual physical device (Android A20s)


text:
Q: Run Through A List Then Paste Result To Its Next Cell I was able to create a macro wherein it would go through all the list of websites in column J starting at row 2 (header at row 1). Get the information that I want from each website, then display them in column K, which is right next to the websites where the information was taken from.
The only problem is that, I cant make the macro go to each of the websites.
I dont know what is wrong with the code.
Sub CommandButton1_Click()
    Dim ie As Object
    Dim lastrow As Integer
    Dim i As Integer
    Dim myURL As String
    Dim sdd As String
    Dim add As Variant
    Dim html As Object
    Dim mylinks As Object
    Dim mylink As Object
    Dim result As String

    ' Create InternetExplorer Object
    Set ie = CreateObject("InternetExplorer.Application")

    lastrow = Sheet1.Cells(Rows.Count, "J").End(xlUp).Row
    For i = 2 To lastrow
    myURL = Sheet1.Cells(i, "J").Value

    ' Hide InternetExplorer
    ie.Visible = False

    ' URL to get data from
    ie.navigate myURL

    ' Loop until page fully loads
    Do While ie.readystate <> READYSTATE_COMPLETE
    Loop

    ' Information i want to get from the URLs
    sdd = ie.document.getelementsbyclassname("timeline-text")(0).innerText

    ' Format the result
    add = Split(sdd, "$")
    Range("K3") = add(1)

    ' Close InternetExplorer
    ie.Quit

    'Return to Normal?
    ie.Visible = True
    End
    Next
    ' Clean up
    Set ie = Nothing

    Application.StatusBar = ""

End Sub

$85,100 is the information I want to get from one of the URLs.
Est.
$85,100

A: Don't quit IE until you've completed the loop. Simply navigate to the next URL and record the new page's information on the same row as the URL was collected from.
Sub CommandButton1_Click()

    Dim lastrow As Long, i As Long
    Dim sdd As String, myURL As String, result As String
    Dim add As Variant
    Dim ie As Object, html As Object, mylinks As Object, mylink As Object

    ' Create InternetExplorer Object
    Set ie = CreateObject("InternetExplorer.Application")
    ' Hide InternetExplorer
    ie.Visible = False

    lastrow = Sheet1.Cells(Rows.Count, "J").End(xlUp).Row
    For i = 2 To lastrow

        'collect next web page url
        myURL = Sheet1.Cells(i, "J").Value

        ' URL to get data from
        ie.navigate myURL

        ' Loop until page fully loads
        Do While ie.readystate <> READYSTATE_COMPLETE
            'allow other process through the message queue
            DoEvents
        Loop

        ' Information i want to get from the URLs
        sdd = ie.document.getelementsbyclassname("timeline-text")(0).innerText

        ' Format the result
        add = Split(sdd, "$")
        Sheet1.Cells(i, "K") = add(1)

    Next i

    'Return to Normal?
    ie.Visible = True
    ' Close InternetExplorer
    ie.Quit
    ' Clean up
    Set ie = Nothing

    Application.StatusBar = ""

End Sub

I've also added DoEvents within your page load wait loop. This allows other processes to execute instead of tying up resources in the single threaded VBA process.

A: there is something you have to take note of while programming. Always try to echo a visible result.
Do this before the loop after the lastrow
msgbox lastrow
E.g in between the for loop, do something like
msgbox sdd
You should be able to get where the errors lie.
I hope this helps.


text:
Q: How to check inside layout if single post is being displayed? I'm trying to render back button in layout if single post is being displayed. I've tried to pass pageContext property on create page in gatsby-node.js:
    result.data.allMarkdownRemark.edges.forEach(({ node }) => {
      createPage({
        path: node.fields.slug,
        component: blogPostTemplate,
        context: {singlePost:true}, // additional data can be passed via context
      })
    })

Couldn't access this property anyhow in my layout:
import React from "react"
import PropTypes from "prop-types"
import { StaticQuery, graphql } from "gatsby"

import Header from "./header"
import "./layout.css"

const Layout = ({ children }) => (
  <StaticQuery
    query={graphql`
      query SiteTitleQuery {
        site {
          siteMetadata {
            title
          }
        }
      }
    `}
    render={data => (
      <>

        <div
          style={{
            margin: `0 auto`,
            maxWidth: 960,
            padding: `0px 1.0875rem 1.45rem`,
            paddingTop: 50,
          }}
        >
          {children}

            © {new Date().getFullYear()}, Built with Gatsby
            {
              pageContext.singlePost
              `<a href="/">Back to all</a>`
             }

      </>
    )}
  />
)

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

I still don't know to much also about conditional rendering in jsx,  but I thought I could do this such way.
How to check if this is single post, pass the pageContext (where to find it) or is there a better way?

A: Your conditional rendering syntax isn't quite right. In JSX, anything inside curly braces is just a regular JavaScript expression, so you want something like this:
{ pageContext.singlePost && Back to all }

A: pageContext will be passed as a props to your blogPostTemplate.
// example

class BlogPostTemplate extends React.Component {
  render() {
    console.log(this.props.pageContext) // your page context
    return (...)
  }
}

If you are using layout component in your blog post template, you'd have to pass context to it explicitly.
// example

class BlogPostTemplate extends React.Component {
  render() {
    return () {
      <Layout singlePost={this.props.pageContext.singlePost}> ... </Layout>
    }
  }
}

As the @TomJardine-McNamara's answer pointed out, your conditional doesn't look right either. Follow up the example above, you can access singlePost as a props in your Layout component.
const Layout = ({ children, singlePost }) => ( // extract `singlePost` from props
  ...
  { singlePost &&  }
)


text:
Q: Unity 3D. Moving along z axis does not set z value to 0 I just have an object that moves parallel to x axis or z axis, but when it moves along z axis, the z coordinates never is 0. Even if I set it to 0, it just goes really small like e-06. This does not happen when moving along x axis.
I presume it happens because float is not accurate enough, but the strange thing is, this only happens to z coordinate only when it moves along z axis. It does not happen when it moves parrallel to z axis like z = 1.
Is this a know bug? Anyway to go over this?


text:
Q: What are visible ASCII characters? RFC7230, the new HTTP/1.1 specification, refers to VCHAR as visible ASCII characters. What are those characters specifically? The RFC specification doesn't mention that.
The US-ASCII spec in RFC20 doesn't also mention which characters are visible and which are not.

A: I assume the visible characters are between hex 0x21 and hex 0x7E. If this assumption is correct, space (0x20) wouldn't be included, horizontal tab (0x09) wouldn't be included and DEL (0x7F) wouldn't be included.
This assumption is supported by the following definitions in RFC7230:
 field-value    = *( field-content / obs-fold )
 obs-fold       = CRLF 1*( SP / HTAB )
 field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
 field-vchar    = VCHAR / obs-text
 obs-text       = %x80-FF

This takes space characters separately into account, so that VCHAR doesn't need to include space and horizontal tab.


text:
Q: How can I use the "frog jump" forward of Gael's Greatsword on PC? Gael's Great Sword has two attacks:
1) Weapon Art + light attack (Left button of mouse) = The rolling attack
2) Weapon art + heavy attack (shift + left button of mouse) = The Frog Jump
The problem with the normal Frog Jump is, you move back first, then strike forward.
However, I have seen in some Youtube videos specially PvPSkillz that he uses the frog jump as a gap closer, I think he uses Xbox, so I'm thinking, How can I change the direction of the Frog Jump? A typical frog jump moves backwards first, then forward, PvPSkillz frog jump is forward, forward!

A: I've just successfully tested it, here is my short video. I did it on PC with keyboard and mouse.
How I did it (with all defaults key bindings):

*

*Hold Shift all the time.

*Right mouse click to make first jump.

*Now simultaneously press backwards move (S) and click left mouse to do forward frog jump.

*During jump press forward (W) and then right mouse to attack.

The problem is, that this does not work if you locked your target: when target is locked instead of turning around backwards move will trigger step back. So you need either do entire thing without locking or release target after step 2 and hold target again after step 3. Looks like it will require a lot of practice to perfect this move.


text:
Q: How to obtain an errored.tfstate file from Terraform Cloud? I have a Terraform deployment that gets applied through Circle CI. It seems that when Circle applies it, it errors out, but when I apply manually I'm unable to reproduce the behavior.
The error I get is:
Error: Failed to persist state to backend

The error shown above has prevented Terraform from writing the updated state to the configured backend. To allow for recovery, the state has been written to the file "errored.tfstate" in the current working directory.

Running "terraform apply" again at this point will create a forked state, making it harder to recover.

To retry writing this state, use the following command:
    terraform state push errored.tfstate

If I could see this errored.tfstate file, it would probably help me diagnose the issue. However, can I obtain it from Terraform itself?
Note: I am not asking here why the error is happening - I intend to make a separate question about that. I am only asking where to obtain the errored.tfstate.


text:
Q: What system logs might tell me if a server lost its internet connection? I have a server:
CentOS Linux release 7.3.1611 (Core)
3.10.0-514.2.2.el7.x86_64 #1 SMP Tue Dec 6 23:06:41 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

I think its network connection cutout at one point (its back now). I haven't been able to find anything in /var/log/messages- maybe I just don't know what to look for?
Essesntially I'm looking for two things: If there was a problem with the nic, If the server lost its internet connection.
The second one is obviously harder to figure out (maybe impossible?). Obviously I should have some external monitoring solution, but from an educational perspective where would you look (locally on the host) to solve this mystery?

A: Check the ring kernel buffer (dmesg) - you should see information for network connectivity events.

A: Your kernel logs (the most recent viewable by dmesg, older by journalctl -k or wherever configured in /etc/rsyslog.conf) will probably contain messages if a NIC loses its link. And of course you can easily find what those messages look like by unplugging the cable. Example:
Jan 13 11:16:33 Zia kernel: r8169 0000:07:01.0 lan: link down

Loss of Internet connectivity is harder, and typically you'd set something up to detect this (either external monitoring, or monitoring of outside machines from your machine). It's also not really a binary state—you can have partial Internet connectivity (can reach some hosts, but not all). You can look for clues, though:

*

*messages from NTP in the journal/logs (e.g., about losing peers), or check the NTP peer stats (if enabled).

*messages in journal/logs about failed network connections (e.g., if you had fetchmail running routinely, it'd complain it couldn't connect to your POP3 server)

*VPN connections going down (I get plenty of OpenVPN logs when the Internet connection goes down).

*sudden 0 load on web (etc.) servers. Many servers log all requests received to some server-specific log.

*similarly, if you log system load (load average, run queue, etc.), quick drop to 0 is a clue.

*lack of noise in firewall logs (at least, if you log blocked packets)

*sudden lack of random worm attacks (I get plenty of failed authentication messages from various services I'm running, and not getting any for hours would be a good clue there was no Internet connectivity)

*traffic levels, if you're monitoring (e.g., using Cacti, MRTG, collectd, etc.). If you're not, your ISP probably is—maybe they'd be willing to share?

*if you have other machines that talk to this machine, check those machine's logs. Might have failure messages

*if you offer services to other people, they might have logs.

*if you have a support desk, they probably know (from all the calls they got).

Basically, you're doing detective work: you need to look for clues. Without monitoring, there isn't going to be an teh Interwebs is down log message.


text:
Q: Path connected but not metrizable What are the examples of path connected spaces which are not metric spaces. The only examples I know are sets with indiscrete topology?
Are there such spaces which are not simply connected (the indiscrete space is simply connected)?

A: One can take familiar spaces with different topologies. For example, one could take $\mathbb{C}$ with the Zariski topology (ie cofinite topology). If you recall that metric spaces are always Hausdorff, then this yields an example because $\mathbb{C}$ with the Zariski topology is not Hausdorff (good exercise).

A: A classic example is the long line (and its subspaces the open and closed long rays). It's locally homeomorphic to $(0,1)$, path-connected, and hereditarily normal, so it's a pretty nice space, but it's sequentially compact without being compact, so it's not metrizable.

A: Take any path connected space and take its Cartesian product with uncountably many copies of $\mathbb{R}$. This space is path connected but not metrizable and is homotopy equivalent to the original space, so in particular it can have nontrivial fundamental group.

A: Take countably many disjoint copies of the unit interval, say $I_n=[0,1]\times\{n\}$.
Glue together all points $\langle 0,n \rangle$ into one point, $p$. (Formally take a quotient map, where $\langle 0,n \rangle\sim \langle 0,m \rangle$ for all $n,m$, and take the quotient topology). The result (also known as the non-metric hedgehog) is not first-countable at $p$. But every two points could be connected with a path, which would necessarily go through $p$ if the two points come from different copies of the unit interval.

A: $\pi$-Base is an online database of topological spaces inspired by Steen and Seebach's Counterexamples in Topology. It lists the following twenty-seven path-connected, non-metrizable spaces. You can learn more about any of these spaces by viewing the search result.
Alexandroff Square
Compact Complement Topology
Countable Excluded Point Topology
Countable Particular Point Topology
Deleted Diameter Topology
Deleted Radius Topology
Divisor Topology
Double Origin Topology
Finite Complement Topology on an Uncountable Space
Finite Excluded Point Topology
Finite Particular Point Topology
Half-Disc Topology
Indiscrete Topology
Nested Interval Topology
Niemytzki's Tangent Disc Topology
One Point Compactification Topology
Overlapping Interval Topology
Prime Ideal Topology
Radial Interval Topology
Right Order Topology on $\mathbb{R}$
Sierpinski Space
Simplified Arens Square
Telophase Topology
The Integer Broom
The Long Line
Uncountable Excluded Point Topology
Uncountable Particular Point Topology


text:
Q: Is connected component open? There is a theorem that:A space is locally connected iff each connected components of an open set is open.
But recently I had seen to prove That each connected component is closed. Connected Components are Closed
Then how can the connected component of an open set be open if it is a locally connected space ? It will be contradiction to the statement that connected components is closed.

A: A subset being closed doesn't preclude that subset from being open.  For a simple example, every discrete space is locally connected, and every subset of a discrete space—in particular the singleton sets (which are the connected components)—is both open and closed.


text:
Q: How do I add 1 to a 4 bit wire in Verilog This seems like it would be simple, but I can't find out how to do this anywhere... All I want to do is add 1 to a 4 bit wire.
Overall, I want to count the number of 1's in a 8 bit variable. Let's call this input inA. The output will be outA. Both are defined as wires; inA is 8 bits where outA is 4 bits.
wire[0:7] inA;
wire[0:3] outA;

I can do a for loop to go through the array:
for (i = 0; i <= 7; i = i + 1) begin
    if (inA[i] == 1) begin
       outA <= outA + 1;
    end
end

But this isn't working.
Can someone please help? I am extremely new to Verilog (and VHDL), so I really have no clue what I am doing wrong.

A: There are a few ways to do this, here is one option:
  reg [0:3] ones;
  integer i;
  always @ (inA) begin
    ones = 0;
    for (i = 0; i < 8; i = i + 1) begin
      ones = ones + inA[i];
    end
  end
  assign outA = ones;

Since you haven't provided your full source code (e.g. the context of the for loop), we can only guess what the problem with that is.
Remember though that non-blocking assignments like outA <= outA + 1 will be scheduled to be executed at the end of the always block, such that the last assignment will override all previous ones.
Since outA (which by the way will have to be a reg if your for loop is embedded in an always block), is only updated after the always block has finished "executing", only inA[7] can cause an increment to outA.
Have a look at my answer here for further information on how always blocks are executed.


text:
Q: Sockets in C: recv fails after one byte I'm currently doing an assignment in which we are defined to use send()/recv() with two parts:

first send an int that indicates the length of the string (4 bytes) and then send the string itself.

When I try to run the client/server on my PC, only the first recv() returns success, while the next one fails.
When I run the same code on my partner's PC, it works well.
The error I'm receiving for recv() is 10054.
I am totally clueless, and have no idea how to approach this.
The receiving code is:
TransferResult_t ReceiveString(char** OutputStrPtr, SOCKET sd){

    /* Recv the the request to the server on socket sd */
    int TotalStringSizeInBytes;
    TransferResult_t RecvRes;
    char* StrBuffer = NULL;

    if ((OutputStrPtr == NULL) || (*OutputStrPtr != NULL))
    {
        printf("The first input to ReceiveString() must be "
            "a pointer to a char pointer that is initialized to NULL. For example:\n"
            "\tchar* Buffer = NULL;\n"
            "\tReceiveString( &Buffer, ___ )\n");
        return TRNS_FAILED;
    }

    /* The request is received in two parts. First the Length of the string (stored in
    an int variable ), then the string itself. */

    RecvRes = ReceiveBuffer(
        (char *)(&TotalStringSizeInBytes),
        (int)(sizeof(TotalStringSizeInBytes)), // 4 bytes
        sd);

    if (RecvRes != TRNS_SUCCEEDED) return RecvRes;

    StrBuffer = (char*)malloc(TotalStringSizeInBytes * sizeof(char));

    if (StrBuffer == NULL)
        return TRNS_FAILED;

    RecvRes = ReceiveBuffer(
        (char *)(StrBuffer),
        (int)(TotalStringSizeInBytes),
        sd);

    if (RecvRes == TRNS_SUCCEEDED)
    {
        *OutputStrPtr = StrBuffer;
    }
    else
    {
        free(StrBuffer);
    }

    return RecvRes;
}

The ReceiveBuffer function is:
TransferResult_t ReceiveBuffer(char* OutputBuffer, int BytesToReceive, SOCKET sd){

    char* CurPlacePtr = OutputBuffer;
    int BytesJustTransferred;
    int RemainingBytesToReceive = BytesToReceive;

    while (RemainingBytesToReceive > 0)
    {
        /* send does not guarantee that the entire message is sent */
        BytesJustTransferred = recv(sd, CurPlacePtr, RemainingBytesToReceive, 0);
        if (BytesJustTransferred == SOCKET_ERROR)
        {
            printf("recv() failed, error %d\n", WSAGetLastError());
            return TRNS_FAILED;
        }
        else if (BytesJustTransferred == 0)
            return TRNS_DISCONNECTED; // recv() returns zero if connection was gracefully disconnected.

        RemainingBytesToReceive -= BytesJustTransferred;
        CurPlacePtr += BytesJustTransferred; // <ISP> pointer arithmetic
    }

    return TRNS_SUCCEEDED;
}

ADDED: the sending function:
TransferResult_t SendString( const char *Str, SOCKET sd ){
    /* Send the the request to the server on socket sd */
    int TotalStringSizeInBytes;
    TransferResult_t SendRes;

    /* The request is sent in two parts. First the Length of the string (stored in
    an int variable ), then the string itself. */

    TotalStringSizeInBytes = (int)( strlen(Str) + 1 ); // terminating zero also sent

    SendRes = SendBuffer(
        (const char *)( &TotalStringSizeInBytes ),
        (int)( sizeof(TotalStringSizeInBytes) ), // sizeof(int)
        sd );

    if ( SendRes != TRNS_SUCCEEDED ) return SendRes ;

    SendRes = SendBuffer(
        (const char *)( Str ),
        (int)( TotalStringSizeInBytes ),
        sd );

    return SendRes;
}

And:
TransferResult_t SendBuffer( const char* Buffer, int BytesToSend, SOCKET sd ){
    const char* CurPlacePtr = Buffer;
    int BytesTransferred;
    int RemainingBytesToSend = BytesToSend;

    while ( RemainingBytesToSend > 0 )
    {
        /* send does not guarantee that the entire message is sent */
        BytesTransferred = send (sd, CurPlacePtr, RemainingBytesToSend, 0);
        if ( BytesTransferred == SOCKET_ERROR )
        {
            printf("send() failed, error %d\n", WSAGetLastError() );
            return TRNS_FAILED;
        }

        RemainingBytesToSend -= BytesTransferred;
        CurPlacePtr += BytesTransferred; // <ISP> pointer arithmetic
    }

    return TRNS_SUCCEEDED;
}


text:
Q: Post classes in the loop are being changed in certain themes Certain themes don't use the default post class structure in the loop ie

Spacing.ca, for example, doesn't use this structure. The posts in their loop use the following tag structure:

The result is that you cannot add classes to these sorts of posts in the main loop using:
add_filter('post_class', 'my_post_class')

I'd like to be able to add classes to specific posts in the loop given specific criteria (via a plugin im making) and can do it if themes use the standard structure first mentioned, but cannot do it if the theme uses the less typical structure in the 2nd code snippet.
Any thoughts on how I could add classes to posts when the theme uses the 2nd code snippet?
Thanks

A: If themes don't use post_class, which is what generates what you call the "default post class structure", it is going to be difficult, and may be something you have to deal with on a theme by theme basis.
There are very few hooks in the Loop itself that you can use, and while things like the_content and the the_title would provide you some hooks there is no guarantee that the theme is using those either. If the author neglected something as critical as post_class, who knows what else is left out or hacked.
I can't think of a general purpose solution for cases where the theme is simply doing it wrong. Even output buffering + regex won't work as a general solution as you have no way to reliable find the content section.
Some people treat those classes like "bloat". It is also possible that the theme or a plugin has hooked something that removes those classes.

A: We're not magicians ;)
If there is no function call or hook, then there is no way to do this.
(Well, you always can buffer the output and then preg_replace it, but I wouldn't use plugin which do something like that).


text:
Q: HQL match string percentage Can I pull data based on percentage matched with string.
Let my Table is Employee having a column named 'empName'
session.createQuery("from Employee where percentage(empName, :emp_name) >= 85 ");
query.setParameter("emp_name", "Tony");


text:
Q: Exclude hidden files and folders in linux find I am trying to exclude hidden files and folders when doing a find in linux.
I have to exclude files or folders that start with a dot (.hidden) but also have to exclude folders that start with an @ (like @eaDir).
So far I have the following command which seems to work but maybe there is a more elegant way?
find /path/to/start/search/ -not -path '*@eaDir*' -not -path "*/\.*" -type f -mtime -2

I did see examples using regular expression like so:
find . \( ! -regex '.*/\..*' \) -type f

but not sure how I would also exclude @eaDir directories with the -regexoption?
I believe there can also be hidden files that start with two dots? like "..hidden"? Is this already covered with my command or would I simply add a third option like -not -path "*/\..*" to exclude those as well?
Then I saw some examples of using -prune so that find won't descend in hidden directories, however I am unsure how I would use this correclty in my example. I would be interested in this to speed things up.
Thanks!

A: Use -not -name '.*'. This will exclude any names that begin with ..

A: Exclude files and folders starting with a . or an @:
find /path/to/start/search/ -not -path '*/[@.]*' -type f -mtime -2

Exclude files starting with a . and files and folders starting with a . or an @:
find /path/to/start/search/ -not -path '*/.*' -type f -mtime -2 | grep -v '/@.*/.*'