text:
Q: Error While Using Realm in React Native app React Native app works fine on emulator (with debugging + without debugging) and also on Android device (without debugging). But when I connect app with chrome for debugging, it's giving below error:
Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://192.168.1691.130/create_session'
React Native Version:
react-native-cli: 2.0.1
react-native: 0.42.3


text:
Q: No module found when importing win32api I was learning Python recently and I encountered one question. I tried to install pywin32 via pip pypiwin32 or the binary. And the installation showed successful for both case. The strange thing is when I directly typed:import win32apiin the CMD, it worked fine. But when I wrote it in a python.py and drag the file in the CMD, the error message: "No module named win32api" rose. Anything I can do solve this problem? I am running python 3.6.2 in windows 7.
Please forgive me for my poor English.
Thank you for your help :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pod is in pending stage ( Error : FailedScheduling : nodes didn't match node selector ) I have a problem with one of the pods. It says that it is in a pending state.
If I describe the pod, this is what I can see:
Events:
  Type     Reason             Age                From                Message
  ----     ------             ----               ----                -------
  Normal   NotTriggerScaleUp  1m (x58 over 11m)  cluster-autoscaler  pod didn't trigger scale-up (it wouldn't fit if a new node is added): 2 node(s) didn't match node selector
  Warning  FailedScheduling   1m (x34 over 11m)  default-scheduler   0/6 nodes are available: 6 node(s) didn't match node selector.

If I check the logs, there is nothing in there (it just outputs empty value).
--- Update ---
This is my pod yaml file
apiVersion: v1
kind: Pod
metadata:
  annotations:
    checksum/config: XXXXXXXXXXX
    checksum/dashboards-config: XXXXXXXXXXX
  creationTimestamp: 2020-02-11T10:15:15Z
  generateName: grafana-654667db5b-
  labels:
    app: grafana-grafana
    component: grafana
    pod-template-hash: "2102238616"
    release: grafana
  name: grafana-654667db5b-tnrlq
  namespace: monitoring
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: grafana-654667db5b
    uid: xxxx-xxxxx-xxxxxxxx-xxxxxxxx
  resourceVersion: "98843547"
  selfLink: /api/v1/namespaces/monitoring/pods/grafana-654667db5b-tnrlq
  uid: xxxx-xxxxx-xxxxxxxx-xxxxxxxx
spec:
  containers:
  - env:
    - name: GF_SECURITY_ADMIN_USER
      valueFrom:
        secretKeyRef:
          key: xxxx
          name: grafana
    - name: GF_SECURITY_ADMIN_PASSWORD
      valueFrom:
        secretKeyRef:
          key: xxxx
          name: grafana
    - name: GF_INSTALL_PLUGINS
      valueFrom:
        configMapKeyRef:
          key: grafana-install-plugins
          name: grafana-config
    image: grafana/grafana:5.0.4
    imagePullPolicy: Always
    name: grafana
    ports:
    - containerPort: 3000
      protocol: TCP
    readinessProbe:
      failureThreshold: 3
      httpGet:
        path: /api/health
        port: 3000
        scheme: HTTP
      initialDelaySeconds: 30
      periodSeconds: 10
      successThreshold: 1
      timeoutSeconds: 30
    resources:
      requests:
        cpu: 200m
        memory: 100Mi
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /etc/grafana
      name: config-volume
    - mountPath: /var/lib/grafana/dashboards
      name: dashboard-volume
    - mountPath: /var/lib/grafana
      name: storage-volume
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-tqb6j
      readOnly: true
  dnsPolicy: ClusterFirst
  initContainers:
  - command:
    - sh
    - -c
    - cp /tmp/config-volume-configmap/* /tmp/config-volume 2>/dev/null || true; cp
      /tmp/dashboard-volume-configmap/* /tmp/dashboard-volume 2>/dev/null || true
    image: busybox
    imagePullPolicy: Always
    name: copy-configs
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /tmp/config-volume-configmap
      name: config-volume-configmap
    - mountPath: /tmp/dashboard-volume-configmap
      name: dashboard-volume-configmap
    - mountPath: /tmp/config-volume
      name: config-volume
    - mountPath: /tmp/dashboard-volume
      name: dashboard-volume
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-tqb6j
      readOnly: true
  nodeSelector:
    nodePool: cluster
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 300
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - emptyDir: {}
    name: config-volume
  - emptyDir: {}
    name: dashboard-volume
  - configMap:
      defaultMode: 420
      name: grafana-config
    name: config-volume-configmap
  - configMap:
      defaultMode: 420
      name: grafana-dashs
    name: dashboard-volume-configmap
  - name: storage-volume
    persistentVolumeClaim:
      claimName: grafana
  - name: default-token-tqb6j
    secret:
      defaultMode: 420
      secretName: default-token-tqb6j
status:
  conditions:
  - lastProbeTime: 2020-02-11T10:45:37Z
    lastTransitionTime: 2020-02-11T10:15:15Z
    message: '0/6 nodes are available: 6 node(s) didn''t match node selector.'
    reason: Unschedulable
    status: "False"
    type: PodScheduled
  phase: Pending
  qosClass: Burstable

Do you know how should I further debug this?

A: Solution :  You can do one of the two things to allow scheduler to fullfil your pod creation request.

*

*you can choose to remove these lines from your pod yaml and start your pod creation again from scratch (if you need a selector for a reason go for approach as on next step 2)
nodeSelector:
    nodePool: cluster

or

*You can ensure that you add this nodePool: cluster as label to all your nodes so the pod will be scheduled by using the available selector.

You can use this command to label all nodes
kubectl label nodes <your node name> nodePool=cluster
Run above command by replacing node name from your cluster details for each node or only the nodes you want to be select with this label.

A: Your pod probably uses a node selector which can not fulfilled by scheduler.
Check pod description for something like that
    apiVersion: v1
    kind: Pod
    metadata:
      name: nginx
      labels:
        env: test
    spec:
      ...
      nodeSelector:
        disktype: ssd

And check whether your nodes are labeled accordingly.

A: The simplest option would be to use "nodeName" in the Pod yaml.
First, get the node where you want to run the Pod:
kubectl get nodes

Use the below attribute inside the Pod definition( yaml) so that the Pod is forced to run under the below mentioned node only.
nodeName: seliiuvd05714


text:
Q: Breaking up a print statement Python with intermediate process When i run the script below, the print statement(s) appear at the same time. I would like the first print statement to display, then the loop to execute, then the run time to print.
Is there an additional statement I need to include?
import time
def main():
    Time = time.clock()
    print("Counting to 100,000,000:", end = "")

    for i in range(1,100000000):
        a = 3

    print(" -- Time: ", time.clock() - Time)

if __name__ == "__main__":
    main()

A: There is a buffer in Python's standard output. This means that data you want to write (as in print()) is sometimes stored and then written in one go - as you are experiencing here.
To override this, just call sys.stdout.flush() which "flushes" everything already in this buffer out.
So to apply this to your code, it would look something like:
import time, sys
def main():
    Time = time.clock()
    print("Counting to 100,000,000:", end = "")
    sys.stdout.flush()

    for i in range(1,100000000):
        a = 3

    print(" -- Time: ", time.clock() - Time)

if __name__ == "__main__":
    main()

which ran as expected for me (producing the following output) with the second part coming through later.
Counting to 100,000,000: -- Time:  4.796258999999999


text:
Q: Angular4 DataTable - Property '$key' does not exist I am using the Angular 4 datatable from here https://github.com/MIt9/angular-4-data-table and this is my code in my ProductsComponent.html:
<data-table [items]="items" [itemCount]="itemCount"

(reload)="reloadItems($event)">

  <data-table-column [property]="'title'" [header]="'Title'" [sortable]="true" [resizable]="true"></data-table-column>

  <data-table-column [property]="'price'" [header]="'Price'" [sortable]="true" [resizable]="true">
    <ng-template #dataTableCell let-item="item">
      {{ item.price | currency:'USD'}}
    </ng-template>
  </data-table-column>

  <data-table-column [property]="$key">
    <ng-template #dataTableCell let-item="item">
      Edit
    </ng-template>
  </data-table-column>

</data-table>

The datatable renders all the data just fine, the browser doesnt show any errors and neither does the compilation during ng serve. However, when I run a ng build --prod I see the following error message and the build fails. Property '$key' does not exist on type 'ProductsComponent'. I am having a hard time debugging this as I don't see a bug when testing - any ideas whats going on here?

A: The $key in the property definition needed to be wrapped in quotes because I am not explicitly referencing a property from my component but a string property from the json object.
  <data-table-column [property]="'$key'">
    <ng-template #dataTableCell let-item="item">
      Edit
    </ng-template>
  </data-table-column>

A: It is probably just a case of not setting 'public' on your variable '$key' in your component.ts file
this part of your code:
    [property]="$key"
as soon as you have a property/attribute enclosed in [] the value assigned to it will be evaluated e.g.

*

*[property] = "'a string'" evaluates to 'a string'

*[property] = "$key" looks for a variable named $key so it can bind the value of $key to property

You probably missing the quotes like so [property]="'$key'"
Angular Docs has more info on this.


text:
Q: python urllib request with cookie processor and user-agent header Using python 3, I am making an http request that needs to handle cookies and represent itself as a browser. This is what I am trying.
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open(uri)

I believe I have built an 'OpenDirector' here but have no idea how to get the reponse from it. It doesn't seem have a read method. How do I finish this?
content = opener.read.decode('utf-8', errors='replace')

Above doesn't work because there is no read method.

A: This works:
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
content =  opener.open(uri).read().decode('utf-8', errors='replace')


text:
Q: Fix two colours on UISlider swift Slider with two different colors
How can we make a slider with two fixed colors? The colors won't change even if the slider is moving. Also, the slider thumb should be able to side over any of those two colors. I should be able to define the length of the first section.
    func createSlider(slider:UISlider) {
    let frame = CGRect(x: 0.0, y: 0.0, width: slider.bounds.width, height: 4)
    let tgl = CAGradientLayer()
    tgl.frame = frame
    tgl.colors = [UIColor.gray.cgColor,UIColor.red.cgColor]
    tgl.endPoint = CGPoint(x: 0.4, y:  1.0)
    tgl.startPoint = CGPoint(x: 0.0, y:  1.0)
    UIGraphicsBeginImageContextWithOptions(tgl.frame.size, false, 0.0)
    tgl.render(in: UIGraphicsGetCurrentContext()!)

    let backgroundImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    slider.setMaximumTrackImage(backgroundImage?.resizableImage(withCapInsets:.zero),  for: .normal)
    slider.setMinimumTrackImage(backgroundImage?.resizableImage(withCapInsets:.zero),  for: .normal)
}

I have already tried this. But this dosent give me exactly what I wanted to achieve.

A: Here's one approach...

*

*set both min and max track images to "empty" images

*add left and right subviews to act as "fake" track images

*add a different color sublayer on each side subview

*when you slide the thumb, update the frames of the layers

Here's some example code... you may want to do some tweaks:
class XebSlider: UISlider {

    private var colors: [[UIColor]] = [
        [.black, .black],
        [.black, .black],
    ]

    // left and right views will become the "fake" track images
    private let leftView = UIView()
    private let rightView = UIView()

    // each view needs a layer to "change color"
    private let leftShape = CALayer()
    private let rightShape = CALayer()

    // constraints that will be updated
    private var lvWidth: NSLayoutConstraint!
    private var lvLeading: NSLayoutConstraint!
    private var rvTrailing: NSLayoutConstraint!

    // how wide the two "sides" should be
    private var leftPercent: CGFloat = 0
    private var rightPercent: CGFloat = 0

    // track our current width, so we don't repeat constraint updates
    //  unless our width has changed
    private var currentWidth: CGFloat = 0

    init(withLeftSidePercent leftWidth: CGFloat, leftColors: [UIColor], rightColors: [UIColor]) {
        super.init(frame: .zero)
        commonInit()
        leftView.backgroundColor = leftColors[1]
        rightView.backgroundColor = rightColors[1]
        leftShape.backgroundColor = leftColors[0].cgColor
        rightShape.backgroundColor = rightColors[0].cgColor
        leftPercent = leftWidth
        rightPercent = 1.0 - leftPercent
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        // set both track images to "empty" images
        setMinimumTrackImage(UIImage(), for: [])
        setMaximumTrackImage(UIImage(), for: [])

        // add left and right subviews
        [leftView, rightView].forEach { v in
            v.translatesAutoresizingMaskIntoConstraints = false
            v.layer.cornerRadius = 4.0
            v.layer.masksToBounds = true
            v.isUserInteractionEnabled = false
            insertSubview(v, at: 0)
        }

        // add sublayers
        leftView.layer.addSublayer(leftShape)
        rightView.layer.addSublayer(rightShape)

        // create constraints whose .constant values will be modified in layoutSubviews()
        lvLeading = leftView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
        rvTrailing = rightView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
        lvWidth = leftView.widthAnchor.constraint(equalToConstant: 0.0)

        // avoids auto-layout complaints when the frame changes (such as on device rotation)
        lvWidth.priority = UILayoutPriority(rawValue: 999)

        // set constraints for subviews
        NSLayoutConstraint.activate([
            lvLeading,
            rvTrailing,
            lvWidth,

            leftView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0.0),
            leftView.heightAnchor.constraint(equalToConstant: 8.0),

            rightView.centerYAnchor.constraint(equalTo: leftView.centerYAnchor),
            rightView.heightAnchor.constraint(equalTo: leftView.heightAnchor),

            rightView.leadingAnchor.constraint(equalTo: leftView.trailingAnchor, constant: 1.0),
        ])
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // we only want to do this if the bounds width has changed
        if bounds.width != currentWidth {
            let trackRect = self.trackRect(forBounds: bounds)
            lvLeading.constant = trackRect.origin.x
            rvTrailing.constant = -(bounds.width - (trackRect.origin.x + trackRect.width))
            lvWidth.constant = trackRect.width * leftPercent
        }

        // get percentage of thumb position
        //  based on min and max values
        let pctValue = (self.value - self.minimumValue) / (self.maximumValue - self.minimumValue)

        // calculate percentage of each side that needs to be "covered"
        //  by the different color layer
        let leftVal = max(0.0, min(CGFloat(pctValue) / leftPercent, 1.0))
        let rightVal = max(0.0, min((CGFloat(pctValue) - leftPercent) / rightPercent, 1.0))

        var rLeft = leftView.bounds
        var rRight = rightView.bounds

        rLeft.size.width = leftView.bounds.width * leftVal
        rRight.size.width = rightView.bounds.width * rightVal

        // disable default layer animations
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        leftShape.frame = rLeft
        rightShape.frame = rRight
        CATransaction.commit()
    }
}

and a controller example showing its usage:
class ViewController: UIViewController {

    var slider: XebSlider!

    override func viewDidLoad() {
        super.viewDidLoad()

        let leftSideColors: [UIColor] = [
            #colorLiteral(red: 0.4796532989, green: 0.4797258377, blue: 0.4796373844, alpha: 1),
            #colorLiteral(red: 0.8382737041, green: 0.8332912326, blue: 0.8421040773, alpha: 1),
        ]
        let rightSideColors: [UIColor] = [
            #colorLiteral(red: 0.9009097219, green: 0.3499996662, blue: 0.4638580084, alpha: 1),
            #colorLiteral(red: 0.9591985345, green: 0.8522816896, blue: 0.8730568886, alpha: 1),
        ]
        let leftSideWidthPercent: CGFloat = 0.5

        slider = XebSlider(withLeftSidePercent: leftSideWidthPercent, leftColors: leftSideColors, rightColors: rightSideColors)

        view.addSubview(slider)
        slider.translatesAutoresizingMaskIntoConstraints = false

        // respect safe area
        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([

            // constrain slider 40-pts from Top / Leading / Trailing
            slider.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
            slider.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),
            slider.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0),

        ])

    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { _ in
            // to get teh custom slider to update properly
            self.slider.setNeedsLayout()
        }, completion: {
            _ in
        })
    }
}

Result:


text:
Q: Unity async task can't be called outside of main thread? I need to convert a .txt file called TheFile to a dictionary called theFileDictionary and then save it to a binary file.
I am doing this with the following class FileHandler:
public class FileHandler : MonoBehaviour
{
    [SerializeField] TextAsset theFile;
    FileStream file;

    public async Task LoadTheFileIntoBinaryFile()
    {
        BinaryFormatter formatter = new();
        file = File.Create(Application.persistentDataPath + "/foods.txt");
        /*line 33, error gets called*/ await Task.Run(() => { formatter.Serialize(file, LoadTheFileIntoDictionary()); } );
        file.Close();
    }

    Dictionary<string, string[]> LoadTheFileIntoDictionary()
    {
        /*line 39, error occurs*/Dictionary<string, string[]> theFileDictionary =
                theFile
                .text
                .Split('\n')
                .Select(x => x.Split('\t'))
                .ToDictionary(x => x[ApplicationInfo.GetLanguageIndex()].Replace("-", " "));

        return blsDictionary;
    }
}

