text:
Q: How to append web request results in a while loop I need to call an API and loop through the various pages of results that are returned and append them all to one object.
I've tried the code below. Generally += works when appending to a powershell object, but no luck this time.
Note: URI and Get are both functions that are defined elsewhere. They work as expected elsewhere in the code.
$min=1
$max=2

while ($min -le $max){
    $url= URI "tasks?page=$min"
    $x=Get $url
    if($min=1){
        $response=$x
    }
    else{
        $response+=$x
    }

    $min=$min+1
}

sample response (converted to json):
  "value": [
    {
      "task_id": 17709655,
      "project_id": 1928619,
      "start_date": "2019-04-11",
      "end_date": "2019-11-29",
      "start_time": null,
      "hours": 1.5,
      "people_id": 17083963,
      "status": 2,
      "priority": 0,
      "name": "",
      "notes": "",
      "repeat_state": 0,
      "repeat_end_date": null,
      "created_by": 331791,
      "modified_by": 0,
      "created": "2019-04-12 00:39:30.162",
      "modified": "2019-04-12 00:39:30.162",
      "ext_calendar_id": null,
      "ext_calendar_event_id": null,
      "ext_calendar_recur_id": null
    },
    {
      "task_id": 17697564,
      "project_id": 1928613,
      "start_date": "2019-10-08",
      "end_date": "2019-10-08",
      "start_time": null,
      "hours": 8,
      "people_id": 17083966,
      "status": 2,
      "priority": 0,
      "name": "",
      "notes": "",
      "repeat_state": 0,
      "repeat_end_date": null,
      "created_by": 327507,
      "modified_by": 0,
      "created": "2019-04-11 16:10:22.969",
      "modified": "2019-04-11 16:10:22.969",
      "ext_calendar_id": null,
      "ext_calendar_event_id": null,
      "ext_calendar_recur_id": null
    }
  ],
  "Count": 2
}```

A: Assuming you want the output to be an array, I'd write your code like this:
$min=1
$max=2

$response = foreach ($Page in $min..$max) {
    $url = URI "tasks?page=$Page"
    Get $url
}

This is the generally preferred method, because both Strings and Arrays have fixed lengths in .Net and therefore PowerShell.
Here, $response[0] should be the first response, $response[1] the second, etc.
If the above doesn't work for you, then my first guess would be that the output of Get isn't a string.
If you're expecting $response to be a single valid JSON string containing all the responses, then my response is "JSON doesn't work that way." You'll have to parse each JSON response to objects (hint: ConvertFrom-Json) combine them, and then possibly convert them back to JSON (ConvertTo-Json). Note that .Net's native dialect of JSON doesn't match the rest of the Internet's dialect of JSON, particularly with dates (though it looks like your dates here are strings). You may want to use JSON.Net, which I believe does match the common Internet dialect.
You may be able to combine $response like this:
$CombinedResponse = '[' + ($response -join ',') + ']'

But I don't know how well that's going to work if you then try to parse that as JSON.


text:
Q: How to send one pull request per separate commit? I forked a project. I worked on it for a bit.
I now have ten different commits, each of which is independent of the other commits.
I'd like to send each individual commit as a separate pull request, to let the maintainer of the upstream choose which ones he/she wants.
I can't find an easy way to do this.
The "easiest" I can find is to create ten separate branches, and cherry-pick each of the ten separate commits into those branches, and then send a pull request from each.
That's ... not sane!
(See for example how to divide one pull request into two different pull request on github )
The underlying git request-pull function supports this workflow, so is the problem here that GitHub just doesn't have a good interface to this? Am I doomed to create ten branches?

A: GitHub's Pull Requests are designed to be per-branch, not per-commit. This is deliberate:

After your pull request is sent, any new commits pushed to your branch will automatically be added to the pull request. This is especially useful if you need to make more changes.

If you want to send ten Pull Requests in GitHub you'll have to do it using ten branches. The only exception would be if you wait for each Pull Request to be merged before submitting the next one.

A: There's a work-around suggested by Grason Koonce that amounts to:
creating successive branches for each piece, and making pull requests against the previous branch point(rather than the target branch).
Once all reviewed and accepted merge in reverse order 5->4, 4->3, 3->2, 2->1, and only then 1->master/target.
It's not pretty but it is a solution.
https://graysonkoonce.com/stacked-pull-requests-keeping-github-diffs-small/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mathematical formulas on a graph (not made by TeX) Let us assume that we have a graph created by a program different from LaTeX (that is not with PStricks or Tikz). I was wandering if it is possible to incorporate mathematical symbols on that graph using a TeX editor.
Thank you.

A: Basically, this is using the example of the stackengine documentation, adapted for use in math mode with the addition of \stackMath in the preamble.
The routine you want is \stackinset which has 6 arguments, \stackinset{H-anchor}{H-offset}{V-anchor}{V-offset}{inset}{underlying anchor image}.  As shown here, it can be nested and the insets themselves can be stacks.
\documentclass[standard]{letter}
\usepackage[usestackEOL]{stackengine}
\stackMath
\usepackage{graphicx}
\def\imgi{\includegraphics[width=.75in]{example-image}}
\begin{document}
\stackinset{l}{ .1in}{b}{.2in}{y=mx+b}{%
\stackinset{r}{ .1in}{t}{.2in}{\Longstack{F_x=ma_x\\F_y=ma_y}}{%
\stackinset{c}{-.5in}{c}{.4in}{E=mc^2}{%
\stackinset{r}{ .8in}{b}{.6in}{\psi^2=0}{%
\stackinset{r}{ .1in}{c}{.0in}{\imgi}{%
\includegraphics[width=3in]{example-image}%
}}}}}
\end{document}


text:
Q: what sort of phrase is "as much money as Mick but not as much as Neil"?
Greg makes as much money as Mick but not as much as Neil.

is it prepositional phrase, noun phrase ,noun clause,gerund phrase,adverb clause ... ?
i.e. noun phrase, verb phrase, adverb phrase, adjective phrase, appositive phrase, infinite phrase, participle phrase and gerund phrase.
why?

A: It's a comparative phrase.
A simile is a figure of speech in which a thing is described by being likened to another, usually using as or like, and usually in a phrase or saying.
So it's not a simile, as it's not likening Greg to something or likening his income to anything: it's simply discussing Greg's income comparative to other people's.
"Greg was as rich as Croesus" is a simile.
"Greg was as poor as a church mouse" is a simile.
"Greg's wealth was like a bathful of water - likely to be drained away at any moment" is an extended simile.

A: It is just a comparative statement.

Greg makes as much money as Mick but not as much as Neil.

This can be broken down to two separate statements.

*

*
Greg makes as much money as Mick

Which means that Greg earns roughly the same amount of money that Mick earns.

*
Greg doesn't make as much money as Neil does.

Which means that Neil has a higher earning when compared to Greg's income.
These two statements are just combined in the first statement.

A: This phrase is an example for combined use of two prepositional phrases joined with another conditional clause to make an assumption or to extract a final meaning from those prepositional phrases.


text:
Q: Flask returns FileNotFoundError: [Errno 2] No such file or directory I have a Flask app that uploads files to AWS S3
This sometimes works and sometimes doesn't work and it's puzzling me:
@app.route('/upload',methods=['post'])
def upload():
    if request.method == 'POST':
        diag_file = request.files['file']
        if diag_file:
            filename = secure_filename(diag_file.filename)
            result = create_presigned_post("bucket123", filename)
            #Open file and load it
            with open(filename, 'rb') as f:
                files = {'file': (filename, f)}
                http_response = requests.post(result['url'], data=result['fields'], files=files)
            # If successful, returns HTTP status code 204
            logging.info(f'File upload HTTP status code: {http_response.status_code}')
            msg = str(create_presigned_url("bucket123", filename))

    return render_template("file_upload_to_s3.html",msg =msg)

I am getting the proverbial FileNotFoundError
Error Message: FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
Full Error Trace:
127.0.0.1 - - [26/Oct/2021 15:25:50] "POST /upload HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/Users/test_user/dev/s3upload/venv/lib/python3.7/site-packages/flask/app.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/test_user/dev/s3upload/venv/lib/python3.7/site-packages/flask/app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/test_user/dev/s3upload/venv/lib/python3.7/site-packages/flask/app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/test_user/dev/s3upload/venv/lib/python3.7/site-packages/flask/app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/test_user/dev/s3upload/venv/lib/python3.7/site-packages/flask/app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/test_user/dev/s3upload/venv/lib/python3.7/site-packages/flask/app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/Users/test_user/dev/s3upload/app.py", line 100, in upload
    with open(filename, 'rb') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

How can I make sure that the file exists?


text:
Q: How to use sklearn.feature_selection with 3D numpy array data I have a 3D data like this (150, 1040, 82) = (frame, feature, num_data) . It is like 3D tensor.
This data is X_data and Y_data is (82,) whole code is under the code.
The labeling_load() function consists of X = 1040, Y = 150, where X is a feature and Y is a frame. And this 2d data finally has the form of (1040, 150, n). And the output result, Y, matches the number of n.
def labeling_load():

 lableing_name = pd.read_excel("data.xlsx")
 pd_labeling_name = pd.DataFrame(lableing_name)

 Y_data = []
 k = 0

 for ID in os.listdir("test_han/"):
    ID_lable = pd_labeling_name["ID"] == str(ID)
    Human_lable = pd_labeling_name["정김령"] == 0
    Final_lable = pd_labeling_name[ID_lable & Human_lable]
    list_final_lable = Final_lable.values.tolist()

    path = "test_han/" + str(ID) + "/"
    file = os.listdir(path)

    list_num_section_m1 = []
    list_num_section_0 = []
    list_num_section_1 = []
    list_num_section_2 = []
    list_num_section_3 = []
    list_num_section_4 = []

    for i in range(len(file)):
        game_state = str(file[i].split("_")[0])
        num_section = str(file[i].split("_")[1].split(".")[0])
        if game_state == "-1":
            list_num_section_m1.append(int(num_section))
        elif game_state == "0":
            list_num_section_0.append(int(num_section))
        elif game_state == "1":
            list_num_section_1.append(int(num_section))
        elif game_state == "2":
            list_num_section_2.append(int(num_section))
        elif game_state == "3":
            list_num_section_3.append(int(num_section))
        elif game_state == "4":
            list_num_section_4.append(int(num_section))

    for j in range(len(list_num_section_m1)):
        if k == 0:
            data_m1 = pd.read_csv(path + "-1_" + str(j) + ".csv")
            data_m1 = data_m1.replace('Nan', -100)
            data_m1 = data_m1.iloc[0:,2:1042]
            # print(m1_data)
            X_data = data_m1.to_numpy()
            # print(np_data_1)
            label_m1 = list_final_lable[0][j+8]
            # print(X_data)
            Y_data.append(label_m1)
            k = 2
        else:
            data_m1 = pd.read_csv(path + "-1_" + str(j) + ".csv")
            data_m1 = data_m1.replace('Nan', -100)
            data_m1 = data_m1.iloc[0:, 2:1042]
            # print(m1_data)
            np_data_m1 = data_m1.to_numpy()

            # print(np_data_1)
            label_m1 = list_final_lable[0][j + 8]

            if label_m1 == 0 or label_m1 == 1:
                if np_data_m1.shape[0] == 150:
                    X_data = np.dstack((X_data, np_data_m1))
                    Y_data.append(label_m1)

    for j in range(len(list_num_section_0)):
        data_0 = pd.read_csv(path + "0_" + str(j) + ".csv")
        data_0 = data_0.replace('Nan', -100)
        data_0 = data_0.iloc[0:, 2:1042]
        # print(m1_data)
        np_data_0 = data_0.to_numpy()
        # print(np_data_1)
        label_0 = list_final_lable[0][j + 54]

        if label_0 == 0 or label_0 == 1:
            if np_data_0.shape[0] == 150:
                X_data = np.dstack((X_data, np_data_0))
                Y_data.append(label_0)

    for j in range(len(list_num_section_1)):
        data_1 = pd.read_csv(path + "1_" + str(j) + ".csv")
        data_1 = data_1.replace('Nan', -100)
        data_1 = data_1.iloc[0:, 2:1042]
        # print(m1_data)
        np_data_1 = data_1.to_numpy()
        # print(np_data_1)
        label_1 = list_final_lable[0][j + 78]

        if label_1 == 0 or label_1 == 1:
            if np_data_1.shape[0] == 150:
                X_data = np.dstack((X_data, np_data_1))
                Y_data.append(label_1)

    for j in range(len(list_num_section_2)):
        data_2 = pd.read_csv(path + "2_" + str(j) + ".csv")
        data_2 = data_2.replace('Nan', -100)
        data_2 = data_2.iloc[0:, 2:1042]
        # print(m1_data)
        np_data_2 = data_2.to_numpy()
        # print(np_data_1)
        label_2 = list_final_lable[0][j + 102]

        if label_2 == 0 or label_2 == 1:
            if np_data_2.shape[0] == 150:
                X_data = np.dstack((X_data, np_data_2))
                Y_data.append(label_2)

    for j in range(len(list_num_section_3)):
        data_3 = pd.read_csv(path + "3_" + str(j) + ".csv")
        data_3 = data_3.replace('Nan', -100)
        data_3 = data_3.iloc[0:, 2:1042]
        # print(m1_data)
        np_data_3 = data_3.to_numpy()
        # print(np_data_1)
        label_3 = list_final_lable[0][j + 126]
        if label_3 == 0 or label_3 == 1:
            if np_data_3.shape[0] == 150:
                X_data = np.dstack((X_data, np_data_3))
                Y_data.append(label_3)

    for j in range(len(list_num_section_4)):
        data_4 = pd.read_csv(path + "4_" + str(j) + ".csv")
        data_4 = data_4.replace('Nan', -100)
        data_4 = data_4.iloc[0:, 2:1042]
        # print(m1_data)
        np_data_4 = data_4.to_numpy()
        # print(np_data_1)
        label_4 = list_final_lable[0][j + 150]
        if label_4 == 0 or label_4 == 1:
            if np_data_4.shape[0] == 150:
                X_data = np.dstack((X_data, np_data_4))
                Y_data.append(label_4)

print(len(X_data), len(Y_data))

X_data = np.array(X_data)
Y_data = np.array(Y_data)

def randomforest2():

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=10)

rf = RandomForestClassifier(n_estimators=100, class_weight='balanced', random_state=10)

rf.fit(X_train, y_train)
importances = rf.feature_importances_

f = open("importance.csv", "w")
wr = csv.writer(f)
wr.writerow(importances)
f.close()

print(len(importances))
print(importances)

indices = np.argsort(importances)[::-1]
plt.figure()
plt.title("Feature importances")
plt.bar(range(X_train.shape[1]), importances[indices],
        color="lightsalmon", align="center")
plt.xlim([-1, X_train.shape[1]])
plt.show()

if __name__ == "__main__":
labeling_load()
X = X_data
y = Y_data

randomforest2()

Error massage is
Traceback (most recent call last):
File "C:\Users\Wonjun\PycharmProjects\ADHD\labeling_load.py", line
228, in <module>
randomforest2()
File "C:\Users\Wonjun\PycharmProjects\ADHD\labeling_load.py", line
195, in randomforest2
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=10)
File "C:\Users\Wonjun\anaconda3\lib\site-
packages\sklearn\model_selection\_split.py", line 2172, in
train_test_split
arrays = indexable(*arrays)
File "C:\Users\Wonjun\anaconda3\lib\site-
packages\sklearn\utils\validation.py", line 356, in indexable
check_consistent_length(*result)
File "C:\Users\Wonjun\anaconda3\lib\site-
packages\sklearn\utils\validation.py", line 319, in
check_consistent_length
raise ValueError("Found input variables with inconsistent numbers of"
ValueError: Found input variables with inconsistent numbers of
samples: [150, 82]


text:
Q: How to use like clause over string separated with comma inside case statement DECLARE @IsSearch_  BIT;
SET @IsSearch_ ='True'
DECLARE @Organization_  VARCHAR(100);
SET @Organization_ ='111,111A'

select *
from VYC20 C20
where (@Organization_ IS NULL)
  OR (1 = CASE @IsSearch_
          WHEN 0 THEN (CASE WHEN @Organization_ IS NOT NULL
                            AND C20.ORG IN
                                (select value
                                from STRING_SPLIT(@Organization_, ','))
                            THEN 1 ELSE 0 END)
          WHEN 1 THEN (CASE WHEN C20.ORG like @Organization_ + '%'
                             THEN 1 ELSE 0 END)
          ELSE 0 END)

In the above query the 1st case WHEN 0 statement with IN clause gives the correct record, but the  WHEN 1 THEN gives me 0 records, can someone please help me how to apply like clause with string separated with comma.

A: It looks like what you actually want is to use LIKE after splitting
DECLARE @IsSearch_  BIT = 1;
DECLARE @Organization_ VARCHAR(100) = '111,111A';

SELECT *
FROM VYC20 C20
WHERE @Organization_ IS NULL
   OR (@IsSearch_ = 0 AND
      C20.ORG IN
          (SELECT s.value
          FROM STRING_SPLIT(@Organization_, ',') s))
   OR (@IsSearch_ = 1 AND
      EXISTS (SELECT 1
          FROM STRING_SPLIT(@Organization_, ',') s
          WHERE C20.ORG LIKE s.value + '%'));

I strongly advise you to do this in a set-based fashion and use a table variable or Table Parameter
DECLARE @IsSearch_  BIT = 1;
DECLARE @Organization_ TABLE (value VARCHAR(100));
INSERT @Organization_ VALUES('111'),('111A');

SELECT *
FROM VYC20 C20
WHERE @IsSearch_ = -1  -- include all
   OR (@IsSearch_ = 0 AND
      C20.ORG IN
          (SELECT s.value
          FROM @Organization_ s))
   OR (@IsSearch_ = 1 AND
      EXISTS (SELECT 1
          FROM @Organization_ s
          WHERE C20.ORG LIKE s.value + '%'));


text:
Q: I like to record video from FMS in another directory I like to record video from my webcam via flash media server 4.
When I try to record the video, flash media server will put the recorded video in it's root's directory. for example (D:\Program Files\Adobe\Flash Media Server 4 applications\sample\streams_definst_\myvideo.flv).
But I need to change this directory to (E:\myvideos\video.flv)
Please kindly advise me.


text:
Q: add properties to a JSON object during iteration? The Mozilla Dev Center says:

it is best not to add, modify, or remove properties from the object
  during iteration, other than the property currently being visited;
  there is no guarantee whether or not an added property will be visited,

However, I have no need to visit the added properties until later. So is it safe to add them?
E.g.
var animals = {"cats":25, "dogs":15}
for(var key in animals){
    if(key.substring(0,3) !=="big"){ // no danger of referencing them
        var newAnimal = "big" + key;
        animals[newAnimal] =0;
    }
}

Or will increasing the size of the object confuse the "for - in" iteration?

A: The docs don't say that the added propterties won't be visited, they say it's undefined.
So depending on the implementation, you may end up with a bigdogs, a bigbigdogs etc., resulting in an endless loop.
Or it may do something completely different, after all, it's undefined behavior.
To solve this, work with a copy of the object instead and add the new properties to the copy without mutating the looped object.
Edit: Looks like you are checking whether the key starts with big, missed that when I first looked at it. So you should be fine.
It is still good practice to avoid undefined behavior like this. This can easily come back and bite you when the code has to be changed at some point in the future and the reasoning behind the loop/check is not absolutely clear.

A: If you don't care that "there is no guarantee whether or not an added property will be visited", then you can do it.
If you want to make sure you won't visit them, make a snapshot of the properties before the loop:

var animals = {"cats":25, "dogs":15}
for(var key of Object.keys(animals))
  animals["big" + key] = 0;
console.log(animals);

If you want to make sure you will visit them, use maps:

var animals = new Map([ ["cats",25], ["dogs",15]]);
for(var key of animals.keys())
  if(key.slice(0,6) !== 'bigbig')
    animals.set("big" + key, 0);
console.log([...animals].map(a => a.join(': ')));

A: Yes it is safe to add them since you have check to make sure you wont end up in an infinite loop.
The "add" adds it in random place so the order is not something you can count on, but looking as you don't need to visit the newly created property in the same loop this should be fine.
I would suggest if you just want to add new property create a new object which will later replace the current object once you are done. Because that way it will have better performance.
Also won't drive the person who is reviewing your code nuts :). Have a good day

A: It's safe
After start the iteration, when

*

*delete an item before visiting , you not see it.

*update an item, you see the new value

*insert an item, you may or may not see it in the current cicle. But that was also safe.

source
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in


text:
Q: [iOS][ReactNative] Undefined symbols for architecture armv7 when building for Generic iOS Device with react-viro Environment

*

*Development OS: MacOS

*Device OS & Version: Xcode 10.2.1 (10E1001)

*Version: react-viro: 2.15.0 & react-native: 0.60.4

Description
I cannot compile my application it throws this error:
ld: warning: ignoring file /Users/loiclopez/app/node_modules/react-viro/ios/dist/ViroRenderer/static_lib/ViroKit_static_lib.framework/ViroKit_static_lib, missing required architecture armv7 in file /Users/loiclopez/app/node_modules/react-viro/ios/dist/ViroRenderer/static_lib/ViroKit_static_lib.framework/ViroKit_static_lib (2 slices)
Undefined symbols for architecture armv7:
  "_OBJC_CLASS_$_VROViewAR", referenced from:
      objc-class-ref in libViroReact.a(VRTARSceneNavigator.o)
      objc-class-ref in libViroReact.a(VRTARUtils.o)
  "_OBJC_CLASS_$_VROViewControllerGVR", referenced from:
      objc-class-ref in libViroReact.a(VRTSceneNavigator.o)
      objc-class-ref in libViroReact.a(VRTVRSceneNavigator.o)
  "_OBJC_CLASS_$_VROViewScene", referenced from:
      objc-class-ref in libViroReact.a(VRT3DSceneNavigator.o)
  "getBlankTexture(VROTextureType)", referenced from:
      -[VRTMaterialManager loadVideoTextureForMaterial:driver:context:] in libViroReact.a(VRTMaterialManager.o)
      -[VRTMaterialVideo updateMaterialVideoTexture] in libViroReact.a(VRTMaterialVideo.o)
  "VROGeometryUtilGetPrimitiveCount(int, VROGeometryPrimitiveType)", referenced from:
      -[VRTGeometry updateGeometry] in libViroReact.a(VRTGeometry.o)
  "toDegrees(float)", referenced from:
      +[VRTARHitTestUtil rotationFromVector:] in libViroReact.a(VRTARHitTestUtil.o)
      ___49-[VRTNodeModule getNodeTransform:resolve:reject:]_block_invoke in libViroReact.a(VRTNodeModule.o)
      -[VRTScene cameraOrientation] in libViroReact.a(VRTScene.o)
      -[VRTScene logSceneDebugInfo:] in libViroReact.a(VRTScene.o)
      -[VRTNode onRotate:node:rotationRadians:rotateState:] in libViroReact.a(VRTNode.o)
      +[VRTARUtils createDictionaryFromAnchor:] in libViroReact.a(VRTARUtils.o)
  "toRadians(float)", referenced from:
      -[VRTNode setRotation:] in libViroReact.a(VRTNode.o)
      -[VRTCamera setRotation:] in libViroReact.a(VRTCamera.o)
      -[VRT360Video setRotation:] in libViroReact.a(VRT360Video.o)
      -[VRT360Video updateSceneWithSphereTexture] in libViroReact.a(VRT360Video.o)
      -[VRT360Image setRotation:] in libViroReact.a(VRT360Image.o)
      -[VRT360Image updateSceneWithSphereTexture] in libViroReact.a(VRT360Image.o)
      ___56-[VRTARSceneNavigatorModule setWorldOrigin:worldOrigin:]_block_invoke in libViroReact.a(VRTARSceneNavigatorModule.o)

  // and more errors...

This issue only occurs when archiving for a release or build for Generic iOS Device.


text:
Q: live real-time collaboration using Emacs? Is there a package or tool that will allow me to do live online collaboration on a text document using Emacs? i.e. a tool that would allow me to connect with another user via the web, both open the same document, display two cursors, allow me to see their cursor and edits in real time, and allow them to see mine?

A: Check out Rudel. I tried it a couple of times and it worked decently. It may not have everything you want (like seeing the other person's cursor), but that's not to say that couldn't be added.

A: For example, Flootbits has Emacs support. You can install corresponding plugin via el-get...


text:
Q: it shows in my reservation calendar this -Notice: Trying to get property of non-object Here is my code. Thankyou. It display like this Notice: Trying to get property of non-object.
 if($result->num_rows > 0){
            $eventListHTML = '
Events on '.date("l, d M Y",strtotime($date)).'
';
            $eventListHTML .= '
';
            while($row = $result->fetch_assoc()){
                $eventListHTML .= '
'.$row['email'].'
';
            }
            $eventListHTML .= '
';
        }
        echo $eventListHTML;
    }


text:
Q: Scanner with GUI I want to make a program cipher using monoaphabetic cipher with java GUI.
But when I click the button to encrypt, the textfield2 won't show the result and make the program crash.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   Scanner sc = new Scanner(System.in);
   String en =  doEncryption(sc.next().toLowerCase());
   jTextField1.setT![enter image description here][1]ext(en);
   jTextField2.setText(doDecryption(en));
   sc.close();
}

A: Don't mix event-driven GUI's with Scanner sc = new Scanner(System.in);. Seriously, just don't do this. This is what the GUI is for, and doing so without considering threading will render your program useless. Understand that sc.next() is a blocking call, a call that blocks the current thread until it completes, and that making this call on the Swing event thread will block the GUI, freezing it. But why even do this when you can get user input through your GUI, through one of your JTextFields or from a JTextArea for instance?
So instead of this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   Scanner sc = new Scanner(System.in);
   String en =  doEncryption(sc.next().toLowerCase());
   jTextField1.setText(en);
   jTextField2.setText(doDecryption(en));
   sc.close();
}

consider doing:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   // Scanner sc = new Scanner(System.in);

   // assuming entryTextArea is a JTextArea for user input:
   String en =  entryTextArea.getText().toLowerCase());
   jTextField1.setText(en);
   jTextField2.setText(doDecryption(en));
   // sc.close();
}


text:
Q: LWC platform events timing out? So I have 2 LWC components, one which publishes a platform event (a text message from an input box) and another one which listens to it and then resposnds by publishing a platform event of its own. When I open the publisher and the receiver components in different tabs to test the communication, everything works fine.
The issue is, that after a while, I guess after 5 minutes or so, If i try to publish another message from the first component, it is not received at the receiver. My gut is that the listening connection is being terminated by the server as said here.
If so, can someone please tell me how to keep the platform event susbcription alive from an LWC component?


text:
Q: How to change file ownership using boost library? I want to change file ownership using boost library, like chown().
Is there any api for this?

A: It doesn't exist. Boost's Filesystem doesn't concern itself with owners (or ACLs, for that matter).


text:
Q: Dart convert whole json tree from base64 I have json where each value is encoded as base64. I want to go trough the whole tree and decode every value. This needs to be automatic. No json key can be specified in the code. It needs to go down itself. How would i go about that?
This is what I have so far
Map<String, dynamic> parseJson(String response) {
  var data = json.decode(response);

  // Here I need to decode from base64

  return data;
}

This is what the json looks like
{
   "app_title":"RnJpU8Okaw==",
   "app_color":"I0ZGRUUzMw==",
   "app_tabs":[
      {
         "title":"RW4gdGl0ZWwgw6XDpMO2w4XDhMOW",
         "content":"CkxpdGUgaW5uZWjDpWxsLiA8YnIgLz4gCjxiPmhlajwvYj4gCjxoMT50ZXN0PC9oMT4KPGEgaHJlZj0iaHR0cDovL2ZyaXNrb2xhLm51Ij5FbiBsw6RuazwvYT4KPGRpdiBzdHlsZT0iY29sb3I6IGdyZWVuIj5MaXRlIGdyw7ZuIHRleHQga2Fuc2tlPzwvZGl2Pgo8aW1nIHNyYz0iaHR0cDovL2ZyaXNrb2xhLm51L2ltYWdlcy9zb2ZyaV9sb2dvdHlwLnBuZyIgLz4K"
      },
      {
         "title":"RW4gdGl0ZWwgw6XDpMO2w4XDhMOW",
         "content":"CkxpdGUgaW5uZWjDpWxsLiA8YnIgLz4gCjxiPmhlajwvYj4gCjxoMT50ZXN0PC9oMT4KPGEgaHJlZj0iaHR0cDovL2ZyaXNrb2xhLm51Ij5FbiBsw6RuazwvYT4KPGRpdiBzdHlsZT0iY29sb3I6IGdyZWVuIj5MaXRlIGdyw7ZuIHRleHQga2Fuc2tlPzwvZGl2Pgo8aW1nIHNyYz0iaHR0cDovL2ZyaXNrb2xhLm51L2ltYWdlcy9zb2ZyaV9sb2dvdHlwLnBuZyIgLz4K"
      },
      {
         "title":"RW4gdGl0ZWwgw6XDpMO2w4XDhMOW",
         "content":"CkxpdGUgaW5uZWjDpWxsLiA8YnIgLz4gCjxiPmhlajwvYj4gCjxoMT50ZXN0PC9oMT4KPGEgaHJlZj0iaHR0cDovL2ZyaXNrb2xhLm51Ij5FbiBsw6RuazwvYT4KPGRpdiBzdHlsZT0iY29sb3I6IGdyZWVuIj5MaXRlIGdyw7ZuIHRleHQga2Fuc2tlPzwvZGl2Pgo8aW1nIHNyYz0iaHR0cDovL2ZyaXNrb2xhLm51L2ltYWdlcy9zb2ZyaV9sb2dvdHlwLnBuZyIgLz4K"
      }
   ]
}

Thanks!

A: This is how you can do it, using Base64Codec , if you use utf8.decode you won't lose the encoding.
  import 'dart:convert';

  Base64Codec base64 = const Base64Codec();
Map<String, dynamic> parseJson(String response) {
    final data = json.decode(response);

    // Here I need to decode from base64
    final dataTitle = data["app_title"];
    final dataColor = data["app_color"];

    //decode base64
    final dataTitle64 = base64.decode(dataTitle);
    final dataColor64 = base64.decode(dataColor);

    //Strings
    String stringTitle = utf8.decode(dataTitle64);
    String stringColor = utf8.decode(dataColor64);

    //content array
    List<Item> list = List();
    for (Map<String, dynamic> value in data["app_tabs"]){
       final mapTitle = base64.decode(value["title"]);
       final mapContent = base64.decode(value["content"]);
       String stringTitle = utf8.decode(mapTitle);
       String stringContent = utf8.decode(mapContent);
       list.add(Item(stringTitle, stringContent));
    }

    //now you have your list of items

    for(Item item in list){
       print("ITEM: ${item.title} .. ${item.content}");
    }
    //return that list if you want

    return data;
  }

A: I ended up solving it myself! This is the final code:
import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

Future<Map<String, dynamic>> fetchJson() async {
  final res = await http.get('http://app.roboro.se/json/001');

  if (res.statusCode == 200) {
    return compute(parseJson, res.body);
  } else {
    throw Exception('Failed to load json');
  }
}

Map<String, dynamic> parseJson(String response) {
  return walkJson(json.decode(response));
}

Map<String, dynamic> walkJson(data) {
  data.forEach((key, value) {
    if (value is List == false) {
      data[key] = base64Decode(value);
    } else {
      value.forEach((item) => item = walkJson(item));
    }
  });

  return data;
}

String base64Decode(String encoded) {
  return utf8.decode(base64.decode(encoded));
}


text:
Q: Select DIV Contain Specific text I try to get div with specific text, but its give me wrong result.
this my html:

1

10

7

6

this my jquery:
$('.ui-droppable').find("div.numb.ui-draggable:contains('1')").addClass('cont');

if I run my jquery, it will adding class to div with contain 1 and 10.

A: For exact content match use filter() method. Although find() method is unnecessary here combine them into a single selector.
$(".ui-droppable div.numb.ui-draggable:contains('1')").filter(function(){
  return $(this).text().trim() == '1' ;
}).addClass('cont');

$(".ui-droppable div.numb.ui-draggable:contains('1')").filter(function() {
  return $(this).text().trim() == '1';
}).addClass('cont');
.cont {
  color: red;
}

1

10

7

6

A: You can use foreach better, simpler and memory efficient
$( ".ui-draggable-handle" ).each(function() {
    if($(this).html() == "1"){
        $(this).addClass('cont');
        return;
    }
});


text:
Q: Yii2 Override Rest Api actioncreate method can anyone tell me how to override actioncreate and actionupdate method yii2 rest api..
class CabController extends ActiveController
  {
     public $modelClass = 'api\modules\v1\models\Cab';

      public function actions(){

        $actions = parent::actions();

        unset($actions['create']);
        unset($actions['update']);

        return $actions;
    }

     public function actionCreate(){

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $model = $this->modelClass;
       $model->load(Yii::$app->request->post());
       $cur_time = date('Y-m-d H:i:s');
       $model->date_created  =  $cur_time;
       $$model->save(false);
  }

If i do like this mean i got error like 500 internal server error and error message like Call to a member function load() on a non-object ..how to solve this issue..
Thanks...

A: You are not creating object, instead you are assigning string api\modules\v1\models\Cab to $model variable. Change assigning part to:
$model = new $this->modelClass;

In case of "Class not found" error add leading backslash to class name: \api\modules\v1\models\Cab.
Related answers about creating object from string:

*

*Creating PHP class instance with a string

*Dynamically create PHP object based on string

*How to create object from String?


text:
Q: Java: Logging FutureTask exceptions I've got an application which regularly submits tasks to be executed in a dedicated thread. Those tasks are FutureTask<V> and the thread is no more than an infinite loop which executes the jobs as they get into a queue, going to sleep if empty.
Sometimes I need to wait for the result of a computation, so I call FutureTask's get() method, which will also throw an exception if something bad happened. But there are cases where I don't care what the result was, if any, but I need to know (log, printStackTrace() or whatever...) if there was some kind of failure during the task execution.
Is there any way I could achieve this without having to wait on a get() that I don't need?
Thanks in advance!
UPDATE: Calling get() on the runner thread after executing the task seemed to be the only way to catch the exception if no one else would wait for the result.
Another solution would be extending FutureTask class to provide a method which, via java reflection, exposes sync.exception private field.

A: Check Thread.UncaughtExceptionHandler

A: If I understand your problem correctly, there is a simple solution.  Modify your dedicated task-runner thread to call Future.get() after running each task, and catch and log the ExecutionException (if any).
Note that calling get in the task-runner thread after running the task is guaranteed not to block.
(Uncaught exception handlers won't help because any exception and error thrown by the run() method of the future's wrapped Runnable will be caught byFutureTask.run()`.)