When starting LoadTheFileIntoBinaryFile() I get this error:

UnityException: get_bytes can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.TextAsset.get_text () (at /Users/bokken/buildslave/unity/build/Runtime/Export/Scripting/TextAsset.cs:23)
FileHandler.LoadTheFileIntoDictionary () (at Assets/Scripts/Daten/FileHandler.cs:39)
FileHandler+<>c__DisplayClass3_0.b__0 () (at Assets/Scripts/Daten/FileHandler.cs:33)
System.Threading.Tasks.Task.InnerInvoke () (at :0)
System.Threading.Tasks.Task.Execute () (at :0)
--- End of stack trace from previous location where exception was thrown ---

From what the error says it seems to be that the Dictionary has to be initialised in Awake() or Start(). When I do that it kinda works but I don't need the method in Start(), I need it sometimes later (and I still need it to load asynchronously)...
I tried declaring and implementing the Dictionary<string, string[]> in Start() but with no change in result.
What am I doing wrong?


text:
Q: How to develop python and cpp mixed project by pybind11? Currently I have some python codes and cpp codes. https://github.com/quiver-team/torch-quiver/tree/main/srcs
cpp codes provides API by pybind11::module.
Now I want to develop these codes, change some cpp codes and python codes.
The first problem is that whether I can use pip install -e . to edit such mixed codes. If not, how can I edit python codes except pip install -e?
The following are some of my ideas:

*

*I try to add -e in current install.sh pip install --no-index -U -e .
But the output is :
/opt/conda/lib/python3.8/distutils/extension.py:131: UserWarning: Unknown Extension options: 'with_cuda'
warnings.warn(msg)
error: ("Can't get a consistent path to setup script from installation directory", '/root/share')
https://github.com/quiver-team/torch-quiver/issues/139
I tried solutions at "Can't get a consistent path to setup script from installation directory" But these solution cannot successfully install.
When I add a pyproject.toml file, the output is ERROR: Could not find a version that satisfies the requirement setuptools>=40.8.0 (from versions: none) But my setuptools  == 58.0.4

*I think I can change python path so that I don't need use pip install, but I don't know where I place my .so files?
May you could recommend some good repo or blogs teach me how to develop this type of repo?


text:
Q: Firebase realtime database rules to edit only existing fields My database:

I want to set firebase rules where user can update existing tags value but not create new tags

A: If you only want the user to be able to update existing properties, and not create any new properties, that'd be:
{
  "rules": {
    "$uid": {
      ".write": "auth.uid === $uid"
      "$property": {
        ".validate": "data.exists()"
      }
    }
  }
}

So this rule validates that a property can only be written if there's already data for that property in the database.

If you only want the user to be able to write a name and address, and not any other properties, that'd be:
{
  "rules": {
    "$uid": {
      ".write": "auth.uid === $uid"
      "name": {
        ".validate": true
      },
      "address": {
        ".validate": true
      },
      "$other": {
        ".validate": false
      }
    }
  }
}

In the above rules we allow writing the named name and address properties, and reject any other properties with a wildcard capture rule.


text:
Q: MySQL SUM row value by id and date What i need to acomplish i sum a value of column of MySQL table based on VARCHAR column value and year range. Maybe that's a confusing so i'll put a basic example:
Columns: id(useless for this), fruit_type, date_of_sale, sale_type, price
Basic Query:
SELECT * FROM fruits

gives me :
  1  APPLES   2018-05-30  GOOD   50.50
  2  APPLES   2018-05-30  BAD   -20.50
  3  APPLES   2018-05-30  GOOD   40.00
  4  APPLES   2018-05-30  BAD   -10.50
  5  APPLES   2017-05-29  GOOD   39.50
  6  APPLES   2017-05-29  BAD   -10.00
  7  APPLES   2017-05-29  GOOD   30.00
  8  APPLES   2017-05-29  BAD   -20.00
  9  BANANAS  2018-05-29  GOOD   20.00
 10  BANANAS  2018-05-29  BAD    20.00
 11  BANANAS  2018-05-29  GOOD   10.00
 12  BANANAS  2018-05-29  BAD    -5.00
 13  BANANAS  2017-05-29  GOOD   50.00
 14  BANANAS  2017-05-29  BAD    -3.00
 15  BANANAS  2017-05-29  GOOD   10.00
 16  BANANAS  2017-05-29  BAD    -3.00
 17  ORANGES  2018-05-28  GOOD    5.00
 18  ORANGES  2018-05-28  BAD    -1.00
 19  ORANGES  2017-05-28  GOOD   10.00
 20  ORANGES  2017-05-28  BAD    -1.00

What i need to acomplish:
  Fruit      Sales 2017    Bad Sales 2017    Total 2017    Sales 2018    Bad Sales 2018    Total 2018
  APPLES     69.50         -30.00            39.50         90.50         -30.50            60.00
  BANANAS    60.00         -6.00             54.00         30.00         -10.00            20.00
  ORANGES    10.00         -1.00             9.00          5.00          -1.00             5.00

The query i've been trying is:
SELECT fruit_type AS Fruit,\
(SELECT SUM(price) FROM fruits WHERE sale_type='GOOD' AND date_of_sale BETWEEN '2017-01-01' AND '2017-12-31') AS Sales_2017,\
(SELECT SUM(price) FROM fruits WHERE sale_type='BAD' AND date_of_sale BETWEEN '2017-01-01' AND '2017-12-31') AS Bad_Sales_2017,\
(SELECT SUM(Sales_2017-Bad_Sales_2017)),\
(SELECT SUM(price) FROM fruits WHERE sale_type='GOOD' AND date_of_sale BETWEEN '2018-01-01' AND '2018-12-31') AS Sales_2018,\
(SELECT SUM(price) FROM fruits WHERE sale_type='BAD' AND date_of_sale BETWEEN '2018-01-01' AND '2018-12-31') AS Bad_Sales_2018,\
(SELECT SUM(Sales_2018-Bad_Sales_2018)),\
FROM fruits
GROUP BY fruit_type;