A: I think you should use 'setException' to report the failure from your task. It will make get() report an ExecutionException.  See this as well:
How to catch exceptions in FutureTask

A: A CompletionService might be a possibility here.  Using one of those will allow you to call get() on the Futures once they are definitely finished.  Alternatively, the Guava libraries have ways to add a listener to a Future or FutureTask to execute when the task is complete (the ListenableFuture and its related objects).

A: You can also check an example I wrote for Futuretask


text:
Q: Scripting Unity3D - Opening door does not stop rotating Right.. It's my first time asking a question here so my apologies if I leave any important details out, I'll do my best to give the relevant information.
Here's my problem: I'm using a script for a door to open a cabinet, and one door works just fine. The other door however is mirrored and opens along the same rotation, making it open inwards instead of outwards.
My guess (as a complete beginner, mind you) is that
    openRot = new Vector3 (defaultRot.x, defaultRot.y + DoorOpenAngle, defaultRot.z

needs to be chaged to a negative DoorOpenAngle (just replacing + with a - to flip the direction of the rotation).
This however has instead made the door spin around incredibly fast and it doesn't stop "opening", it just keeps spinning the full 360 degrees in an infinite loop. The following script is the one for the properly working door, if I was to change the angle to a negative value like in my suggestion above, what else could be the cause of the door never stopping?
 I'm guessing there's another piece of code with a conflict due to trying a simple mirror rotation, sorry if this looks messy according to your own standards, done my best on the formatting.
var smooth = 2.0;
var DoorOpenAngle = 90.0;

private var open : boolean;
private var enter : boolean;

private var defaultRot : Vector3;
private var openRot : Vector3;

function Start()
{
  defaultRot = transform.eulerAngles;
  openRot = new Vector3 (defaultRot.x, defaultRot.y + DoorOpenAngle, defaultRot.z);
}

//Main function
function Update (){
  if(open)
  {
    //Open door
    transform.eulerAngles = Vector3.Slerp(transform.eulerAngles,
        openRot, Time.deltaTime * smooth);
  }
  else
  {
    //Close door
    transform.eulerAngles = Vector3.Slerp(transform.eulerAngles,
        defaultRot, Time.deltaTime * smooth);
  }

  if(Input.GetKeyDown("f") && enter){
    open = !open;
  }
}
function OnGUI(){
  if(enter){
    GUI.Label(new Rect(Screen.width/2 - 75, Screen.height - 100, 150, 30), "Press 'F' to open the cabinet");
  }
}

A: You've misunderstood what Slerp does. You're expecting it to behave more like RotateTowards.
Slerp, like any linear interpolation function, takes two values from and to, then returns another value that is t percent between them. That's very useful, sometimes, but not really what you're trying to do, here.
RotateTowards, on the other hand, takes two values current and target, then rotates current toward target by up to maxRadiansDelta and returns that. This is much closer to the behavior you're looking for.
Since we are dealing with rotation, it'll be easier to use Quaternion.RotateTowards. The basic concepts are the same.
Suppose you want the door to rotate by 30 degrees per second:
//convert euler angles to quaternion
//you can do this earlier, but this is fine for now
var openRotQ = Quaternion.Euler(openRot);

//calculate rotation
var maxDegrees = Time.deltaTime * 30;
var newRot = Quaternion.RotateTowards(transform.rotation, openRotQ, maxDegrees);

//apply rotation
transform.rotation = newRot;

If it's still not working after those changes, it's worth noting that Unity's documentation recommends that you avoid angles above 360 degrees when working with Euler angles.
You can work around that by building a separate quaternion for each rotation you wish to apply:
//compose and apply a separate quaternion for rotation
var rotated = transform.rotation * Quaternion.Euler(0, DoorOpenAngle, 0);
openRot = rotated.eulerAngles;


text:
Q: TableViewController MVC - Swift Say I have a table view controller in Swift. In an MVC type setting would a Table View Cell represent the view portion and if I were to create a separate model class that the table view controller used as part of its data source would this conform to the MVC structure? Or would the Table View Controller itself be classed as a mixture still of view and controller?

A: Creating a model class that the View Controller used for it's data source would be more akin to the MVVM (Model-View-ViewModel) pattern.
See here


text:
Q: DDD and optimization for showing data in views This is a common requirement in many web-based projects: an entity has to show information to another related entity. For example, a book in an e-commerce site has to show relevant information about its author.
Let say I model both the book and author as an entity, how should I implement a feature which display a book and its author's information on the same page.

*

*I can make a call to the BookRepo to retrieve the book's information, and then another call to the AuthorRepo to retrieve the author, using the authorid inside the book entity. This is 2 queries

*I can write a query where I join the Book and Author tables together and retrieve both information in 1 query. But which repo does this query goes? Does this break DDD because I am assuming details about the Book and Author entity?

Which is the 'best practices', and what are other ways I can approach this problem?
(I am assuming using the use of standard SQL queries [such as PHP + MySQL], since in EF 4 you would define associations between Book and Author which would solve the problem rather easily).

A: But even though you don't seems to use ORM's you probably have tto populate your entities from your SQL querys and your entities has to relate to each other in some way (collections, navigation properties etc...).
If your domain contains entities that have no associations between each other, I wouldn't call it DDD since you lack some important ingredients like aggregates, value objects, bi-/unidirectional relationships.
But what do I know :-) Maybe you have made your puzzle well and this last piece is to merge entities into a "view" that can be useful for your clients.
Since repositories normally operates on an aggregate-root entity you can have repository methods like ListBooksByAuthor (BookRepository) or ListAuthors (AuthorRepository).
When you want to display complex data from many different aggregates in a web page I recommend using Data Transfer Objects. Let that DTO object be unique for that page or Use Case and being a "view" that displays all (or most of the) data that web page needs.
I also recommend NOT using DTO's everywhere unless you're using web services. Using DTO's together gives both pros and cons. Together with a service layer it gives you a nive anti corruption layer and also gives you the place to inject Book and Author repository. Then from service layer you can assemble and reassemble DTO's (look at AutoMApper or similar...helps you a lot).
BUT to much DTO's everywhere also gives you overhead in maintenance of the application. It adds another layer to maintain.
I prefer to just use it for certain clients/web pages.
I hope you understand what I'm trying to explain :-)

A: If you look at this page it describes two ways to load and relate the aggregate roots. Linking this back to your example:
The Book class would encapsulate the relevant Author information as a Value Type so when the Book information is displayed on the web page it has all the information on the author it needs. If the users decides to view more information on the Author they can by following a link to an Author Page (whatever the requirement is).
If you have a service method called FindBookByTitle then
loading the Book entity would then load the relevant author information from the BookRepo.
class Author
{
  public Author(int authorID, FullName name) { }

  int AuthorID { get; }
  FullName Name { get; }
  List<BookDetails> AuthoredBooks { get; set; }
}

class BookDetails
{
  public BookDetails(int ID, string title) { }

  int BookID { get; }
  string Title { get; }
}

class Book
{
  public Book(int ID, string Title) { }

  int BookID { get; }
  string Title { get; }
  List<AuthorDetails> Writers { get; set; }
}

class AuthorDetails
{
  public AuthorDetails(int ID, FullName name) { }

  int AuthorID { get; }
  public FullName fullName { get; }
}

class FullName
{
  public FullName(string name, string surname) { }

  public string Name { get; }
  public string Surname { get; }
}

A: There is no silver bullet solution to this, but you have a few options.
Your first proposed solution of making a call to two repositories is perfectly valid and happens all the time in practice. For example, it takes over a hundred different services to render an Amazon product page. Each service is responsible for providing data specific to its bounded context. You can create a service called something like BookService which calls the two repositories to return a reporting object or a DTO that has all the data that you need for the particular view. If you feel that performance is due to two repository calls is going to be an issue, you can employ caching, or CQRS to create appropriate read models, but don't jump  to those solutions prematurely.
But which repo does this query goes?
I would just add it to the BookRepository, or even a whole new repository called BookDetailsReportingRepository, perhaps a method called GetBookDetails.  This method would not return an editable entity, but a reporting object which is a projection of values from multiple entities.
Does this break DDD because I am assuming details about the Book and Author entity?
This does not violate DDD and in my opinion makes it easier to apply. Just regard as the data returned by the aforementioned repository as reporting objects, not entities.