The problem is the values returned by the query are the total SUM of the whole column with value GOOD or BAD instead of value GOOD by fruit type match.
Need some tips for that problem plz.

A: use sum + case when condition to summary your sales
try it:
select
  fruit_type AS Fruit,
  sum(
    case when date_of_sale between '2017-01-01 00:00:00' and '2017-12-31 00:00:00' then
      case when sale_type = 'GOOD' then price else 0 end
    else 0 end
  ) "Sales 2017",
  sum(
    case when date_of_sale between '2017-01-01 00:00:00' and '2017-12-31 00:00:00' then
      case when sale_type = 'BAD' then price else 0 end
    else 0 end
  ) "Bad Sales 2017",
  sum(
    case when date_of_sale between '2017-01-01 00:00:00' and '2017-12-31 00:00:00' then
      price
    else 0 end
  ) "Total 2017",
  sum(
    case when date_of_sale between '2018-01-01 00:00:00' and '2018-12-31 00:00:00' then
      case when sale_type = 'GOOD' then price else 0 end
    else 0 end
  ) "Sales 2018",
  sum(
    case when date_of_sale between '2018-01-01 00:00:00' and '2018-12-31 00:00:00' then
      case when sale_type = 'BAD' then price else 0 end
    else 0 end
  ) "Bad Sales 2018",
  sum(
    case when date_of_sale between '2018-01-01 00:00:00' and '2018-12-31 00:00:00' then
      price
    else 0 end
  ) "Total 2018"
FROM fruits
GROUP BY fruit_type;

SQL Fiddle Demo Link

A: SELECT T.FRUIT,
  SUM(IF(T.YEAR='2017' AND T.sale_type='GOOD',T.price_per_year,0)) `Sales 2017`,
  SUM(IF(T.YEAR='2017' AND T.sale_type='BAD',T.price_per_year,0)) `Bad Sales 2017`,
  SUM(IF(T.YEAR='2017',T.price_per_year,0)) `Total 2017`,
  SUM(IF(T.YEAR='2018' AND T.sale_type='GOOD',T.price_per_year,0)) `Sales 2018`,
  SUM(IF(T.YEAR='2018' AND T.sale_type='BAD',T.price_per_year,0)) `Bad Sales 2018`,
  SUM(IF(T.YEAR='2018',T.price_per_year,0)) `Total 2018`
FROM (SELECT
  FRUIT_TYPE FRUIT,
  YEAR(date_of_sale) YEAR,
  sale_type,
  SUM(price) price_per_year
FROM fruits
GROUP BY
FRUIT_TYPE,
YEAR(date_of_sale),
sale_type) T
GROUP BY FRUIT
ORDER BY T.FRUIT;

See a working DEMO on SQL Fiddle.

A: Try this, just add more subselects for each row you want.
SELECT all2017.fruit_type as Fruit
,Sales_2017
,Bad_Sales_2017
from (SELECT fruit_type
,SUM(ABS(price)) Sales_2017
FROM fruits
WHERE year(date) = 2017
GROUP BY fruit_type) as all2017
join (SELECT fruit_type
,SUM(ABS(price)) Bad_Sales_2017
FROM fruits
WHERE year(date) = 2017
AND sales_type = 'BAD'
GROUP BY fruit_type) as bad2017
on all2017.fruit_type = bad2017.fruit_type


text:
Q: Selendroid scroll issue Using appium-selendroid mode on my real device running Android API level 17, I try to scroll down using the following code
TouchActions action = new TouchActions(driver).scroll(0,100);
action.perform();

The scrolling takes place however, The elements do not get rendered.Kindly help to figure out the issue.