text:
Q: Boolean custom environemnt I noticed that boolean custom environment variable working in unexpected way in conditions. Without explicitly checking if it is true or false it's passing to if anyway.
Example:
I had in .env
REACT_APP_TEST=false

when
(some stuff)

if (process.env.TEST) { // getting here regardless of value
  yield call(fetchDocumentIfEnd, input)
}

if (process.env.TEST === true) { // working as expected
  yield call(fetchDocumentIfEnd, input)
}

(some stuff)

Why is working like that? I not found any information here
React version: "^16.13.1"


text:
Q: Oracle SQL compare strings and find matching sub-strings I have colon separated tags associated to two different entities in two tables. Would like to do a sub-string matching for the tags and relate the entities.
Table 1 - Table of issues

Issue ---------------- Tag

Issue 1 -------------- Dual UOM:Serial Control:Material Issue

Issue 2 -------------- Validity rule:Effectivity date

Table 2 - Table of Tests

Test ----------------- Tag

Test 1 --------------- Inventory:Outbound:Material Issue

Test 2 --------------- Items:Single UOM

Test 3 --------------- Items:Dual UOM

Test 4 --------------- Recipe:Validity Rule

Test 5 --------------- Formula:Version control:date

Test 6 --------------- Formula:Effectivity date

Now, for each issue in table 1, I need to compare its associated tag with the tags in table 2 and find applicable tests.
In above ex,
Issue 1 - Matched tests will be Test 1, Test 3
Issue 2 - Matched tests will be Test 4, Test 5
All the tags associated to the issues and tests will come from a common tag master.
Any help in providing the sql code snippet that would do this sub-string to sub-string matching is much appreciated.

A: Here's one option: split issues into rows and compare them to test tags, using the INSTR function. Note that letter case must match. If it doesn't (in reality), use lower or upper function.
Read comments within code (which is split into several parts, to improve readability).

Sample data first:
SQL> with
  2  -- sample data
  3  issues (issue, tag) as
  4    (select 1, 'Dual UOM:Serial Control:Material Issue' from dual union all
  5     select 2, 'Validity Rule:Effectivity date'         from dual
  6    ),
  7  tests (test, tag) as
  8    (select 1, 'Inventory:Outbound:Material Issue' from dual union all
  9     select 2, 'Items:Single UOM'                  from dual union all
 10     select 3, 'Items:Dual UOM'                    from dual union all
 11     select 4, 'Recipe:Validity Rule'              from dual union all
 12     select 5, 'Formula:Version control:date'      from dual union all
 13     select 6, 'Formula:Effectivity date'          from dual
 14    ),

Split issues into rows (splitiss), compare them to test tags (temp)
 15  -- split issues into rows ...
 16  splitiss as
 17    (select issue,
 18            tag,
 19            regexp_substr(tag, '[^:]+', 1, column_value) val
 20     from issues cross join
 21       table(cast(multiset(select level from dual
 22                           connect by level <= regexp_count(tag, ':') + 1
 23                          ) as sys.odcinumberlist))
 24    ),
 25  -- ... and now compare them to test tags
 26  temp as
 27    (select i.issue, i.tag issue_tag, i.val, t.test, t.tag test_tag,
 28       instr(t.tag, i.val) ins
 29     from splitiss i cross join tests t
 30    )

Return the result:
 31  -- return only test tags which match to separate issues (INS > 0)
 32  select t.issue,
 33         t.issue_tag,
 34         listagg(t.test, ', ') within group (order by t.test) matched_tests
 35  from temp t
 36  where t.ins > 0
 37  group by t.issue, t.issue_tag;

     ISSUE ISSUE_TAG                              MATCHED_TESTS
---------- -------------------------------------- --------------------
         1 Dual UOM:Serial Control:Material Issue 1, 3
         2 Validity Rule:Effectivity date         4, 6

SQL>

P.S. I believe you posted wrong test tags for issue #2; should be 4, 6, not 4, 5.

A: Thanks, this worked
I did break the tags into rows and then used substr,instr matching.


text:
Q: Is distribution of raring packages officially ended? I don't see raring on http://us.archive.ubuntu.com/ubuntu/dists/. Is it a temporary thing or people are expected to move to next versions of Ubuntu ?
Thanks.

A: Raring went End of Life some time ago.  All releases of Ubuntu have specific End of Life dates.  The wiki contains a page of all Releases, both current releases and releases that have gone End of Life, where they are no longer supported, and no longer should be used.  It is infinitely important that you use a version of Ubuntu that is still supported so that you do not put yourself and your data at risk.
The "repositories" for older releases of Ubuntu are under this location but never receive updates or security fixes.  Continuing to use an older release that has gone End of Life puts you and your data at risk.


text:
Q: Loading Multiple html pages (WebView) From the same activity and using the if / else clause I'm new to android dev. I want to know if it is possible to load up to twenty html pages in the assets folder from one activity using the if/else clause statements.
I want it that when a button is clicked in another activity, it opens a WebView according to the Button number pressed. I'm thinking I will have to create an activity for each webViews, but I'd like to know if I can use just one java class, and one Webview layout.

A: Yes it is possible, you can use single activity and a webView,and change content by if/else statements. See docs. for loadUrl and loadData methods of WebView.

A:
I'm thinking I will have to create an activity for each webViews, but
  I'd like to know if I can use just one java class, and one Webview
  layout.

No, you don't have to create an activity for each webViews.
When you're in your first activity, you can pass data to the second with the URL containing the HTML file in the assets folder.
Assuming you have two HTML pages for two different buttons:
file:///android_asset/page_button_1.html
file:///android_asset/page_button_2.html

In your first activity, pass the right URL in the onClick event (example for button one):
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML","file:///android_asset/page_button_1.html");
startActivity(i);

Then in your webview activity :
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_layout);
    Bundle extras = getIntent().getExtras();
    String value = "file:///android_asset/default_page.html";
    if(extras !=null) {
       value = extras.getString("keyHTML");
    }
    webView = (WebView)findViewById(R.id.webview);
    webView.loadUrl(value);
}

A: In one activity you have a webview and in the web view you can change the html pages with method webview.loadUrl("http://developer.android.com/");
just make the html pages in the asset folder and then load the same pages at run time according to your logic.
e.g
webView.loadUrl("file:///android_asset/your.html");


text:
Q: Ionic 2 app.scss issue I have been working on an ionic 2 app for a month. I usually test in on Android and it was working perfectly fine. I just ran on IOS, and the design is very wrong. It looks like it is not reading the app.scss file which I use for global CSS classes. Any idea what is the issue ?
This is a sample of the app.scss file
/***** Validation *****/
.error {
    background-color: $red;
    margin-top: 15px;
    margin-bottom: 15px;
    padding: 10px 10px 10px 10px;
    color: white;
}

.error ion-icon {
    padding-right: 5px;
}

/***** Loading *****/
ion-spinner {
    position: absolute;
    left: 50%;
    top: 50%;

    .z-index {
        z-index: 2;
    }
}

/***** Menu *****/
.header-md::after, .tabs-md[tabsPlacement="top"] > .tabbar::after, .footer-md::before, .tabs-md[tabsPlacement="bottom"] > .tabbar::before {
    background-image: none;
}