A: Solution - implement a class that uses the interface RemoteWebDriver
    public class SwipeableWebDriver extends RemoteWebDriver implements HasTouchScreen {
    public RemoteTouchScreen touch;
public SwipeableWebDriver(URL url, Capabilities caps) {
    super(url, caps);
    touch = new RemoteTouchScreen(getExecuteMethod());
}

public TouchScreen getTouch() {
    return touch;
}

Now instantiate a driver of this class and use the Touch class as given in the question with the "flick" gesture rather than scroll.

A: I was using same code and was facing same issue and after using flick method it was fixed for me. Already answered here
Don't use scroll just replace it with flick and you also have to give an element address with flick.

TouchActions action = new TouchActions(driver).flick(element_add, 0,
  -1000, 100); action.perform();


text:
Q: Godot: How to calculate an angle with multitouch and smoothly add it to camera rotation I've been struggling for a few days to build multitouch rotation functionality in my godot game and have succesfully managed to incorporate zoom code and simulating multitouch.
One problem I'm facing though is multitouch rotation, I am trying to replicate what Google Maps or Apple Maps does with 2 finger rotation using godot and gdscript. I like how when you rotate in maps it rotates from where you pressed.
I have a 3D scene with a 3D Camera set as orthogonal and I am trying to rotate around the Camera.position.Y
What is the problem:
When I use _camera.rotation.y = _centerScreenVector2.angle_to_point(touchvector) * delta it feeds the angle directly (the angle being the center point to where I've touched) and the rotation snaps to the new angle, i'd like to calculate the angle where I've touched and where I've travelled to.
I'd imagine it would look something like _camera.rotation.y = _camera.rotation.y + angleBetweenPoints * delta
I'll add some of my existing code below, apologies if its badly written (i've ommited a lot of the code that isnt relevant (zoom code and screen orientation code)
func _input(event):
if event is InputEventScreenTouch:
    if event.pressed:
        match event.index:
            0:
                pos_0 = event.position
                pos_0_last_touched = pos_0
                pos_0_valid = true
                pos_0_moved = false
                _line.points[0] = event.position
            1:
                pos_1 = event.position
                pos_1_last_touched = pos_1
                pos_1_valid = true
                pos_1_moved = false
                rotated_pos_1 = pos_1.rotated(_line.points[0].angle_to_point(_line.points[1]))
                _line.points[1] = event.position

    else:
        match event.index:
            0:
                pos_0 = Vector2.ZERO
                pos_0_valid = false
                pos_0_moved = false
                distance_prev_valid = false

            1:
                pos_1 = Vector2.ZERO
                pos_1_valid = false
                pos_1_moved = false
                distance_prev_valid = false
    elif event is InputEventScreenDrag:
    match event.index:
        0:
            pos_0 = event.position
            pos_0_moved = true
        1:
            pos_1 = event.position
            pos_1_moved = true

func _physics_process(delta):

    deg = rad2deg(_line.points[0].angle_to_point(_line.points[1]))

    if (pos_0_valid && pos_1_valid):
       #just testing with 1 finger first
       camera.rotation.y = test.position.angle_to_point(pos_0)

Thank you! please review the image below I've tried to illustrate my problem.
Further clarification aka TLDR
If what I wrote above is convoluted and confusing let me try simplify my question
How can I rotate an orthogonal scene using multitouch where when putting my fingers down and create an arc it smoothly adds to the camera rotation, exactly like you would see in Google maps?
image visualising orthogonal rotation problem


text:
Q: How to make qemu generate external interrupt and jump to isr (bare metal code) I have an stm32 (arm-cortexm3) firmware running in qemu and want to emulate a hw interrupt, say uart rx interrupt. How can I make qemu to make a jump to the isr implemented in my firmware?
I have placed the isr at correct place in the vector table.
I have set the irq number in my emulated uart.
But when I call qemu_set_irq() and then cpu_interrupt(&env, CPU_INTERRUPT_HARD),
qemu interrupts but aborts with "hwerror, interrupt but no vector".
Something is missing. Does anyone know about this?
EDIT:
Using qemu-stable-2.10
nvic = armv7m_init(system_memory, flash_size, NUM_IRQ_LINES, kernel_filename, cpu_model);
qemu_irq uart_irq = qdev_get_gpio_in(nvic, 1);
uart = sysbus_create_simple(TYPE_VCPU_UART, 0x40020000, uart_irq);

If I later do:
qemu_set_irq(uart_irq ,1);

I would expect a jump to the uart isr, but it does not occur.
Is this correct hook up of nvic/irq, or is something more missing?
EDIT2
I realized that I had not enabled the interrupts in the firmware code! Oops!
After setting proper bits in NVIC Set Enable register it works!

A: You shouldn't be calling cpu_interrupt() yourself (it is an internal function within QEMU's CPU model code, not one intended to be called from a board or device model). The Arm M-profile CPU has a very tightly integrated interrupt controller (the NVIC), which in QEMU's emulation is also closely connected to the CPU. You should have your board model wire up the UART's interrupt line to the NVIC, and then the NVIC will take care of telling the CPU which interrupt needs to be taken (based on interrupt priorities, masking, etc). The error message you're getting is because your incorrect call to cpu_interrupt() is effectively telling one half of this system (the cpu) about the interrupt but not the other half (the NVIC) -- so when the cpu asks the NVIC about this interrupt the NVIC says "never heard of it" and aborts. If you use the proper interface for telling the NVIC about interrupts it will work correctly. (The existing QEMU M profile board models will have code which does this.)
Important note: the M profile interrupt handling was significantly rewritten in QEMU 2.9, as it was quite buggy before then, and we fixed some further exception related bugs in 2.10. If you are using M profile I strongly recommend using 2.10 or later. I can tell you aren't because that particular error message is part of the old and buggy code.

A: I believe you should be using qemu_set_irq instead.


text:
Q: IReadOnlyList to BindingList I'm trying to bind a IReadOnlyList of a Material class I made to a ComboBox but I can't find a way to make this works.
var bList = new BindingList<Material>(listToBind);

This gives me Argument type 'System.Collections.Generic.IReadOnlyList<Data.Material>' is not assignable to parameter type 'System.Collections.Generic.IList<Data.Material>'
Do I need to cast it to IList or is there any other way to accomplish this ?

A: BindingList<T> does not have a constructor that takes any of the interfaces an IReadOnlyList extends.
BindingList<T> has two constructors (MSDN docs), one is empty, and the other takes an IList<T>. However, IReadOnlyList<T> extends IEnumerable<T>, which means it provides the function .ToList() that gives us a List<T> that we can use to populate our BindingList<T>.
The final code would then look like this:
var bList = new BindingList<Material>(listToBind.ToList());

A: In MSDN:

BindingList(IList)
  Initializes a new instance of the BindingList class with the specified list.

So you need an object which implements IList; IReadOnlyList does not.
You could achive what you want with the following code:
var bList = new BindingList<Material>(listToBind.ToList());


text:
Q: How can I prevent "yyyy-mm-dd" from breaking within the string I have block of strings (below) that looks like this:
022-05-26 2022-05-25 2022-05-24 2022-05-23 2022-05-19 2022-05-18 2022-05-14 2022-05-11 2022-05-10 2022-05-09 2022-05-08 2022-05-05 2022-05-04 2022-05-03 2022-05-02 2022-05-01
But displayed in a div in a web page the words are split at the YYYY-MM-DD dashes (interpretted an hyphens) which I don't want it do:
022-05-26 2022-05-25 2022-05-24 2022-05-23 2022-05-19 2022-05-18 2022-05-14 2022-05-
11 2022-05-10 2022-05-09 2022-05-08 2022-05-05 2022-05-04 2022-05-03 2022-05-02 2022-05-01

I have tried css solutions to keep the word from breaking. overflow-wrap and word-break were not useful.
Any suggestions would be helpful.

A: I don't think you can with only CSS, but you could just wrap each date in a span/div and style it with something like
span.date-block {
   display: inline-block;
   whitespace: nowrap;
}


text:
Q: Change Checkout Step Label in Magento 2 How i can change checkout steps Label in magento 2?
http://prntscr.com/nr9rrr

A: You can achieve this using a mixin.
Create a requirejs-config.js file in your design folder e.g. app/design/frontend/custom/theme/Magento_Checkout/requirejs-config.js
var config = {
    'config': {
        'mixins': {
            'Magento_Checkout/js/view/shipping': {
                'Magento_Checkout/js/view/checkout/shipping-mixin': true
            }
        }
    }
};

Now create your mixin under the same directory e.g. app/design/frontend/custom/theme/Magento_Checkout/web/js/view/checkout/shipping-mixin.js
define([
    'jquery',
    'ko',
    'Magento_Checkout/js/model/step-navigator'
], function($, ko, stepNavigator) {
    'use strict';

    var mixin = {
        initialize: function() {
            this._super();
            $.each(stepNavigator.steps(), function(index, step) {
                if (step.code === 'shipping') {
                    step.title = 'Your step title';
                }
            });
        }
    };

    return function(target) {
        return target.extend(mixin);
    }
});

A: Magento 2 having onepage 2 step checkout.

*

*Shiping

*Review & Payment

For changing Label for Shipping
copy a file /vendor/magento/module-checkout/frontend/web/js/view/shipping.js.
create a new file in app/design/frontend/{vendorname}/{themename}/Magento_Checkout/web/js/view/shipping.js
change in function stepNavigator.registerStep 3rd argument shipping to custom label.
stepNavigator.registerStep(
                        'shipping',
                        '',
                        $t('Custom Label'),
                        this.visible, _.bind(this.navigate, this),
                        10
                    );
same way we can change for review and payment step in payment.js file.


text:
Q: Bisecting line segments in a tetrahedron. Suppose that $OABC$ is a regular tetrahedron with base $ABC$. Suppose further that $T$ is the mid-edge of $AC$, $Q$ is the mid-edge of $OB$, $P$ is the mid-edge of $OA$, and $U$ is the mid-edge of $CB$.
How can one show that $QT$ bisects $PU$?

A: The midpoint of either $QT$ or $PU$ is simply $\frac{O+A+B+C}4$.

A: One nice way to see this is to realize you can determine a regular tetrahedron by taking a set of (four) non-adjacent vertices of a cube. Each of the six edges of this tetrahedron is a diagonal of a face of that cube, so each "mid-edge" point of the tetrahedron is the center of a cube-face. Any of the segments joining opposite "mid-edge" points, then, is perpendicular to the corresponding cube-faces, and passes through the cube's center (which bisects each of those segments).


text:
Q: Rebuild flat json to nested json for treeview plugin From a rest service I receive the following json:
    [{
        "number": "59875002030004",
        "level": 1,
        "name": "VALUEOPTIONS - CHANGED NAME",
        "costcenter": "51181"
    }, {
        "number": "51873762550004",
        "level": 2,
        "name": "SEABULK INTERNATIONAL",
        "costcenter": "53170"
    }, {
        "number": "53593295610004",
        "level": 3,
        "name": "NOTRE DAME SECONDARY SCHOOL",
        "costcenter": "51181"
    }, {
        "number": "53593295610024",
        "level": 4,
        "name": "NOTRE DAME SECONDARY SCHOOL",
        "costcenter": "51181"
    }, {
        "number": "57743516530004",
        "level": 3,
        "name": "THE DAILY NEWS",
        "costcenter": "53170"
    }, {
        "number": "55724780540004",
        "level": 4,
        "name": "SEALAND",
        "costcenter": "51181"
    }, {
        "number": "53507720410004",
        "level": 5,
        "name": "BALDWIN TECHNOLOGY",
        "costcenter": "53170"
    }, {
        "number": "58804493340004",
        "level": 3,
        "name": "AUTOMATED BUILDING COMPONENTS",
        "costcenter": "51181"
    }, {
        "number": "53454777630004",
        "level": 2,
        "name": "TECK COMINCO AMERICAN",
        "costcenter": "53170"
    }, {
        "number": "53757520360004",
        "level": 3,
        "name": "THE CONVERTIBLE CASTLE",
        "costcenter": "51181"
    }, {
        "number": "56995879770004",
        "level": 3,
        "name": "INNOVAPOST+",
        "costcenter": "51181"
    }, {
        "number": "58317262690004",
        "level": 4,
        "name": "LYDALL",
        "costcenter": "53170"
    }, {
        "number": "55841724060004",
        "level": 5,
        "name": "PROVIDENT NEW YORK BANCORP",
        "costcenter": "51181"
    }, {
        "number": "57687006340004",
        "level": 5,
        "name": "HILLCREST HEALTHCARE SYSTEM",
        "costcenter": "51177"
    }, {
        "number": "57687006340024",
        "level": 6,
        "name": "HILLCREST HEALTHCARE SYSTEM",
        "costcenter": "51177"
    }, {
        "number": "57687006340044",
        "level": 6,
        "name": "HILLCREST HEALTHCARE SYSTEM",
        "costcenter": "51177"
    }, {
        "number": "57687006340064",
        "level": 6,
        "name": "HILLCREST HEALTHCARE SYSTEM",
        "costcenter": "51177"
    }, {
        "number": "57746248440004",
        "level": 5,
        "name": "HAMPSHIRE HOLDINGS CORP",
        "costcenter": "51181"
    }, {
        "number": "57746248440024",
        "level": 6,
        "name": "HAMPSHIRE HOLDINGS CORP",
        "costcenter": "51181"
    }, {
        "number": "57746248440044",
        "level": 6,
        "name": "HAMPSHIRE HOLDINGS CORP",
        "costcenter": "51181"
    }, {
        "number": "58374896490004",
        "level": 4,
        "name": "R.B.C. LIFE INSURANCE",
        "costcenter": "53170"
    }, {
        "number": "59755252870004",
        "level": 2,
        "name": "MERITER HEALTH SERVICES",
        "costcenter": "51181"
    }, {
        "number": "51573698010004",
        "level": 3,
        "name": "CATHOLIC ELEMENTARY SCHOOL",
        "costcenter": "53170"
    }, {
        "number": "59788019250004",
        "level": 2,
        "name": "COSMETIC ESSENCE",
        "costcenter": "51181"
    }]

Which I need to rebuild for the jonmiles treeview plugin https://github.com/jonmiles/bootstrap-treeview into a nested json similar to:
[{
    "custId": "59875002030004",
    "text": "VALUEOPTIONS - CHANGED NAME 59875002030004",
    "tags": ["51181"],
    "nodes": [{
            "custId": "51873762550004",
            "text": "SEABULK INTERNATIONAL 51873762550004",
            "tags": ["53170"],
            "nodes": [{
                    "custId": "53593295610004",
                    "text": "NOTRE DAME SECONDARY SCHOOL 53593295610004",
                    "tags": ["51181"],
                    "state": {
                        "checked": true,
                        "selected": true
                    },
                    "nodes": [{
                        "custId": "53593295610024",
                        "text": "SEABULK INTERNATIONAL 53593295610024",
                        "tags": ["51181"],
                        "state": {
                            "checked": true,
                            "selected": true
                        }
                    }]
                },
                {
                    "custId": "57743516530004",
                    "text": "THE DAILY NEWS 57743516530004",
                    "tags": ["53170"],
                    "nodes": [{
                        "custId": "55724780540004",
                        "text": "SEALAND 55724780540004",
                        "tags": ["51181"],
                        "nodes": [{
                            "custId": "53507720410004",
                            "text": "BALDWIN TECHNOLOGY 53507720410004",
                            "tags": ["53170"]
                        }]
                    }]
                },
                {
                    "custId": "58804493340004",
                    "text": "AUTOMATED BUILDING COMPONENTS 58804493340004",
                    "tags": ["51181"]
                }
            ]
        },
        {
            "custId": "53454777630004",
            "text": "TECK COMINCO AMERICAN 53454777630004",
            "tags": ["53170"],
            "nodes": [{
                    "custId": "53757520360004",
                    "text": "THE CONVERTIBLE CASTLE 53757520360004",
                    "tags": ["51181"]
                },
                {
                    "custId": "56995879770004",
                    "text": "INNOVAPOST+ 56995879770004",
                    "tags": ["51181"],
                    "nodes": [{
                            "custId": "58317262690004",
                            "text": "LYDALL 58317262690004",
                            "tags": ["53170"],
                            "nodes": [{
                                    "custId": "55841724060004",
                                    "text": "PROVIDENT NEW YORK BANCORP 55841724060004",
                                    "tags": ["51181"]
                                },
                                {
                                    "custId": "57687006340004",
                                    "text": "HILLCREST HEALTHCARE SYSTEM 57687006340004",
                                    "tags": ["51177"],
                                    "nodes": [{
                                            "custId": "57687006340024",
                                            "text": "HILLCREST HEALTHCARE SYSTEM 57687006340024",
                                            "tags": ["51177"]
                                        },
                                        {
                                            "custId": "57687006340044",
                                            "text": "HILLCREST HEALTHCARE SYSTEM 57687006340044",
                                            "tags": ["51177"]
                                        },
                                        {
                                            "custId": "57687006340064",
                                            "text": "HILLCREST HEALTHCARE SYSTEM 57687006340064",
                                            "tags": ["51177"]
                                        }
                                    ]
                                },
                                {
                                    "custId": "57746248440004",
                                    "text": "HAMPSHIRE HOLDINGS CORP 57746248440004",
                                    "tags": ["51181"],
                                    "nodes": [{
                                            "custId": "57746248440024",
                                            "text": "HAMPSHIRE HOLDINGS CORP 57746248440024",
                                            "tags": ["51181"]
                                        },
                                        {
                                            "custId": "57746248440044",
                                            "text": "HAMPSHIRE HOLDINGS CORP 57746248440044",
                                            "tags": ["51181"]
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "custId": "58374896490004",
                            "text": "R.B.C. LIFE INSURANCE 58374896490004",
                            "tags": ["53170"],
                            "nodes": [{
                                "custId": "51573698010004",
                                "text": "CATHOLIC ELEMENTARY SCHOOL 51573698010004",
                                "tags": ["53170"]
                            }]
                        },
                        {
                            "custId": "59788019250004",
                            "text": "COSMETIC ESSENCE 59788019250004",
                            "tags": ["51181"]
                        }
                    ]
                }
            ]
        },
        {
            "custId": "59755252870004",
            "text": "MERITER HEALTH SERVICES 59755252870004",
            "tags": ["51181"]
        }
    ]
}]

Is there any library I can use to unflatten the json or one who has a starting point?


text:
Q: SQL Server 2014 - No services installed in SQL Configuration Manager I have Installed Microsoft® SQL Server® 2014 Express , but I can't find SQL Server Services to run it in the "SQL Server Configuration Manager", so I can't connect to SQL server.
It's a problem because when I launch Sql Server Management Studio and that I try to connect me on the database server with server name "(local)", "localhost", "SQLEXPRESS",(local)/SQLEXPRESS, it doesn't work
I've seen in services.msc and I saw "SQL Server VSS Writer" launched automatically.
Do you have a solution ?
Thank you

A: If you download from http://www.microsoft.com/en-us/download/details.aspx?id=42299, make sure use SQLEXPRADV_x86_ENU.exe or SQLEXPR_x86_ENU.exe. SQLManagementStudio_x86_FRA.exe does not contains database engine.

A: I want to think that I had the same issue. When this happened to me, I went to the Configuration Manager only to learn that I had no Services whatsoever. I solved it by installing the SQL Server Express with with Advanced Services version from Microsoft.
I don't know whether you do need all its functionality, though. But what I do know is that it will solve your issue.

A: The problem is actually, I am pretty sure, that you have installed the Management Studio, not the Database Engine itself. You have to install the Database Engine. The response @Edward gave will lead you to the Database Engine for SQL Server Express 2014, that will do the trick.
I hope this helps to clarify what the problem was.


text:
Q: How can we fetch >100 comments using YouTube API v2? I know that YouTube API v2 has been deprecated, however, v3 has no provision to fetch comments from youtube videos. So, I have no choice but to use v2 to fetch the comments.
I read online that we are allowed to fetch up to 1000 comments from a youtube video, but I can only fetch 50 results at a time. So, I used the following urls to fetch the data:
http://gdata.youtube.com/feeds/api/videos/JsDY1Ha83M8/comments?v=2&max-results=50&start-index=1
http://gdata.youtube.com/feeds/api/videos/JsDY1Ha83M8/comments?v=2&max-results=50&start-index=51
http://gdata.youtube.com/feeds/api/videos/JsDY1Ha83M8/comments?v=2&max-results=50&start-index=101
http://gdata.youtube.com/feeds/api/videos/JsDY1Ha83M8/comments?v=2&max-results=50&start-index=151
....

and so on, till start-index=1001
The thing is, youtube stops returning comments from start-index=101 and onwards. So, I can only fetch 100 comments. I need to be able to fetch 1000 comments. How can I do that?
To reproduce the issue I am facing, simply go to:
http://gdata.youtube.com/feeds/api/videos/JsDY1Ha83M8/comments?v=2&max-results=50&start-index=101
and you'll see that there are no "entry" fields.

A: As it was announced in Vidcon this year, v3 comments are in testing stage. For interested parties, we include them in testing process, as well as production version is so soon to be launched.


text:
Q: How to make fontsize bigger for one letter in matlab plot title I want to make \mu to appear the same size as the other letters, how can i do that?
title('Größen-Parameter x in dem spongiösen Knochen(300\mum, 600\mum und 2000\mum)');

A: To answer the question in the title:
You can adjust the font size of a letter (or a text of any length) with {\fontsize{size},letter}. E.g.:
title('Größen-Parameter x in dem spongiösen Knochen(300{\fontsize{14}\mu}m, 600{\fontsize{14}\mu}m und 2000{\fontsize{14}\mu}m)');

However, your actual problem seems to be that the mu's appear slightly smaller than the rest of the text. The reason for this is that Matlab by default interprets normal text as literal characters (WYSIWYG) while using a latex interpreter if you call a latex command such as \mu. This causes those letters to be displayed differently.
Of course you can just increase the size of those letters, but that's not very elegant and the letters will still have a different style. As an alternative I would suggest using a Latex interpreter for the whole text - aside from solving your problem, it will also look nicer!
title('Groessen-Parameter x in dem spongioesen Knochen (300 $\mu$m, 600 $\mu$m und 2000 $\mu$m)','interpreter','latex');

The only problem are your german special characters (ö and that double s thingy). To display those correctly you would have to load the german language package ngerman. This isn't easy but there are instructions here. However, if you are using a german matlab (if that's a thing) it might work without that.


text:
Q: ASP.NET MVC Routing issue. Not mapping route I'm new to ASP.NET MVC and I've encountered problem, which I can't solve. I've spent two days searching Google, but still nothing.
So, my situation is:
I'm trying to implement localization in my ASP.NET MVC application using routing.
www.mysite.com/Home/Index - for default (Russian)
www.mysite.com/en/Home/Index - for English
So I'm registering routes:
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                        "Default",
                        "{controller}/{action}",
                        new { controller = "Home", action = "Index"},
                        new { controller = "^[a-zA-z]{4,}$" }
             );

            routes.MapRoute(
                        "Localization",
                        "{lang}/{controller}/{action}",
                        new { lang = "en", controller = "Home", action = "Index" }
            );
        }

Navigating to default: www.mysite.com/Home/Index works fine.
But when I try to navigate to www.mysite.com/en/Home/Index I get 404 error.
What is more interesting, RouteDebugger does'n see my new route:

Adding more new routes, changing the order of their mapping or even deleting all my routes do nothing.
It seems that route {controller}/{action}/{id} is just the default route for MVC which was added "before me".
So, what could be the problem? I have totally no idea! I've seen screenshots of Rote Debugger from other sites and their routes are displayed. For example some other site: Screenshot
Maybe I have to change something in web.config? I'm completely confused. Please help!
Thank you very much for your time!

A: In MVC 4, RouteConfig.cs is stored in App_Start. If you create your project from the MVC 4 project wizard it should wire it all up for you. If not, you will need to call it from global.asax.cs:
protected void Application_Start()
{
    // other stuff ...
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    // other stuff ...
}

Also, IIRC, the MVC 3 project wizard sets up all the default routes directly in Application_Start, so you'll need to remove those (or move them into RegisterRoutes as the case may be).

A: RoutConfig is read sequentially and "Default {controller}/{action}" is very greedy. Move your "Localization" route code above the "Default" route and see if that helps.


text:
Q: How many permutations of {1,2,...,n}. How many permutations of {1,2,...,n} where n >=5 are there such that none of {1,2,3} are adjacent to one another?

Example: the permutation (5,3,1,4,2) does not meet the condition described in the problem because 1 and 3 are in two adjacent places and the permutation (2,5,3,4,1) as well as (1,6,2,5,3,4) meets this condition.

A: Moving comment to answer:
First arrange the numbers $4,5,6,\dots,n$.
Next, pick a "hole" between those or to either side to place the $1$.  Then pick a different hole to place the $2$, etc...

 $(n-3)!\cdot (n-2)(n-3)(n-4)$

In general, the number of permutations of $1,2,3,\dots,k,\dots,n$ where none of $1,2,\dots,k$ are adjacent, the same approach works.

 $(n-k)!\cdot \frac{(n-k+1)!}{(n-2k+1)!}$

or better yet, using $a\frac{b}{~}$ to denote the falling factorial $a\frac{b}{~}=\underbrace{a(a-1)(a-2)\cdots(a-b+1)}_{b~\text{terms}} = \frac{a!}{(a-b)!}$ this would be

 $(n-k)!\cdot (n-k+1)\frac{k}{~}$

A: Consider $A$ representing a permutation of the elements $1,2,3$. Since the remaining $n-3$ elements may be permuted in $(n-3)!$ ways, the required number is $$n!-\binom{3}{2}2!(n-1)!+\binom{3}{3}3!(n-2)!$$ because of the inclusion-exclusion principle.


text:
Q: Workitems migration from TFS 2013 to Visual Studio Team Services What are the best practices to migrate workitems say PBIs/Features manually from TFS to VSTS? And how to ensure we don't lose any linking to changesets or other linked child workitems?
Have referred the below link and the migration tool mentioned is deprecated and would like to know any other options which will help to migrate the data.
How to migrate work items from TFS to VS Team Services (VS Online)

A: The recommend way for now is using  Migrate to Visual Studio Team Service, a  way import your TFS Database into Visual Studio Team Services which definitely along with data.
However, currently only the following versions of TFS are supported for import with this tool:

*

*TFS 2017 Update 3

*TFS 2018

You may have to upgrade your TFS server to use. Alternative, the Microsoft official option is using public API-based tools.
Personally, even though Team Foundation Server Integration Tools has been deprecated. You could still use this solution in your case.
Besides, if you have no work item customization, then OpsHub is an
   option.  VSTS Sync Migration Tools is another way.  But none offer a full fidelity migrations. Each tool has its own limitations.


text:
Q: seaborn: could not convert string to float I have DataFrame df:

Timestamp-start    datetime64[ns]
Timestamp-end      datetime64[ns]
M                          object
S                          object
Type                       object
description_x              object
description_y              object
Date               datetime64[ns]
number_col                 float64
dtype: object

number_col:
51      0.0
0       1.0
1       2.0
2       3.0
52      5.0
      ...
47    148.0
48    148.0
43    148.0
49    149.0
50    149.0
Name: number_col, Length: 132, dtype: float64

And I want to plot histogram using seaborn and column number_col
>     import seaborn as sns
>
>     sns.distplot(df, x='number_col')

But I got this following error:
ValueError: could not convert string to float: 'number_col'

I have no idea why this is happening, 'number_col' is already a float column.

A: sns.distplot does expect Series, 1d-array, or list. as 1st argument, not whole pandas.DataFrame, try replacing
sns.distplot(df, x='number_col')

using
sns.distplot(df['number_col'])

single column of pandas.DataFrame is pandas.Series mentioned as Series in snd.distplot's docs

A: I found that sns.distplot is deprecated. Instead of that we should use sns.displot.
In first argument of sns.displot we can put pandas.DataFrame:
sns.displot(df, x='number_col')


text:
Q: Insert data using SqlDataAdapter I am very confuse with following code .This is also inserting data into table with insert in Stored procedure, even this has not executenonquery(),executescalar() or adapter.insert like methods...
then how it is possible
public DataSet GetDataSet(string spName, System.Collections.Hashtable hst)
{
    cmd.CommandTimeout = 220;
    con = new SqlConnection();
    cmd = new SqlCommand();
    con.ConnectionString = constr;
    cmd.Connection = con;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = spName;
    con.Open();
    if (hst != null)
        if (hst.Count > 0)
            AttachParameters(cmd, hst);
    DataSet dataset = new DataSet();
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = cmd;
    adapter.Fill(dataset);
    con.Close();
    return dataset;

}

A: This method just Retrieve the data u wanted and storing it into your dataset
adapter.Fill(dataset); this part is used to fill your dataset with the data u populate out.
So as to pass to your stored procedure so technically your stored procedure is doing the insert not this.In your stored procedure u should have a insert statement
If the stored procedure is in your database stored procedure folder u do not need to use adapter as it will run internally to retrieve the results
something like this
INSERT INTO msdb.dbo.db(db)
        VALUES (@dbdata)


text:
Q: Per instance widget preferences VS app preferences My app is currently using a subclass of PreferencesActivity for its preferences.
I am in the process of adding widgets, where each instance has its own preferences (I also offer multiple widget sizes, which means multiple subclasses of AppWidgetProvider).
The widgets and the app share most of their preferences, the widget actually supporting a few items less.
In the process of writing the widget configurator activity, I am realizing that I need to access a preferences layout which does not exist.
As I understand it, is not possible to access the PreferencesActivity layout in the configurator activity. Does this means that I must create a sepecific preferences layout for the configurator activity ? Do you have any tips on optimizing the overlap between app and widget preferences ?

A: Your configuration activity does not to have to be a PreferenceActivity. Make it a normal Activity and use the SharedPreferences.Editor class to change the preferences the widget uses.


text:
Q: Excel sheet reference formula I have a file with months names as sheet names like,
January, february, march and so on.
And one sheet named "overview".
In total 13 sheets.
If in a cell of "overview" sheet it is written january then it will get data from "january" sheet like ='january'!A2. If the cell contains february then it will get data from "february" sheet like ='february'!A2.
Means cell in overview sheet have any month name and I want to get data from respective sheet.

A: You may use the indirect formula to convert a string to a reference. So, if cell A1 has the value say January which is also a name of the worksheet then you may enter a formula like =INDIRECT(A1 & "!A2") to pull value of cell A2 from January sheet. If the value in range A1 changes to February, the value will now be pulled from February sheet.


text:
Q: Percolation in $Z^2$, problem in the proof of the existence of a critical probability I have a $Z^2$ lattice. Every element $(z_1, z_2) \in Z^2$ is connected to one of its 4 neighbours $(z_1, z_2) + (0,1)$, $(z_1, z_2) + (0,-1)$, $(z_1, z_2) + (1,0)$, $(z_1, z_2) + (-1,0)$ by an edge. The edges can be "open" with a probability $p$ and "closed" with a probability 1-p.
I call $\sigma_n$ the total number of self avoinding walks starting from $(0, 0)$ and composed of $n$ steps through the edges. Then I define the event {$ N_n = k $} = {"the number of SAW composed of n OPEN steps is k"}. My question is: is it correct writing that the probability of this event is the following?
$$
P(N_n = k) = \binom {\sigma_n} {k} (p^n)^k (1-p^n)^{\sigma_n - k }.
$$
This would mean that the events {"this SAW is open"} and {"this other SAW is open"} are all independent one from the other, but I think it should be wrong because some SAWs necessarily share some edge one with the other one. But on the other hand, this is the only way I am able to justify the last equality in the following expression, which I find in many text books of percolation theory,
$$
P( N_n \geq 1) = \sum_{k=1}^{\sigma_n} P(N_n =k) \leq \sum_{k=1}^{\sigma_n} k P(N_n = k) =E[N_n] = p^n \sigma_n.
$$
where E is the expectation. Could anyone help me to clarify this point?

A: I think your formula for $P(N_n=k)$ is false because as you said, paths are dependent on one-another. With that said:
Expectation is linear, regardless of dependence. Let $S_n$ be the index of set of SAWs of length $n$ and $\gamma_{ni}$ denote a self avoiding path of length $n$, $i\in S_n$. You write
$$N_n=\sum_{i\in S_n} 1_{\gamma_{ni}}$$
Now you note that each $\gamma_{ni}$ has probability $p^n$ and $S_n$ has $\sigma_n$ elements in it. Using $E[1_{\gamma_{ni}}]=p^n$, it immediately follows that $E[N_n]=p^n\sigma_n$.


text:
Q: How should i design pagination component with async in javascript? How should i design javascript pagination component by async?
I want to synchronized http request/respone.
Because the pagination component must need total data count to figure out page count when component was created and initialized(like in constructer).
So the total data count is in my web server(or db) so i http requested total data count. But it was async api, so the code will not blocked when i request total data count to server. It must be blocked and dispose with synchronize.(because if component can't know total data count, then it can't initialized.
Below is my component code.
function ComponentPagination(paginationAreaID, pageViewDataCount ,
getTotalDataCountApiUrl)
{
this.OnUpdatePagingCallBack = null;

//div
var paginationArea = document.getElementById(paginationAreaID);
paginationArea.classList.add("component-pagination-area");

//prev button
var prevBtn = document.createElement("a");
prevBtn.textContent = "Prev";
paginationArea.appendChild(prevBtn);

//page buttons
var totalDataCount = getTotalDataCount();
if (totalDataCount == null) //If error occur
    totalDataCount = 0;

var pageCount = (totalDataCount / pageViewDataCount);

for (var i = 0; i < pageCount; ++i) {
    var pageBtn = document.createElement("a");
    pageBtn.textContent = (i + 1) + "";
    pageBtn.addEventListener("click", function (event) {

        if (this.OnUpdatePagingCallBack == null) {
            console.log("[Component Pagination Error] You must register
                update paging callback function!");
            return;

        }

        var curClickedPage = event.target.textContent
        axios.get(getTotalDataCountApiUrl)
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log("[Component Pagination Error] " + error);
            });

    }.bind(this));

    paginationArea.appendChild(pageBtn);
}

//Next Button
var nextBtn = document.createElement("a");
nextBtn.textContent = "Next"
paginationArea.appendChild(nextBtn);

/* Private Function */
function getTotalDataCount()
{

    this.totalDataCount = 0;
    axios.get('/API/TestAPI/GetTotalFileCount') //hard coded for test
        .then(function (response) {
            this.totalDataCount = response.data;
        }.bind(this))
        .catch(function (error) {
            console.log("[Component Pagination Error] " + error);
        });

    return this.totalDataCount;
}

/* Call Back */
this.registerUpdatePagingCallBack = function(onUpdatePagingMethod)
{
    if (typeof onUpdatePagingMethod != "function")
    {
        console.log("[Component Pagination Error] You must pass only function
         to registerUpdatePagingCallBack method's parameter");
        return;
    }
    this.OnUpdatePagingCallBack = onUpdatePagingMethod;

}
}

And then i use this like below in window.onload = function().
 var fileListPaginationer = new ComponentPagination("blocked-file-view-
 pagination-area", 10, "/API/TestAPI/GetTotalFileCount");
 fileListPaginationer.registerUpdatePagingCallBack(function ()
 {
     /* This function will call when paging button clicked or updated.
        Parameters will passed like (clickedPageIndex)
        User dispose real pagination data like file list table...(etc)
      */
 });

JavaScript developers usually say that java script event or request must be run with async,  but i have no idea that i can't know total data count in component initializing time.
Well... maybe show loading... message until request/response total data count will be the way of this problem...
If Possible i want to initialize pagination component in initialize time.
(like window.onload)
(ps: I think the loading message is a little bit burdensome.)
May i have some suggestion about design this pagination component?
I had never designed library or component with async.


text:
Q: multiple instances of Swingbuilder? I'm a little late to the Groovy party (like most other parties) and the documentation I've been able to find online about SwingBuilder is somewhat limited.  I am trying to build a gaming application in Groovy (converting my current Java code to Groovy).  In Java I have a JFrame and multiple JPanels which include labels and text fields and buttons and all the other fun swing items that you can use in building a GUI.
The code for all this can be cumbersome, having to declare variables for each JButton and JPanel and so on and so forth, so naturally when I discovered SwingBuilder in groovy just days ago I was ecstatic.
However, the examples are somewhat limited.  So here is my inital code.
def Game(){
    mainMenu = new MainMenuPanel()
    gPane = new SwingBuilder()
    gPane.edt{
        frame(size:[1024,768],
            defaultCloseOperation: JFrame.EXIT_ON_CLOSE, location:[75,50], show:true, pack:false){
            container(container:mainMenu){}
            widget(mainMenu)
            }
        }
    }
    mainMenu.shell.show()
}

in MainMenuPanel I have this code
class MainMenuPanel extends JPanel implements ActionListener, KeyListener, ItemListener {
    public shell
shell = new SwingBuilder()
    shell.panel(id: "mainM",/*size:[512, 354],
    shell.edt{frame(show:true){panel(size:[512, 354],
            layout: new GridLayout(cols:1, rows: 7),*/
            visible:true, constraints: BL.NORTH){

            textLabel = label(text: "Welcome Travelers", horizontalAlignment: 0)
            speak = button(CreateButton("Say Hello", 83),
                actionPerformed:{ shell.optionPane(message: "Hello World").createDialog(null, "Hello").show()})
            }
        }

When I run the groovy script I get an JFrame, with nothing in it.  I've tried various combinations of this code, sometimes I get two frames, but they are not nested inside each other.  Most of the time I get a lot of nothing.
The purpose of what I'm trying to do is have a MainMenu class that returns a Menu Panel that has functionality to control that panel, and have various other classes that also return Panels that do other various things and nest them all in the Pane.
Is it possible to do this?  Am I missing something here?

A: I believe this is functionally similar to what you have above:
import groovy.swing.SwingBuilder

def mainMenu = { builder ->
  builder.panel( id:'mainM' ) {
    label( text: 'Welcome Travelers' )
    button( text: 'Say Hello', actionPerformed:{
      builder.optionPane( message:'Hello World' )
             .createDialog( null, 'Hello' )
             .show()
    } )
  }
}

new SwingBuilder().with { builder ->
  builder.edt {
    frame( size:[ 1024, 768 ], show:true ) {
      panel()
      mainMenu( builder )
    }
  }
}

Hope it helps?


text:
Q: TinyMce copies the classes from the current block element when pressing Return When using tinyMce in Wordpress, In the visual editor, I'f I'm entering content in an element and press return the classes from the parent element are copied over, i would want simply to create a new
 element.
For example, I'm editing

d aasdas d

Then i press return and the following is added:

where i would want only to add

I have forced_root_block option set to p

A: This is tinymce default behaviour.
You could add a tinymce handler to your editor that gets triggered by the keyup event. Testing for charCode 13 you can detect if ENTER has been pressed. If so you could remove the classes from the actual paragraph in the editor:
$(tinymce.get('youreditor_id').getNode()).closest('p').removeAttr('class');

A: This might be the solution to this problem:
tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  keep_styles: false
});

tinymce - content filtering docs

A: The complete answer, based on @thariama post is
        tinyMCE.editors.content.on('keyup',function(e){
            if ( 13 === e.keyCode ) {
               $(tinyMCE.editors.content.selection.getNode()).closest('p').removeAttr('class');
            }
        });


text:
Q: Move a SKNode around a circle i am moving my sknode around a circle created with this code:
    circleDiameter = 300;
    pathCenterPoint = CGPointMake(self.position.x - circleDiameter/2, self.position.y - circleDiameter/2);

    UIBezierPath *circlePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(pathCenterPoint.x, pathCenterPoint.y, circleDiameter, circleDiameter) cornerRadius:circleDiameter/2];
    self.actionClockwise = [SKAction followPath:circlePath.CGPath asOffset:false orientToPath:true duration:2];
    self.circleActionForever = [SKAction repeatActionForever:self.actionClockwise];
    [self runAction:self.actionCounterClockwise withKey:@"circleActionForever"];