ion-header {
    .navbar {
        padding: 0;
        box-shadow: 0 4px 2px -2px #aeaeae;
    }

    .navbarSection {
        padding: 8px 8px 0px 8px;
    }

    .menuSection {
        text-align: left;

        button:hover,
        button {
            color: white !important;

            div {
                margin-left: 10px;
            }
        }
    }

    .titleSection {
        text-align: center;

        ion-title h5 {
            font-size: 14px;
            color: white;
        }
    }

    .buttonsSection {
        text-align: right;

        button, button:hover {
            background-color: #ffffff !important;
            color: $black;
            font-weight: bolder;
            text-transform: none;
            font-size: 12px;
        }

        ion-icon {
            padding-left: 10px;
            padding-right: 10px;
            font-size: 16px;
        }
    }

    .categoriesSection {
        background-color: white;
        height: 42px;

        .filterSection {
            div {
                display: inline-block;
            }

            .filter-icon {
                color: $blue;
                margin-left: 15px;
                font-weight: bolder;
            }

            .filter-searchbar {
                position: relative;
                margin-left: 10px;
            }
        }
    }

A: Some of your styles included in app.scss seem to be android specific.
eg:
.header-md::after, .tabs-md[tabsPlacement="top"] > .tabbar::after, .footer-md::before, .tabs-md[tabsPlacement="bottom"] > .tabbar::before {

classes with -md suffix are set only for android. You will have to set similar styles for -ios suffix.
.header-ios::after, .tabs-ios[tabsPlacement="top"] > .tabbar::after, .footer-ios::before, .tabs-ios[tabsPlacement="bottom"] > .tabbar::before {


text:
Q: SQL Server 2012 Group only by one column I need to group only by one column
SQL Server 2012 query:
SELECT OrderID,Status,DateEdited
FROM orders
WHERE Status='Pending'
GROUP BY OrderID,Status,DateEdited

and the result is:

As you can see there are duplicate OrderId column values.
Works but it groups by OrderId,Status,DateEdit but what I need is that the OrderId would be unique in the results can I have something like:
SELECT OrderID,Status,DateEdited
FROM orders
WHERE Status='Pending'
GROUP BY OrderID

A: You have to use an aggregate function for status and DateEdited, to get distinct valeus for each grouped ORDERID. You can also use the ranking functions to do so like this:
WITH CTE
AS
(
   SELECT
     OrderID,
     Status,
     DateEdited,
     ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY DateEdited DESC) rownum
   FROM orders
   WHERE Status='Pending'
)
SELECT
  OrderID,
  Status,
  DateEdited
FROM CTE
WHERE rownum = 1;

This will give you distinct ORDERIDs. But which status and DateEdited to return for each grouped ORDERID?

A: Then you can do like this,
SELECT OrderID,'Pending' as Status,max(DateEdited)
FROM orders
WHERE Status='Pending'
GROUP BY OrderID

If you dont want to loose any record then you can go for
GROUP_CONCAT()
SELECT OrderID,'Pending' as Status,GROUP_CONCAT(DateEdited)
FROM orders
WHERE Status='Pending'
GROUP BY OrderID

Note: Am not sure whether you GROUP_CONCAT in sqlserver Incase it's not there
go for a function like that. :)


text:
Q: ¿Como reemplazar etiquetas con JavaScript? Quiero reemplazar unas etiquetas específicas mediante el uso de JavaScript.
La etiquetas que quiero reemplazar son estas <!-- y -->. Entre estas dos etiquetas tengo código que se ejecutará cuando cargue por completo la página.
Este es mi código:
function listen(){
var html = document.getElementsByTagName('html')[0];
[].slice.call(html).forEach(function(el, i){
el.innerHTML.replace('<!--', '<script>').replace('-->', '</script>');
});
}

window.addEventListener('DOMContentLoaded', function(){
listen();
}, false);

A: Extrae el contenido del script entre <!-- --> usando expresiones regulares, luego, creas un elemento script y lo añades al final del body para su ejecución.
Ejemplo

let scriptText = "<!-- alert('Hola'); -->";
let matches = scriptText.match(/<!--(.*?)-->/);
let code = matches[1].trim();

let script = document.createElement('script');
script.textContent = code;
document.body.appendChild(script);

Sin embargo, no le veo ningún sentido a lo que haces, a no ser que realices algún proceso cuando cargue la página y luego añadas los scripts. Simplemente no hagas eso; si quieres cargar scripts al final del parseo y carga del DOM utiliza el atributo defer en los scripts, como lo indica @Lorthas.

A: Replace crea una nueva cadena con el texto remplazado, no modifica la cadena actual.
Por tanto deberías hacer:
el.innerHTML = el.innerHTML.replace('<!--', '<script>').replace('-->', '</script>');

Referencia: String.prototype.replace en MDN

A: creo que por temas de legibilidad deberías tener los scripts en un fichero a parte del html y más si los quieres cargar a posteriori.
Si lo quieres cargar a posteriori es tan fácil como que los cargues añadiendolos al html. Te dejo una pequeña función que hace esto:
function loadScript(url)
{
    document.body.appendChild(document.createElement("script")).src = url;
}

Solo tienes que pasarle la ruta/nombre del fichero y ya lo tendrás disponible.
Espero que te sirva.

A: Si lo que quieres es cargar simplemente ciertos scripts después de haber cargado el DOM (cosa que he entendido yo al menos) lee lo siguiente:
Según https://m.genbetadev.com/javascript/javascript-defer-vs-async
Si añades el atributo defer a la etiqueta script, el codigo Javascript no se ejecutará hasta haber cargado todos los elementos de la página.
<html>
  <head>
    <script defer src="url/archivo.js">
  </head>
  <body>
  <body>
<html>

También puedes para asegurarte poner la etiqueta script antes de cerrar el body.
Async y Defer son de HTML5.


text:
Q: A question from CFT (possibly due to the English expressions) I am currently reading the book ''Conformal Field Theory'' and encountered a description about which I am very confused. I am afraid to say, this may be due to the fact that I am not a native English speaker.
On pp.6, it says:

However, the field theory describing a statistical system (like the Ising model) lives in one spatial dimension less than the statistical system itself, since time constitutes an extra dimension inherently incorporated in the quantum description of the field theory.

Here, let's say, the statistical system we want to describe is 3 dimensional. Then according to the author, the field theory should lives in 2 dimensional space, right? But this sentence is followed immediately by

Critical quantum phenomena on which the methods of two-dimensional conformal field theory can be applied are thus one-dimensional, like the spin chain described above.

Now, the statistical system is 1 dimensional while the field is 2 dimensional. That is to say, the field lives in one spatial dimension more than the statistical system. Even if we wick rotate back into the Minkowskian spacetime, the field lives in 1 dimensional space (now 1+1 spacetime) and not one spatial dimension less than the statistical system. Where is going wrong for my understandings?

A: I agree that the language is very confusing - I'm a native English speaker, and it also took me a while to understand what they were saying.  When they talk about the dimension of "the statistical system itself," they mean the spacetime dimension.  So if a system has two spatial dimensions, then it has three dimensions total (including time), and the statistical field theory has one dimension less than that - back to two again, the number of spatial dimensions.
There are two ways to intuitively understand this:
(1) If you think about real time, the "statistical mechanics describing finite-temperature phenomena" deals with thermodynamic equilibrium, which by definition does not depend on time.  So you can ignore the time dimension (or more precisely, average over it) and only focus on the fluctuations in the spatial dimensions.
(2) If you think about imaginary time in the Matsubara formalism of statistical field theory, then the imaginary time dimension is periodic with period $\beta$.  At finite temperature, this dimension is compact.  But at phase transitions, all correlation lengths diverge, and so they become infinitely larger than the circumference $\beta$ in the imaginary time direction.  So you can neglect the finite circumference $\beta$ entirely and ignore that dimension, and only consider the spatial dimensions, which are extended.  This is why we say that any finite temperature, no matter how low, phase transitions are essentially classical, even if quantum effects are significant away from the transition at that temperature.  On the other hand, at zero temperature, the imaginary time direction is infinitely long and on the same footing as the spatial dimensions, so we need to consider it even with arbitrarily long correlation lengths.


text:
Q: How to use bundle with local gems during Mina deployment of Rails app? I'm deploying a Rails app with Mina mina:deploy which clones from a git repo and Bundler installs the gems.
# /config/deploy.rb
# ...
task :deploy => :environment do
  deploy do
    invoke :'git:clone'
    invoke :'bundle:install'
    # ...
  end
end

However, unlike when I bundle install manually, mina is installing each gem anew. With a healthy number of gems, this takes roughly 10 minutes to complete. How can I deploy while pointing bundler to use any locally available (already installed) gems where possible?
I've also tried replacing invoke :'bundle:install' with queue! "bundle install --local" with no change in behavior.

A: For that you need to use a local copy of the gems that you have without checking rubygems so after installing gems you run bundle package to create a cache of the gems used and instead of running bundle install you should run bundle install --local to use only the cached copy of gems without checking the rubygems.com .


text:
Q: func start with PowerShell and Az.Storage strange error I run several Azure functions based on PowerShell. I love the local debugging feature, but lately I am experiencing a quite awkward error.
When running func start form the library containing my function, everything is fine, if it is the first time I start the function locally. However, if I stop and restart the local function, I get the following error:
[5/2/2020 2:33:35 PM] EXCEPTION: Import-Module : Az.Storage doesn't support PowerShell Core versions lower than 6.2.4. Please upgrade to PowerShell Core 6.2.4 or higher.
[5/2/2020 2:33:35 PM] + CategoryInfo          : OperationStopped: (Az.Storage doesn't \u2026re 6.2.4 or higher.:String) [Import-Module], RuntimeException
[5/2/2020 2:33:35 PM] + FullyQualifiedErrorId : Az.Storage doesn't support PowerShell Core versions lower than 6.2.4. Please upgrade to PowerShell Core 6.2.4 or higher.,Microsoft.PowerShell.Commands.ImportModuleCommand
[5/2/2020 2:33:35 PM]
[5/2/2020 2:33:35 PM] Script stack trace:
[5/2/2020 2:33:35 PM]    at <ScriptBlock>, C:\Users\AxelBogAndersen\AppData\Local\AzureFunctions\TeamsAppBackend\ManagedDependencies\200501092203881.r\Az.Storage\1.14.0\Az.Storage.psm1: line 41
[5/2/2020 2:33:35 PM]
[5/2/2020 2:33:35 PM] System.Management.Automation.RuntimeException: Az.Storage doesn't support PowerShell Core versions lower than 6.2.4. Please upgrade to PowerShell Core 6.2.4 or higher.
[5/2/2020 2:33:35 PM]    at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord)

I am running PowerShell 7.0, so it is higher then 6.2.4 - same error is produced in PowerShell 7.1 preview 2.
I have not defined any Az.Storage version in my function, so the newest version is loaded into the ManagedDependencies library. Currently that is version 1.14.0.
Once the error manifests, it is stable until I delete the entire folder in the ManagedDependencies library.
I would really like to avoid having to delete the dependencies package, because I have to wait for the download every time I do that. Downloading 256MB is time consuming annoying.
Just deleting the Az.Storage folder is not an option - the module is not re-loaded at next run and the entire session breaks. As a workaround I could live with deleting the Az.Storage and do a force update on the modules, if such a command exists.
I use AzTable in the mix, but I am not sure that has any significance.
I would be grateful for any kind of help to solve this very annoying issue.

A: I had the same problem. In your Azure Function run.ps1 output the psVersion, it's most likely 6.2.3. If you used Chocolatey to install the Azure Function Core Tools in the config file there is an attribute called powershellHost, which uses Chocolatey's built-in powershell host.
feature name="powershellHost" enabled="true" setExplicitly="false" description="Use Chocolatey's built-in PowerShell host. Available in 0.9.10+." />

I had some trouble modifying the config file, so I just upgraded the package using Chocolatey and was able to use the Az modules.


text:
Q: Highcharts not picking up on date - dates being interpreted as strings I'm trying to create a highchart with irregular x axis, a bit like this: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/spline-irregular-time/
I'm pulling my data from mySQL via PHP and processing in JSON format.
I can't get highcharts/JS to read the dates in date format - it seems to be pulling them as strings.
Here's my script:
$(document).ready(function() {
    var options = {
        chart: {
            type: 'spline',
            marginRight: 130,
            marginBottom: 25
        },
        title: {
            text: 'some title',
            x: -20 //center
        },
        subtitle: {
            text: '',
            x: -20
        },
        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: { // don't display the dummy year
                month: '%e. %b',
                year: '%b'
            },
            categories: []
        },
        yAxis: {
            title: {
                text: 'L/min'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        plotOptions: {
            spline: {
                marker: {
                    enabled: true
                }
            }
        },

        tooltip: {
            formatter: function() {
                return ''+ this.series.name +': '+
                this.y +'
'+ this.x;
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -10,
            y: 100,
            borderWidth: 0
        },
        series: []
    }

        $.getJSON("allreports/report.php", function(json) {

        options.xAxis.categories = json[0]['data'];
        options.series[0] = json[1];
        options.chart.renderTo = 'container';
        chart = new Highcharts.Chart(options);
    });

and here's my PHP page:
<?php
    $con = mysql_connect("localhost","db-user","db-pw");

    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("db", $con);

    $sth = mysql_query("SELECT v1,v2 FROM table");
    $rows = array();
    $rows['name'] = 'v1';
    while($r = mysql_fetch_array($sth)) {
        $rows['data'][] = $r['v1'];
    }

    $result = array();
    array_push($result,$rows1);
    array_push($result,$rows);

    print json_encode($result, JSON_NUMERIC_CHECK);

    mysql_close($con);
?>

This outputs the following:
[{"name":"medicinetime","data":["01,01,1970,01,00,00","01,01,1970,01,33,36","01,01,1970,01,33,36","01,01,1970,01,33,36"]},{"name":"units","data":[1,3,2,2]}]

But my chart is as follows:

Any thoughts on what I'm doing wrong please? What do I need to do to get PHP/JS to pick up on this array as a series of datetimes rather than strings?
Thank you!

A: You have two issues. First, you need to convert your date-component values into an actual Javascript date object. The format you're looking for for your series data is an array of X/Y pairs. It'll look like this, using your data:
[
  [Date.UTC(1970,1,1,1,0,0),1],
  [Date.UTC(1970,1,1,1,33,36),3],
  [Date.UTC(1970,1,1,1,33,36),2],
  [Date.UTC(1970,1,1,1,33,26),2]
]

Try something like this:
var xVals= json[0].data.map( item => {
  var dateArr = point[0].join(',');
  return Date.UTC(dateArr[2],dateArr[1],dateArr[0],dateArr[3],dateArr[4],dateArr[5]);
});

var yVals = json[1].data;

options.series[0] = {
  name: json[1].name,
  data: xVals.map( (x,i) => [x,yVals[i]])
}

Some documentation on valid formats for the series data is here: http://www.highcharts.com/docs/chart-concepts/series
Second, you have some duplicate X values there, and that's going to be confusing...you're going to want your timestamps to be unique, or it's going to be hard to make a line chart out of them.


text:
Q: Блокировка программы при попытке парсинга на сервере У получил бан по ip на сайте https://777score.ru. Я купил себе сервер с удаленным рабочим столом. Проверил работу сайта запустив его через браузер хром, открывается без проблем, бана и каких либо блокировок нет. Но при попытке запуска самого парсера на сервере, получаю следующий html код. Скажите пожалуйста, как обойти данную проблему? Ведь сайт через браузер открывается нормально. Возможно в настройках виндовс что-то нужно изменить? Я уже даже не знаю на что думать.
<!DOCTYPE html>

<title>Attention Required! | Cloudflare</title>
<meta charset="utf-8"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="noindex, nofollow" name="robots"/>
<meta content="width=device-width,initial-scale=1" name="viewport"/>
<link href="/cdn-cgi/styles/cf.errors.css" id="cf_styles-css" rel="stylesheet"/>

Please enable cookies.

Sorry, you have been blocked

You are unable to access 777score.ru

Why have I been blocked?

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 777f0ee76a09bb50
•

      Your IP:
      <button class="cf-footer-ip-reveal-btn" id="cf-footer-ip-reveal" type="button">Click to reveal</button>
193.124.92.162
•

Performance & security by Cloudflare

A: <meta content="noindex, nofollow" name="robots"/>

Сервер считает Вас роботом. Пробуйте передавать headers тем самым маскируя себя под обычного клиента. Смотрите как формируются cookies в браузере и в парсере. Возможно парсеру не хватает одного небольшого запроса, чтобы получить куку и действовать как браузер.
Букмекеры не самые бедные люди, защит там полно может быть. Так вот нахрапом брать главную страницу, которая у Вас так и так не зарендерится нет смысла. Так что лучше от задачи отталкиваться.
Если знакомы с php, можете попробовать данный парсер:
https://github.com/San4ezZ-89/777Parser
Если он заработает, то можно будет изучить разницу между requests, postman и данным парсером.
Скорее всего здесь дело в cookies, но просто так скопировать их из браузера не получится, также на робота выведет.
Подробнее о блокировках на английском SO.
Обратите внимание на __cf_bm cookie, он в браузере появляется одним из первых, а response с роботами неоднократно ссылается на cf-.
Последнее обновление
Помучал сайт ещё через Tor. Обычные браузеры, всё же, шалят с JS даже если его запрещать. В Tor на сайт не пускает и просит включить JS. Так что тут либо драйвер использовать, либо упорно изучать что в js происходит и имитировать активность.


text:
Q: error The "Login" component has been registered but not used vue/no-unused-components I am getting following error:
         The "Login" component has been registered but not used       vue/no-unused-components and
       error  The "HelloWorld" component has been registered but not used  vue/no-unused-components.
       but why it is giving i am not getting any idea. i am new to vue.
router.js

import Vue from 'vue'
import VueRouter from 'vue-router';
import Login from './components/Login.vue';
import HelloWorld from './components/HelloWorld.vue';

Vue.use(VueRouter)

export default new VueRouter({
    routes: [
        {
            path: '/',
            name: 'Login',
            component: Login
        },
        {
            path: '/helloworld',
            name: 'Helloworld',
           component: HelloWorld
        },
    ]
})

App.vue

 <template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import Login from './components/Login.vue'
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
      Login,
      HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
   }
</style>

A: In your App.vue you don't need to import Login and HelloWorld. This will be taken care of by the vue router in router.js file. You can remove below lines from your App.vue
<script>
import Login from './components/Login.vue' //remove this line
import HelloWorld from './components/HelloWorld.vue' //remove this line

...
...
components: {
      Login, //remove this line
      HelloWorld //remove this line
  }
....

Now, some information about the error that you have got because I am sure that you will be again getting this same error in other places of the project as you continue to develop. The error that you got is because of eslint found two variables that are not used anywhere in the file. Eslint helps to improve the code quality and reduce the bundle size by notifying many errors as you got. You can disable this particular lint by using.
<script>
/* eslint-disable vue/no-unused-components */
...

Or you can disable all eslint using /* eslint-disable */ There are many other rules that you can apply for eslint check it here, https://eslint.org/docs/rules/


text:
Q: 60GB in version store in short amount of time, allow snapshot isolation is disabled We had a situation where the version store went from zero to 60 GB in just a few minutes.  It stayed high for hours and due to the performance impact of this on tempdb (disk queue was 1000), almost everything became super slow and we ended up failing over to a secondary to get back to a reasonable state of performance.
Snapshot isolation is not enabled on any of the databases, and I can see from the session captures that everything is read committed or read uncommitted.   NOLOCK is used extensively (please refrain from going down this rabbit hole unless it is 100% relevant to the issue at hand) to manage blocking.
I have found references stating that online index rebuilds will use version store, but there were no rebuilds running.  There was a REORGANIZE running on a 122 GB table, but according to my understanding this would not use any version store as a reorg just moves one page at a time.  Additionally, this had been running for hours before the version store usage escalated, so I'm quite sure this was not causing the issue.
There were no sleeping sessions with open transactions.
I have found some other references about MARS and triggers using version store, but not seeing that those were factors here as there are only two triggers for auditing on some small user tables.
The one thing I've noticed that started at the time the version store exploded was a column data type change was started on a load table that had ~30 million rows:
ALTER TABLE dbo.some_table ALTER COLUMN UAI_ID BIGINT NOT NULL

And it was still running 5 hours later. (Please refrain from asking why this would be done as I don't know.)  There have been no recent changes to the process and it hasn't caused a problem before, so I don't see that this would cause the version store to go nuts, either.
I've seen references to reviewing the "internal space" used by sessions, but these only add up to ~10 GB, so I'm not seeing a correlation there.
Prevailing wait types were page latch and CXPACKET shortly after the version store usage went high.  As time went on and things started to pile up, SLEEP_TASK and CXPACKET prevailed.
What am I missing here?  What other types of activity could use so much version store so fast?

A:
What other types of activity could use so much version store so fast?

If the instance was acting as a readable secondary replica for an availability group, then snapshot will be used for read queries against that database - regardless of the settings or specific isolation levels requested.  If there are a lot of data changes on the primary for that AG database, or really long running transactions, then the version store can grow very quickly.
Note that this could be a different database and AG from the one where performance issues were occurring - since prior to SQL Server 2019, all user databases share the same version store in tempdb.

Regarding the waits you encountered, one thing I learned recently that's not very intuitive is that hash spills to tempdb incur the SLEEP_TASK wait type.  This shouldn't cause the version store to grow, but it lines up with the disk issues you mentioned with tempdb (disk queue being 1,000, etc).


text:
Q: How to transform R dataframe to duplicate rows and divide values from one column between two rows? I have a dataframe that looks like this:
df1 <- data.frame(ID = c("A","B","F","G","B","B","A","G","G","F","A","A","A","B","F"),
                 code = c(1,2,2,3,3,1,2,2,1,1,3,2,2,1,1),
                 value =  c(100,50,100,100,50,50,100,100,100,50,50,100,100,50,100))

I want now to duplicate the number of rows, so the ID column gets duplicated, the code column would duplicate leaving one value the same and another would be +1 and the value column would be divided between two. So the dataframe would look like this:
df1 <- data.frame(ID = c("A", "A","B","B","F","F","G","G","B","B","B","B","A","A","G","G","G","G","F","F","A","A","A","A","A","A","B","B","F", "F"),
                 code = c(1,2,2,3,2,3,3,4,3,4,1,2,2,3,2,3,1,2,1,2,3,4,2,3,2,3,1,2,1,2),
                 value =  c(100,50,50,25,100,50,100,50,50,25,50,25,100,50,100,50,100,50,50,25,50,25,100,50,100,50,50,25,100,50))

A: You can use rbind and transform.
rbind(df1, transform(df1, code = code + 1, value = value / 2))

To get the desired order use:
rbind(df1, transform(df1, code = code + 1, value = value / 2))[
    matrix(seq_len(nrow(df1)*2L), 2L, byrow=TRUE),]
#   ID code value
#1   A    1   100
#16  A    2    50
#2   B    2    50
#17  B    3    25
#3   F    2   100
#...

A: library(dplyr)
df1 %>%
  mutate(code = code + 1,
         value = value / 2) %>%
  bind_rows(df1)

To get the (interleaved) expected output, you can arrange:
df1 %>%
  mutate(row_number = row_number(),
         code = code + 1,
         value = value / 2) %>%
  bind_rows(df1 %>% mutate(row_number = row_number()), ., .id = "df") %>%
  arrange(row_number, df) %>%
  select(-c(df, row_number))

#    ID code value
# 1   A    1   100
# 2   A    2    50
# 3   B    2    50
# 4   B    3    25
# 5   F    2   100
# 6   F    3    50
# 7   G    3   100
# 8   G    4    50
# 9   B    3    50
# 10  B    4    25
# 11  B    1    50
# 12  B    2    25
# 13  A    2   100
# 14  A    3    50
# 15  G    2   100
# 16  G    3    50
# 17  G    1   100
# 18  G    2    50
# 19  F    1    50
# 20  F    2    25
# 21  A    3    50
# 22  A    4    25
# 23  A    2   100
# 24  A    3    50
# 25  A    2   100
# 26  A    3    50
# 27  B    1    50
# 28  B    2    25
# 29  F    1   100
# 30  F    2    50


text:
Q: Remove JavaScript comments using Regex - PHP I want to minify HTML code using PHP && Regex code
The minify function :
public static function sanitize_output($buffer) {

    $search = array(
        '/ {2,}/',
        '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
    );
    $replace = array(
        ' ',
        ''
    );
    $buffer = preg_replace($search, $replace, $buffer);

    return $buffer;
}

I use this function when I rendering the template (HTML file), but I get always this error on console

SyntaxError: missing } in compound statement note: { opened at line

The minify code delete some " { " on Js code, is there any solution the fix this problem?
After some search, I found that the error is in JS comments, when I minify the HTML code the comments concatenate with the code.
I try to use this regex
/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/

but it's doesn't work

A: Like you say, when you Minify your code using the function, all the HTML code be in single line, for that any code after a JS comments well be a comment to.
So You can use this PHP regex to remove inline JavaScript comment :
Your new function :
 public static function sanitize_output($buffer) {

        $search = array(
            '#^\s*//.+$#m', //remove JS comment,
            '/ {2,}/',
            '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
        );
        $replace = array(
            '',
            ' ',
            ''
        );
        $buffer = preg_replace($search, $replace, $buffer);

        return $buffer;
    }


text:
Q: publishing artifacts is to slow At the end of my build log i have the following:
[15:16:22]: Publishing artifacts (25m:29s)
[15:16:22]: [Publishing artifacts] Paths to publish: [automation/artifacts]
[15:16:23]: [Publishing artifacts] Sending files

i tried reading the agents log and got this
[2013-05-02 15:16:23,023]   INFO -    jetbrains.buildServer.AGENT - Start: Sending files
[2013-05-02 15:41:51,214]   INFO -    jetbrains.buildServer.AGENT - Done publishing artifacts to , total files published: 22

the size of the artifacts 272 MB.
In the past this part of the process took less then half a minute.
where can i find more data about the operation?

A: Check your network connection between the host with Teamcity master and Teamcity agent. Teamcity saves all the artifacts on master and in the end of the build copy them from agent to master.

A: do you have a lot of files on the server? I found it would take about 50 mins to complete on a server with a lot of files, however the files would have already been uploaded after 5 mins so I think it might be trying to list all the files or something. When I uploaded the artifacts to another server with less files, it would publish it in around 5 mins

A: I like to answer this question as recently we faced this problem .
We upgraded our Teamcity from v9.1.7 to V2019.2.1 , In the updated Teamcity there are new requests like /app/agents/v1/commands/next  which are increasing traffic for Teamcity . These type of requests will always be polling to Teamcity server from Teamcity agents .
In case your Teamcity server is behind a Apache proxy,  request flow will be like this .
Client <--> load balancer <--> Apacher <--> Tomcat of Teamcity .
If Apache in our case is not able to handle that much traffic as now requests are more flowing to Teamcity due to new automated requests then during all interaction to Teamcity requests will be queuing at Apache end hence increasing time for all requests and packet drops .


text:
Q: Empty value when opening I want to use select2 with Angular, and sometimes it gets "empty" value when opening the select. I do not know why this happens.
Check how it looks like:

But, sometimes it works perfectly:

I really do not know why it happens this way. Here is my directive code:

 0">
<ui-select ng-model="selectedItem" on-select="onChange($item);" theme="bootstrap">
    <ui-select-match placeholder="{{placeholder}}">
        {{selectedItem[fillable]}}
    </ui-select-match>

    <ui-select-choices repeat="item in items | filter: $select.search">

    </ui-select-choices>
</ui-select>

This is how I instantiate it:
<strainer-select
        items="campaigns"
        selectedItem="campaignSelected"
        handler="onCampaignFilterChanged"
        placeholder="Filtre por campanha"
        fillable="campaign"
    ></strainer-select>

Does anyone have ever seen this happens?
Any help is very appreciate.
Thank you all.

A: It might be a bug of the directive itself. The problem seems to be with directive's input inside it. So a workaround is to add style to force 100% width.
<!DOCTYPE html>

    <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <link data-require="select2@3.4.5" data-semver="3.4.5" rel="stylesheet" href="//cdn.jsdelivr.net/select2/3.4.5/select2.css" />
    <link data-require="select2@3.4.5" data-semver="3.4.5" rel="stylesheet" href="./select.min.css" />

Hello Plunker!

        <strainer-select items="campaigns" selecteditem="campaignSelected" handler="onCampaignFilterChanged" placeholder="Filtre por campanha" fillable="campaign"></strainer-select>


text:
Q: Multiple values in one table; need them to be in separate columns I'm relatively new to SQL so thank you in advance for any help you can give me. I'm writing a query that needs to produce a table that shows all students' majors, minors, and the dept. I've created multiple columns already: (maj, dept, min, dept, concentration, dept). My problem is that my table is producing multiple rows because I have not included anything in my query that allows for students who have multiple majors. So instead what is happening is that they are showing up in multiple rows. I need every student to occupy only one row. Students can have any combination of maj's, minor's, and concentrations (and multiple for each). I'm dealing with 5,000 students. What do I need to include in my syntax? Thank you.

A: What you need is

*

*a "student" table

*a "major" table

*a linking table (also known variously as an "intersection" or "association" or "joining" table). The fancy name for this is "Associative Entity" (if you read nothing else, read this!).
1 row per "student" in the student table - this is critical for good design - otherwise you are going to have to keep track of multiple copies of your student data. This will typically contain their student id, name(s), address, tel: & - PRIMARY KEY student_id.
1 row per "major" - again, no multiple copies of data. Typically contains, id major name, department, prerequisites.... &c. PRIMARY KEY - major_id.
The joining table will probably contain only 1 record per student - the brigher/more hardworking ones might have more than 1 record per student and will just simply contain (student_id, major_id) - the PRIMARY KEY in this case will just simply also be (student_id, major_id). So, a student with 2 majors will have 2 records &c.
You will obviously then have a department table - possibly a joining table for department-major for multi-disciplinary majors? I imagine that most (all) majors will have a primary department?
NEVER have a .csv type arrangement where you have multiple "facts" stored in the same field of a database  - there are two reasons for this:
1) it makes SQL programming impossible and
2) it's a breach of Codd's rules (the second one) which states:

Rule 2: The guaranteed access rule:
Each and every data (atomic value)
  in a relational data base is guaranteed to be logically accessible by
  resorting to a combination of table name, primary key value and column
  name.

Even if you don't understand them yet, there is a reason why Codd's rules are regarded as fundamental amongst database practicioners.
Start with this - break down the problem, determine your entities (or "objects", or just plain "things"). Have a table for each one. That and joining tables for "things" which are connected in a 1->n or m->n relationship and you'll at least have the basics right. Come back to us if you have more specific requirements after having done that.

A: I'm sure there are lots of ways to solve this.  The first thing that comes to my mind is to create a simple scalar value function that accepts the Student-Id and 'type' of column you are trying to populate and returns a delimited string of values for that student and type of column.
The scalar value function (GetInfo) uses the student id and the 'type' of column (Maj, Dept, Min, etc.) to select and concatenate the results into a varchar string to return.
The main query would simply invoke the scalar function
select
   dbo.GetInfo(STUDENT_ID,'MAJ') AS MAJORS,
   dbo.GetInfo(STUDENT_ID,'DEPT') AS DEPARTMENTS
from
   student table


text:
Q: Add values from table cells I have a table with digit values it its cells.
My objective is that by clicking on table cells and getting their values but adding them up as I click at will. It should keep track of the sum and show it in a separate div.
I have written code which handles clicking the td and adds a class which, among other things, changes the background color, necessary so that the user can see what he has clicked so far. Because classes are being added on the fly, I use live().
Then I want to check on the fly the td that have the new class (called selecting) and add them up.
This is the code I have so far, but, first it does not add them up, rather, appends one after the other, and also in some weird order:
$(document).ready(function() {
    total = '';

    $('td').click(function() {
        $(this).toggleClass('selecting');
        $('.selecting').live( {
            click: function() {
                if ($('td').hasClass('selecting')) {
                    total += $(this).html();
                }
            }
        })
        $('#feedback').text(total);
    });
})

A subsquent step would be that, on clicking again the td that were clicked, the sum is substracted for the value of the clicked again cell. So if newly clicked, adds, if clicked again, substracts, but that is like a second step, too difficult for me to do all at once first.

A: total += +$(this).text();

When adding a string to another string, you're concatenating. If you want to addition, you need to work with numbers. The + changes a string to a number.
Also, change total = ''; for total = 0;.

A: Try this:
$('td').click(function() {
    var $td = $(this);
    var total = 0;
    $td.toggleClass('selecting');

    $(".selecting").each(function() {
       total += parseInt($(this).text(), 10);
    });

    $('#feedback span').text(total);
});

Example fiddle
You'll see in the code that for each click it completely re-calculates the total, this negates the need to store the total between clicks so that you can subtract the clicked value. It makes the logic a lot simpler.
Also I've removed live() firstly because live() is now deprecated and should not be used, and secondly because you don't need to use it.


text:
Q: Paste multiple cells into a single cell using VBA I am trying to code several buttons to help out with archiving information into neat data.
But the value spreads over several rows.
I need it to go into a single cell.
Also would be swell if i could clear the copied data of all formatting and use the paste workbook as format "giver"
I am very new to Coding and mostly read up and copy pasted information. Nothing of value tried
Sheet4.Range("D25", Workbooks("Underlag.xlsm").Worksheets("EU").Cells(Rows.Count, "D").End(xlUp)).Copy Workbooks("Arkiv.xlsm").Worksheets("EU").Range("E" & Rows.Count).End(xlUp)(2)

Expected result is to have to copied data go into a single cell,
actual result is that it spreads over rows ruining data from other buttons.

A: Maybe you can try this :
Sub test_paste()

    Dim allData As String
    Dim rng As Range
    Dim cell As Range
    Dim pasteRng As Range

    Set rng = Sheet4.Range("D25", Workbooks("Underlag.xlsm").Worksheets("EU").Cells(Rows.Count, "D").End(xlUp))
    Set pasteRng = Workbooks("Arkiv.xlsm").Worksheets("EU").Range("E" & Rows.Count).End(xlUp)

    For Each cell In rng
        If Not IsEmpty(cell.Value) Then
            allData = allData & cell & " "
        End If
    Next

    pasteRng = allData

End Sub

It appends the values of each individual cells in the original range into a string, then puts that string in the chosen cell.
note: I tried this in only one sheet, not across different workbook


text:
Q: Redis Sentinel read from a slave server I am using redis server for my production environment and for HA I am using redis sentinel. But reading the documentation, when a client connects to the sentinel, sentinel gives client the master redis server.
Are all read and write operations are carried on the master server and the slave servers are only for failover or we can use the slave servers to read the data from?

A:
But reading the documentation, when a client connects to the sentinel, sentinel gives client the master redis server.

Not quite, it will give you what you request from it. If you ask for the master, you get the master. If you ask for the slaves, it will return the list of slaves. You use sentinel master <name> to get the master, and sentinel slaves <name> for the list of slaves.
Thus if you want to do read-only operations on slaves, use a sentinel connection to get the slave list, then open a connection to one or more of those slaves. The tricky part will be that you will want your code to watch for and detect failovers so you know if your slave has been promoted and you can get the new slave list to use.
sidenote: don't think of it as "connecting to redis via sentinel". The would be as inaccurate as saying you "connect to a web server via DNS server" - sentinel is your lookup service, not a proxy connection.


text:
Q: Windows Explorer: Create File Shortcut and Select it In Windows 7, when you created a file/folder shortcut in the Windows Explorer, then the shortcut was automatically selected which made it easy to cut/copy that shortcut somewhere else.
But in Windows 8/10, when you create a file/folder shortcut, the shortcut is not selected.
Is there any configuration to make Windows 8/10 to select the created shortcut?
Thanks in advance,


text:
Q: Example of web development local and production environment sample setup and workflow I am working on moving our existing websites from a shared hosting to a VPS and then they will be redeveloped and improved using Laravel. My background is not software development, I have however a decent understanding of web development (enough to make a blog, CMS etc) BUT I have never worked in a web dev team so I don't know how things should be done "properly".
Locally I have always used XAMPP and remotely it has always been as basic as publishing files via Filezilla.
Now I have been required to do:

*

*Version control - the changes to the website should be reviewed by a second (non technical person) before going live

*Develop a system based on Laravel

What I am struggling to understand is how Ubuntu Server, GIT, Docker, Kubernetes, NGINX etc. all work together. Basically I don't know what "the big picture" looks like, how a decent workflow should look like.
So far I have manually installed all the necessary software to run Laravel on the VPS (the LAMP stack) but soon after I started to run into problems (libraries that are activated locally are not activated remotely). It has also become clear that software updates and differences between my local environment and remote (production environment) will make the issues worst over time.
Can someone explain in VERY general terms, how things should fit together so that my setup is both resilient, robust and scalable? For example:

*

*Install docker on the server and on your computer

*Download such and such image

*connect GIT in such and such way

*Enable unattended-upgrades

The more I read the more I get confused.
What I would like is a simple guide/idea on how things should be done properly.