And everything is working. Now i want that when an user tap on the screen to revert the direction and move the node in counterClockwise. I did that by running the same action with .reversedAction command.
But the action always restart from the start point.
I want to know if there is some kind of method to make start the animation from the point where the old animation is when the user tap on the screen?

A: A UIBezierPath is composed by path Elements where the first is moveToPoint that , as explained in the official document, starts a new subpath at a specified location in a mutable graphics path.
So, unfortunately is not enough doing:
UIBezierPath *circlePathReversed = [circlePath bezierPathByReversingPath];

because when you stop your circle from following the path, the actual position of the circle is not the same of the moveToPoint point (coordinates x and y).
However you could rebuild your path retrieving all elements and re-starting from the actual circle position.
void MyCGPathApplierFunc (void *info, const CGPathElement *element) {
    NSMutableArray *bezierPoints = (__bridge NSMutableArray *)info;

    CGPoint *points = element->points;
    CGPathElementType type = element->type;

    switch(type) {
        case kCGPathElementMoveToPoint: // contains 1 point
            [bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
            break;

        case kCGPathElementAddLineToPoint: // contains 1 point
            [bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
            break;

        case kCGPathElementAddQuadCurveToPoint: // contains 2 points
            [bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
            [bezierPoints addObject:[NSValue valueWithCGPoint:points[1]]];
            break;

        case kCGPathElementAddCurveToPoint: // contains 3 points
            [bezierPoints addObject:[NSValue valueWithCGPoint:points[0]]];
            [bezierPoints addObject:[NSValue valueWithCGPoint:points[1]]];
            [bezierPoints addObject:[NSValue valueWithCGPoint:points[2]]];
            break;

        case kCGPathElementCloseSubpath: // contains no point
            break;
    }
}

Usage:
NSMutableArray *bezierPoints = [NSMutableArray array];
CGPathApply(circlePath.CGPath, bezierPoints, MyCGPathApplierFunc);


text:
Q: The message exceeds the maximum supported size I'm using Microsoft.Office365.OutlookServices.OutlookServicesClient from Microsoft.Office365.OutlookServices library to work with Office 365 Outlook AAD.
When I try to get one of messages by its message-ID an error occurs :

"{"error":{"code":"ErrorMessageSizeExceeded","message":"The message exceeds the maximum supported size., The message exceeds the maximum supported size."}}".

Is there any way to fix this error?
Here is the code below that I use to get a message:
var messageQuery = m_user.Messages[messageSummary.MessageId];
IMessage message = await messageQuery.ExecuteAsync();

Thanks


text:
Q: Custom list formatting not visible in list preview I changed the formatting of a text column in a list, added a few, very basic formatting:
{
    "$schema": "http://columnformatting.sharepointpnp.com/columnFormattingSchema.json",
    "debugMode": true,
    "elmType": "div",
    "txtContent": "@currentField",
    "style": {
                    "width": "80px",
                    "background-color": "#189bdb",
                    "float": "left",
                    "color": "#fff",
                    "padding": "5px",
                    "margin-right": "10px",
                    "flex": "1",
                    "height": "80px"
    }

 }

Then I added a list preview web part to my page (modern site), selected the list, but the format change is not visible. How can I present the new format with the list preview web part?

A: Currently, the Modern list view webpart is still in preview. So, couple of stuff like json column formatting is not supported at the moment.
Seems like obvious choice to me since we will, quite often, need to format the columns, but looks like we are gonna have to wait.
There's a uservoice request, would suggest that you upvote it so that it can picked by MS team in their future updates. There's no ETA to this.
UserVoice link - Column formatting in list view webpart
If you do indeed want to display list columns like that, you should develop a custom SPFx webpart where you will be in full control of the UI.


text:
Q: Create a column with varchar(max) rather than varchar(8000) How can I create a column in a table and specify it as varchar(max) when using servicestack ormlite?
Currently I execute some sql after the table create to get what I want.
I've seen the StringLength attribute but was wondering if there's a nicer way of doing it?
Something like
StringLength(Sql.VarcharMax)

Thanks

A: Worked around the issue by doing the following
 if (!db.TableExists(typeof(Entity).Name))
 {
   db.CreateTableIfNotExists<Entity>();
   db.ExecuteSql("ALTER TABLE Entity ALTER COLUMN Column VARCHAR(MAX)");
 }

A: Decorate your domain model with System.ComponentModel.DataAnnotations.StringLengthAttribute
such as
[StringLengthAttribute(8001)]
public string Markdown { get;set; }

or
[StringLength(Int32.MaxValue)]
public string Markdown { get;set; }

using any length greater than 8000 to exceed to maximum length of Sql Server varchar/nvarchar column types that required the MAX declaration.
Use a custom dialect provider the understands the MAX declaration.
public class MaxSqlProvider : SqlServerOrmLiteDialectProvider
{
  public new static readonly MaxSqlProvider Instance = new MaxSqlProvider ();

  public override string GetColumnDefinition(string fieldName, Type fieldType,
            bool isPrimaryKey, bool autoIncrement, bool isNullable,
            int? fieldLength, int? scale, string defaultValue)
  {
     var fieldDefinition = base.GetColumnDefinition(fieldName, fieldType,
                                    isPrimaryKey, autoIncrement, isNullable,
                                    fieldLength, scale, defaultValue);

     if (fieldType == typeof (string) && fieldLength > 8000)
     {
       var orig = string.Format(StringLengthColumnDefinitionFormat, fieldLength);
       var max = string.Format(StringLengthColumnDefinitionFormat, "MAX");

       fieldDefinition = fieldDefinition.Replace(orig, max);
     }

     return fieldDefinition;
  }
}

Use the provider when you construct the database factory
var dbFactory = new OrmLiteConnectionFactory(conStr, MaxSqlProvider.Instance);

Note this illustration is specifically targeting SqlServer but it would be relevant for other data providers with minor alterations after inheriting from the desired provider.

A: The column definition of each type can be controlled using OrmLite's Type Converters where the default SqlServerStringConverters will use VARCHAR(MAX) for properties attributed with [StringLength(StringLengthAttribute.MaxText)], e.g:
public class PocoTable
{
    public int Id { get; set; }

    [StringLength(StringLengthAttribute.MaxText)]
    public string MaxText { get; set; }

    [StringLength(256)]
    public string SmallText { get; set; }
}

Using StringLengthAttribute.MaxText (or its alias int.MaxValue) will automatically use the most appropriate datatype for storing large strings in each RDBMS.

A: It appears that ServiceStack has addressed this with a feature to further customize the creation type of fields, see: https://github.com/ServiceStack/ServiceStack.OrmLite#custom-field-declarations
or as detailed at that link:

The [CustomField] attribute can be used for specifying custom field declarations in the generated Create table DDL statements, e.g.:

public class PocoTable
{
    public int Id { get; set; }

    [CustomField("CHAR(20)")]
    public string CharColumn { get; set; }

    [CustomField("DECIMAL(18,4)")]
    public decimal? DecimalColumn { get; set; }
}

Where
db.CreateTable<PocoTable>();

Generates and executes the following SQL:
CREATE TABLE "PocoTable"
(
  "Id" INTEGER PRIMARY KEY,
  "CharColumn" CHAR(20) NULL,
  "DecimalColumn" DECIMAL(18,4) NULL
);

Again however, as per my comment o one of the previous answers, I am guessing that this is probably db-specific, sorry, I don't have easy access to several db servers to test.


text:
Q: how can i fix this problem with pip on osx? I am trying all day to reinstall pip or pip3
I always have the same problem when i try to run it:
    Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/bin/pip", line 6, in <module>
    from pkg_resources import load_entry_point
ImportError: cannot import name 'load_entry_point'

I tried to uninstall and reinstall pip with curl and then with easy_install and now it's a big mess.
I am on the last Mac-osx release
I guess i should remove pip and pip3 completely, but how?


text:
Q: What is the meaning of `1:` in the version of a yum package? I have an Amazon linux machine. When I run yum list installed to list all the versions of the packages I've installed, I see one line saying
pkgconfig.x86_64                       1:0.27.1-2.7.amzn1                 installed

Why does the version starts with 1:? What does it mean? I haven't seen any version like this before.
If I run sudo yum install pkgconfig-1:0.27.1-2.7.amzn1, I got an error saying No package pkgconfig-1:0.27.1-2.7.amzn1 available..
However, I can run sudo yum install pkgconfig-0.27.1-2.7.amzn1 to correctly install pkgconfig whose version is 0.27.1-2.7.amzn1.
What does 1: mean in the version?

A: this is the epoch number.
It somehow overrides the version numbers: 3.0.0 < 1:1.0.0 < 2:0.1.0 etc. This would allow developers to change their numbering scheme but keep the updates going. yum mostly prints the epoch, but doesn't accept it as input on most of his commands. It can be a little bit disturbing, yes :)


text:
Q: Upload Document to CloudSearch, treats my JSON as a string I'm trying to upload my documents of data to CloudSearch. I'm uploading the data in a file called test.json and it has the following content.
[
    {
        "type": "add",
        "id": "1-1",
        "fields": {
            "id": 1,
            "type": 1,
            "address": "Moeboda 4",
            "city": "Alvesta",
            "country": "Sweden",
            "rooms": 3,
            "size": 45,
            "price": 275000
        }
    }
]

I run into the following problems:

*

*CloudSearch tells me that the only fields uploaded are:
content, content_encoding, content_type, resourcename

*When I download the "Batch" that was generated I get the following data in it:
[ {
    "type" : "add",
    "id" : "test.json",
    "fields" : {
        "content" : "[\r\n\t{\r\n\t\t\"type\": \"add\", \r\n\t\t\"id\": \"1-1\", \r\n\t\t\"fields\": {\r\n\t\t\t\"id\": 1,\r\n\t\t\t\"type\": 1,\r\n\t\t\t\"address\": \"Moeboda 4\",\r\n\t\t\t\"city\": \"Alvesta\",\r\n\t\t\t\"country\": \"Sweden\",\r\n\t\t\t\"rooms\": 3,\r\n\t\t\t\"size\": 45,\r\n\t\t\t\"price\": 275000\r\n\t\t}\r\n\t}\r\n]",
        "resourcename" : "test.json",
        "content_encoding" : "UTF-8",
        "content_type" : "application/json"
    }
} ]

So what I'm guessing is that AWS CloudSearch think my JSON is a string, so it creates a new file with its now fields (content, resourcename, content_encoding, content_type) and populates it with my "string" and then also escapes it since the strings should be escaped.
I have no idea why this is happening and I have been working on it for hours. I've been trying .txt files, .json, changing charsets, removing brackets and so on but nothing works.
And yes, I have set Index Options where I have set all the fields I'm trying to upload. See screenshot:

A: This issue was related to the character encoding of the .py file. When "forced" the save to be UTF-8 it worked. I think my editor had saved it as "UTF-8 with BOM".
So if you run into this issue. Tripple check your encodings and charsets.


text:
Q: How to set clang-cl to c++14 or c++1z? I've tried to set clang-cl arguments with -std=c++14, -std=c++1z, -std=c++1y. And they don't work. I am using clang 3.7 pre-build for windows x64 and VS 2015.

A: The Clang page linked below claims -std=c++11, -std=c++14 as well as -std=c++1z are all supported commands. Now considering that clang-cl is, as far as I know, clang --driver-mode=cl which aims to emulate MSVC cl.exe. I can't see why this would eliminate support for platform agnostic features like c++ standards.
http://clang.llvm.org/cxx_status.html
EDIT: In another post on this same topic, it was mentioned that in order to pass arguments to clang itself when in clang-cl mode you must use:
-Xclang <arg>         Pass <arg> to the clang compiler
This is referenced here:
http://clang.llvm.org/docs/UsersManual.html#clang-cl

A: I don't believe that -std=c++14 is supposed to work. Clang-cl is a separate driver for clang (not that separate as it is just a rename of clang), which supports the MSVC arguments instead of the GCC arguments.
An overview of all supported command line arguments which are supported can be found here, which doesn't contain this flag.
From my understanding, clang-cl takes over the C++ features supported by MSVC instead of using the standard (+ some extensions not supported by MSVC). This is especially important as MSVC (pre-2015) did not differentiate on standard, making for instance MSVC 2013 contain features from c++11, c++14 and c++17, while other features from these same standards ain't supported or ain't working correctly.
So to be able to support compilation of MSVC, clang can't support the -std=c++11 flag without breaking compilation. (Though it might be what you want)
That said, MSVC 2015 supports /std:c++14, so possibly clang-cl should be supported for this too. (Sounds like a bug/feature request)


text:
Q: How to force close/refresh the app's shortcuts menu? I have an App Shortcut (See:App shortcuts overview ) that calls an activity that immidietly calls finish() (after changing a small thing in the shareprefs).
so when I click on the shortcut - everything works, but the shortcut menu remains open. [The user doesn't notice the activity opening and closing and stays on the homescreen - with the shortcuts menu still open]
can I force close/force refresh it somehow?
[this gets annoying since I want to dynamically change the text of the shortvcut but this doesnt change unless i close this menu and re opens it]

A: well this is not the perfect answer
but this will suffice the purpose
instead of calling :
finish();

call this code after you change your shared preferences :
Intent goToHomeIntent = new Intent(Intent.ACTION_MAIN);
goToHomeIntent.addCategory(Intent.CATEGORY_HOME);
goToHomeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(goToHomeIntent);

what this does is that it takes the user to home screen of device
hope it helps
happy coding :)


text:
Q: Using the react-router trailing path for active navlink class I'm trying to use react router 4's URL to determine how a certain views data should be sorted.
(Nav Image)

So each of these nav links all goes to the same page they just change the parameter at the end. For example.
/home/:general
/home/:bikini
/home/:lingerie
etc.
This works but the activeClassName parameter is applied to them all

Is there a way to make a NavLink only apply the styles to the links with the EXACT link.
The Routing Component
import React from 'react';
import {Switch, Route, Redirect} from 'react-router';

import Home from './views/home/Home';

const CurrentDash = () => (
      <Switch>
          <Redirect exact={true} from='/' to='/home/:general' />
          <Route path='/home' component={Home} />
      </Switch>
);

export default CurrentDash;

A snippet of some of the NavLinks
  <NavigationLinkWrapper>
              <NavigationLink>
                <NavLink exact strict to='/home/:bikini' activeClassName='navigation-link--active'>Bikini</NavLink>
              </NavigationLink>
            </NavigationLinkWrapper>

            <NavigationLinkWrapper>
              <NavigationLink>
                <NavLink exact strict to='/home/:lingerie' activeClassName='navigation-link--active'>Lingerie</NavLink>
              </NavigationLink>
            </NavigationLinkWrapper>

            <NavigationLinkWrapper>
              <NavigationLink>
                <NavLink exact strict to='/home/:makeup' activeClassName='navigation-link--active'>Makeup</NavLink>
              </NavigationLink>
            </NavigationLinkWrapper>

I know this is happening because this is in the /home route and all the links think they would show but I thought if I included the exact and strict parameters to them then they would show the specific nav-items only. Should I be going about this another way?

A: you must use this link methode synatx my friend for geeting a dynamic routing
 <NavigationLinkWrapper>
          <NavigationLink>
            <NavLink exact strict to={`/home/${data.id}`} activeClassName='navigation-link--active'>Lingerie</NavLink>
          </NavigationLink>
        </NavigationLinkWrapper>


text:
Q: Storing and fetching user details I am working on an app that allows multiple user login.Logged in users can store certain details locally and he must view these details next time he log in.
 I did the login part using core data.But i am completely clueless on storing and fetching the detais of a particular user.Please help me out or suggest me a good tutorial for the same.

A: You can read this tutorial or other.
I talk to you, what you must doing:
You need to create an entity "User" (for example) in your appDataModel.momd file. To "User" you can add attributes which you need to use later (for example: name, id, age etc.). Now you must create your entity classes User.h and User.m (look tutorials), import User.h to class, where you will create fetch request and create it (fetch request) in some method (look in tutorials).
To create exemplar of entity:
(User_John for example)
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = appDelegate.managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];

User *User_John = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; //create variable of new user
User_John.name=@"John";
User_John.age=23;
User_John.id=1;

To change user parameters you need just use setter method:
User_John.age=24;

OR:
[User_John setValue:24 forKey:@"age"];


text:
Q: Get the reduced or increased working hours I need to get the reduced or increased working hours, starter and leavers from employee list for previous compare to current month for the last 12 month.
The problem I have is I don't get any leavers which was on previous month but current month the working hours is null so called leavers.

here is what I have tried:
WITH CURRENTbase AS
(
    SELECT Employee, Work_hrs,monthdate
    FROM MyTable
    WHERE monthlydate >= '2020-mar-01'
),
PREVIOUSbase AS
(
    SELECT Employee, Work_hrs,monthdate
    DATEADD(MONTH,1,monthdate) monthdate
    FROM MyTable
    WHERE  monthdate >= '2020-mar-01'
)
SELECT
    B.*, A.*,
    A.monthdate,
    ISNULL(B.Work_hrs,0) PreviousHRS,
    ISNULL(A.Work_hrs,0) CurrentHRS,
    CASE
        WHEN b.Work_hrs is null THEN 'Starter'
        WHEN a.Work_hrs is null THEN 'Leaver'
        WHEN a.Work_hrs > b.Work_hrs THEN 'hrs_Increase'
        WHEN b.Work_hrs > a.Work_hrs THEN 'hrs_Decrease'
        WHEN b.Work_hrs = a.Work_hrs THEN 'NoChange'
        ELSE 'Check'
    END Status
FROM CURRENTbase A

LEFT JOIN PREVIOUSbase B
    ON A.Employee = B.Employee AND A.monthdate = B.monthdate

WHERE a.CensusDate >= '2020-apr-01'

GROUP BY
    A.monthdate,
    ISNULL(B.Work_hrs,0) PreviousHRS,
    ISNULL(A.Work_hrs,0) CurrentHRS,
    CASE
        WHEN b.Work_hrs is null THEN 'Starter'
        WHEN a.Work_hrs is null THEN 'Leaver'
        WHEN a.Work_hrs > b.Work_hrs THEN 'hrs_Increase'
        WHEN b.Work_hrs > a.Work_hrs THEN 'hrs_Decrease'
        WHEN b.Work_hrs = a.Work_hrs THEN 'NoCHange'
        ELSE 'check'
    END

A: You can try this query if you use MS SQL SERVER 2012 or above, adopt the order by to suite your needs
SELECT *
  ,CASE
      WHEN LEAD(WORKING_HOURS) OVER (
              PARTITION BY Employee ORDER BY Year DESC
                  ,Month DESC
              ) IS NULL
          THEN 'Starter'
      WHEN LEAD(WORKING_HOURS) OVER (
            PARTITION BY Employee ORDER BY Year ASC
                ,Month ASC
            ) IS NULL
        THEN 'Leaver'
      WHEN LEAD(WORKING_HOURS) OVER (
            PARTITION BY Employee ORDER BY Year ASC
                ,Month ASC
            ) > LEAD(WORKING_HOURS) OVER (
            PARTITION BY Employee ORDER BY Year DESC
                ,Month DESC
            )
        THEN 'hrs_Increase'
      WHEN LEAD(WORKING_HOURS) OVER (
            PARTITION BY Employee ORDER BY Year DESC
                ,Month DESC
            ) > LEAD(WORKING_HOURS) OVER (
            PARTITION BY Employee ORDER BY Year ASC
                ,Month ASC
            )
        THEN 'hrs_Decrease'
      WHEN LEAD(WORKING_HOURS) OVER (
            PARTITION BY Employee ORDER BY Year DESC
                ,Month DESC
            ) = LEAD(WORKING_HOURS) OVER (
            PARTITION BY Employee ORDER BY Year ASC
                ,Month ASC
            )
        THEN 'NoCHange'
      ELSE 'check'
      END
 FROM (
     SELECT Employee
        ,MONTH(monthdate) Month
        ,YEAR(monthdate) Year
        ,SUM(Work_hrs) AS WORKING_HOURS
    FROM MyTable
    GROUP BY Employee
       ,MONTH(monthdate)
       ,YEAR(monthdate)
  ) a


text:
Q: What's the natural way to ask about the current degrees of the weather? What's the natural way to ask about degrees of the weather?
Can I ask: "What's the temperature?" or "What's the weather like now?" and people will understand I'm asking the degrees?
Asking "How many degrees of Celsius are now?" or "How many degrees are now?" are natural? Or maybe another way to ask appropriately what I want.

A: Asking "what's the temperature?" or "what's the temperature outside? are both perfectly normal. However, your response will almost certainly be in Fahrenheit if you are in the U.S. If you are in the U.S. and you need to ask specifically for the temperature in Celsius, the best way would be to ask, "what's the temperature in Celsius?"
This would be a shortened and casual way of asking "what is the current local temperature measured in Celsius?" However, it can be assumed in casual conversation that you are asking for the temperate here and now and that Celsius is a unit of measurement.
Therefore, you can simply ask: "what's the temperature in Celsius?"

A: Weather doesn't have degrees, it has states and conditions.
If you ask what the weather is like, you'll likely get a response similar to the following:

It's (windy, raining, sunny, snowing, hot, cold).

It would be unusual to get a response with the actual temperature unless it's something particularly noteworthy:

"You wouldn't believe how hot it is! It's up to 35°C / 95°F!"

If the temperature is specifically what you want to know, then you should ask about it specifically:

"What's the temperature?"

A: Cambridge Dictionary defines temperature as:

the measured amount of heat in a place or in the body.

When you are asking about the temperature outside, it simply means that you are asking for the degree of the heat outside.
Whereas Cambridge Dictionary defines weather as:

the conditions in the air above the earth such as wind, rain, or temperature, especially at a particular time over a particular area.

When someone asks for the weather outside, that person is generally asking if it's hazy, windy or rainy. Weather is a broader term which includes temperature and other units such as humidity, precipitation, cloudiness and visibility.

A: "What's the temperature outside?" would be a totally natural way to ask this. You can shorten this to just "What's the temperature?" if you think it's clear that you're talking about the temperature outside. You can also add "now" or "right now" if you want.
If you know that it's cold outside, it would also sound totally natural to ask "How cold is it outside?"; and likewise, if it's hot, you can ask "How hot is it outside?"
"How many degrees are now?" sounds ungrammatical. On the other hand, the question "How many degrees are there now?" would be grammatical—but it's still incorrect! After all, we don't say "There are 30 degrees outside"; we say "It's 30 degrees outside". So you can't ask about "how many degrees there are".
You could ask "How many degrees is it now?", and that wouldn't be incorrect—but it's just not something people say. If you ask the question that way, people will think that maybe you don't know the word "temperature".
In summary:

*

*What's the temperature outside? – good

*How cold is it outside? – good if it's cold outside

*How hot is it outside? – good if it's hot outside

*How many degrees are now? – ungrammatical

*How many degrees are there now? – incorrect (but not ungrammatical)

*How many degrees is it now? – sounds strange (but not incorrect)