text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to write a spirial function in python? I'm trying to write a function in python that takes two arguments (x,y), and returns an angle in degrees in a spiraling direction.
Suppose the center of the spiral is at location (x0,y0). Then given (0,0), it returns 45. Given some other point say (0,90) which is the second intersection from the top on the y axis, the angle is around 170. For any point not touching the red line, it should return an angle of what you would expect the direction to be. The spiral is just a general thing to show the direction of the angles.
Does anyone know how to write such a function?
Thanks
A: That's an Archimedean spiral curve. As the page says in polar coordinates the formula of the curve is r = aθ, usually the scalar a is 1 i.e. r = θ. Polar to cartesian conversion is
x = r cos θ, y = r sin θ
Hence
x = θ cos θ, y = θ sin θ
Varying θ from 0 to 6π would give the curve you've. When you vary the parameter θ and get x and y values what you get would be relative to the origin (0, 0). For your case, you've to translate i.e. move the points by the x and y offset to position it accordingly. If you want a bigger version of the same curve you've to scale (before translation) i.e. multiply both x and y values by a constant scalar.
A: (I think the spiral image is more confusing than helpful...)
for a point (x, y), you want to get back the angle theta in degrees, where (1,0) is at 0 degrees and (0, 1) is at 90 degrees.
So we want to find theta. Using trigonometry, we know that x is the adjacent side and y is the opposite side, and tan(theta) == y/x.
This is slightly confused by the fact that tan() repeats every 180 degrees - tan(y/x) == tan(-y/-x). Luckily, Python has a built-in function, atan2, that compensates for that. It returns theta in radians, and we convert that to degrees, like so:
from math import atan2, degrees
x, y = (2, 2)
theta = degrees(atan2(y, x)) # => theta == 45.0
however atan2 returns values in -2*pi < theta <= 2*pi (-179.9... to +180 degrees); you want it in (0.. 359.9...) degrees:
theta = (degrees(atan2(y, x)) + 360.0) % 360.0
A: You want a vector field where one of the trajectories is the Archimedean spiral.
If you take the spiral formula
x = θ cos θ, y = θ sin θ
from the answer of legends2k and compute its tangent, you get
vx = cos θ - θ sin θ, vy = sin θ + θ cos θ
Elimination of θ for x and y in the most straightforward way gives the general vector field
vx = x/r-y, vy = y/r + x, where r=sqrt(x^2+y^2).
The angle of the vector field is then obtained as atan2(vy,vx).
A: If someone could verify this I'd appreciate it.
This solution allows you to have a radius which grows at a different rate then the angle
radius:
r(t) = r_scalar * t
d(r(t))/dt = r_scaler
degrees:
a(t) = a0 + a_scalar * t
d(a(t))/dt = a_scaler
location:
x(t),y(t) = x0 + r(t)*cos(a(t)), y0 + r(t)*sin(a(t))
Now we can compute the direction of any t as:
d(x(t))/dt = r(t)*(-sin(a(t))*d(a(t))/dt) + d(r(t))/dt*cos(a(t))
d(y(t))/dt = r(t)*(cos(a(t))*d(a(t))/dt) + d(r(t))/dt*cos(a(t))
which simplifies:
d(x(t))/dt = r(t)*(-sin(a(t))*a_scaler) + r_scaler*cos(a(t))
d(y(t))/dt = r(t)*(cos(a(t))*a_scaler) + r_scaler*sin(a(t))
to get the a value of t for a,b such that it is closest to x(t),y(t). you can first approximate saying the distance x0,y0 to x1,y1 will satisfy r(t).
t0 = sqrt((x0 - x2)^2 + (y0 - y1)^2)/r_scalar
seeing that the closest point in the spiral will be at the same degree, adjust t minimally such that the angle is satisfied.. ie
t1 = t0-t2 where atan((y0 - y1)/(x0 - x2)) = (a0 + a_scalar * t0) % 2*pi - (a0 + a_scalar * t2)
thus
t2 = (((a0 + a_scalar * t0) % 2*pi) - atan((y0 - y1)/(x0 - x2)) + a0)/a_scalar
then the closest direction angle is atan((d(x(t0-t2))/dt / d(y(t0-t2))/dt))
A: import numpy as np
import matplotlib.pyplot as plt
import math
def fermat_spiral(dot):
data=[]
d=dot*0.1
for i in range(dot):
t = i / d * np.pi
x = (1 + t) * math.cos(t)
y = (1 + t) * math.sin(t)
data.append([x,y])
narr = np.array(data)
f_s = np.concatenate((narr,-narr))
return f_s
f_spiral = fermat_spiral(20000)
plt.scatter(f_spiral[len(f_spiral)//2:,0],f_spiral[len(f_spiral)//2:,1])
plt.scatter(f_spiral[:len(f_spiral)//2,0],f_spiral[:len(f_spiral)//2,1])
plt.show()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22898555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to tell when AxWindowsMediaPlayer is downloading? I am using AxWindowsMediaPlayer on VB.NET to preview MP3 files from the web so that the user can choose to download it if he likes it. It works. I just put a link in the URL property and after a while it begins playing.
... after a while, of course. Because it has to download the file first. Perhaps I realized that because of my slow connection XD.
But that made me think: how can I tell if the player is currently downloading a file? So that I can put a label saying "Please wait, preparing file..." or something.
A: Look at using the Buffering Event and the BufferingProgress Property. According to the MSDN Link:
Use this event to determine when buffering or downloading starts or stops. You can use the same event block for both cases and test IWMPNetwork.bufferingProgress and IWMPNetwork.downloadProgress to determine whether Windows Media Player is currently buffering or downloading content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10407123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android: Issue creating Custom 3 state toggle button I'm trying to create a 3 state toggle button by overriding the Button class.
Although, there is no error in the code, but Eclipse is showing following issue in layout xml.
The following classes could not be instantiated:
- com.example.threewaytoggle.TriToggleButton (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.
Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse
And in the error log, this is coming:
com.example.threewaytoggle.TriToggleButton failed to instantiate.
java.lang.NullPointerException
at android.view.View.mergeDrawableStates(View.java:7506)
at com.example.threewaytoggle.TriToggleButton.onCreateDrawableState(TriToggleButton.java:42)
at android.view.View.getDrawableState(View.java:7410)
at android.view.View.setBackgroundDrawable(View.java:7583)....
Following is the code:
Layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.example.threewaytoggle.TriToggleButton
android:id="@+id/triToggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TriToggleButton" />
</LinearLayout>
Custom Button Class:
package com.example.threewaytoggle;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
public class TriToggleButton extends Button {
int _state = 0;
public TriToggleButton(Context context) {
super(context);
_state = 0;
this.setText("1");
}
public TriToggleButton(Context context, AttributeSet attrs) {
super(context, attrs);
_state = 0;
this.setText("1");
}
public TriToggleButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
_state = 0;
this.setText("1");
}
private final int[] STATE_ONE_SET = { R.attr.state_one };
private final int[] STATE_TWO_SET = { R.attr.state_two };
private final int[] STATE_THREE_SET = { R.attr.state_three };
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 3);
if (_state == 0) {
mergeDrawableStates(drawableState, STATE_ONE_SET);
} else if (_state == 1) {
mergeDrawableStates(drawableState, STATE_TWO_SET);
} else if (_state == 2) {
mergeDrawableStates(drawableState, STATE_THREE_SET);
}
return drawableState;
}
@Override
public boolean performClick() {
nextState();
return super.performClick();
}
private void nextState() {
_state++;
if (_state > 2) {
_state = 0;
}
setButtonText();
}
private void setButtonText() {
//TODO
}
public int getState() {
return _state;
}
}
A: Found it....Only static was missing in:
private static final int[] STATE_ONE_SET = { R.attr.state_one };
private static final int[] STATE_TWO_SET = { R.attr.state_two };
private static final int[] STATE_THREE_SET = { R.attr.state_three };
But how come this creates a problem...?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12329987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cron run my Python script but nothing is happening I want to run a Python script every night at 12:00 am to clean up a csv file which is automatically filled in during the day by another script.
My csv file code_list.csv content looks like this at the end of the day:
87698
63753
19742
89876
62765
79832
# etc.
I use the truncate method to clean the csv file with this script csvclean.py :
import csv
filename = "/root/folder/code_list.csv"
f = open(filename, "w")
f.truncate()
f.close()
and here is my crontab:
SHELL=/bin/bash
0 0 * * * cd /root/folder && /usr/bin/python3 ./csvclean.py
Both files are located in the same folder /root/folder.
I can see in /var/log/syslog that the cron is running at the scheduled time but nothing is happening inside my code_list.csv file. While if I run the script directly using python3 csvclean.py it cleans up the csv file perfectly.
What have I forgotten?
- EDIT -
I used a method found here to retrieve logs.
I edited my crontab like this:
*/1 * * * * cd /root/folder && /usr/bin/python3 ./csvclean.py > /root/folder/csvclean.log 2>&1
and I added this line at the beginning of the csvclean.py script:
print 'starting'
I opened the csvclean.log file after the cron and I saw:
/usr/bin/python3: can't open file './csvclean.py': [Errno 2] No such file or directory
Which made me realize that my Python script file name is cleancsv.py and not csvclean.py.
It was under my eyes...
A: Run this command: sudo /etc/init.d/cron restart
after setting crontab demon has to restart.
Also check sys/log for tracing what is issue while running script.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62812613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: google maps resize event The problem is start the map hidden, if the toggle buttom start showing the map there isn't any ploblem.
I'm seeing a lot of question with this problem but I can't fix it. This is my code. I call the resize event after toogle the map and doen't work.
$('.map-btn').click(function(){
$(this).next().toggle(500, function(){
var gMap = document.getElementById("acf-map");
google.maps.event.trigger(gMap, 'resize');
});
})
Related question here Google Maps v3 load partially on top left corner, resize event does not work
A: Form my experience is better recall a (re)initilizeMap() function when you click the tab for show the map.
Due the problem/difficulties related to the correct congfiguration of the map in this case if you, wher click the tab for show the map call the initializzazion of the map. the problem is structurally solved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33876810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Getting a GIT change summary like GitHub I've got a group of developers which make GIT commit and merge mistakes (once in a while).
I would like to monitor for 'large changes' somehow. I see in GitHub that they have the following line when looking at the details of a specific commit:
Showing 759 changed files with 21,736 additions and 3,237 deletions.
That is an example of a real merge that should have only had 1 file changed and several additions/deletions.
Is there some way or some tool that exists that would send out an alert via email or SMS when a commit breaches a configured threshold?
If not, I was wondering if it was possible to generate that same type of output using the GIT command line. That way, if no tool exists, I can easily script it and send out an email with my own tools.
Update: 2014-03-20 18:52
Based on nulltoken's suggestion, I've tried the following command:
git diff --shortstat $(git rev-parse HEAD HEAD^)
And got exactly what I needed (for the very last commit anyway). Oddly enough though, what I just observed is that GitHub (1) provides the following numbers, compared to what my GIT provides (2):
1 : 759 changed files with 21,736 additions and 3,237 deletions.
2 : 759 files changed, 3237 insertions(+), 21736 deletions(-)
So somebody clearly has a bug! Either GitHub or my GIT (version 1.7.10.4)... funny!
Update: 2014-03-20 19:05
Correction, I simply inverted my hashes and it fixed it... my mistake! No bug to report.
A:
if it was possible to generate that same type of output using the GIT command line. That way, if no tool exists, I can easily script it and send out an email with my own tools.
You may be after one of the following options of git diff
*
*git diff --stat <from_commit> <until_commit>
*git diff --shortstat <from_commit> <until_commit>
Those commands, when ran against the LibGit2Sharp project, output the following
$ git diff --stat a4c6c45 14ab41c
LibGit2Sharp.Tests/StashFixture.cs | 3 ++-
LibGit2Sharp/Core/NativeMethods.cs | 8 +++-----
LibGit2Sharp/Core/Proxy.cs | 18 +++++++++---
LibGit2Sharp/ReferenceCollection.cs | 5 ++++-
4 files changed, 18 insertions(+), 16 deletions(-)
$ git diff --shortstat a4c6c45 14ab41c
4 files changed, 18 insertions(+), 16 deletions(-)
You'll note that this is pretty much the same content than from the GitHub page showcasing those changes (Note: Clicking on the "Show Diff Stats" will show the per file counts).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22546125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JPQL NEW operator with native query ? Can I use the NEW JPQL operator to map result of query inside DTO ?
I tested this code :
Query query = em.createNativeQuery("SELECT NEW com.sim.dtos.entities.FreeLocation(t1.galaxie, t1.ss, t1.position) FROM ...");
List<FreeLocation> l = query.getResultList();
But I have exception :
[#|2012-12-20T12:9:21.203+0100|WARNING|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=79;_ThreadName=Thread-2;|StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
org.postgresql.util.PSQLException: ERREUR: erreur de syntaxe sur ou près de « . »
Position : 15
So can I use NEW operator with native query please ?
A: A native query, by definition, is a SQL query. It must contain valid SQL for your specific database.
The query will return a List<Object[]>, and it should be trivial to iterate through the list and create a new instance of FreeLocation for each Object[] array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13971125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: R_Extracting data for a particular date form a zoo object Hi I have a zoo time series (interval-1 min) contains rainfall data from multiple rain gauges for a month which looks like
head(precApr)
RG.1 RG.2 RG..4 RG.5 RG.6 RG.7 RG.8 RG.9 RG.10 RG.12 RG.13
2008-04-06 00:00:00 0 0 0 0 0 0 0 0 0 0 0
2008-04-06 00:01:00 0 0 0 0 0 0 0 0 0 0 0
2008-04-06 00:02:00 0 0 0 0 0 0 0 0 0 0 0
2008-04-06 00:03:00 0 0 0 0 0 0 0 0 0 0 0
2008-04-06 00:04:00 0 0 0 0 0 0 0 0 0 0 0
2008-04-06 00:05:00 0 0 0 0 0 0 0 0 0 0 0
RG.14 RG.15 RG.16 RG.17 RG.18
2008-04-06 00:00:00 0 0 0 0 0
2008-04-06 00:01:00 0 0 0 0 0
2008-04-06 00:02:00 0 0 0 0 0
2008-04-06 00:03:00 0 0 0 0 0
2008-04-06 00:04:00 0 0 0 0 0
2008-04-06 00:05:00 0 0 0 0 0
Now I want to extract the data for a particular date, say 25. I used the following code using xts::.indexDate
precAprxts=as.xts(precApr)
precApr25=precAprxts[.indexDate(25)]
But this just gives the following answer whereas I would expect a time series of that day
precApr25
## RG.1 RG.2 RG..4 RG.5 RG.6 RG.7 RG.8 RG.9 RG.10 RG.12 RG.13 RG.14 RG.15
## RG.16 RG.17 RG.18
Does anybody know what's the problem with my code or Is there are any other method to do it? Thanks in advance.
A: If z is a zoo series (as stated in the question) then subscripting and window should both work. In the second and third examples we have assumed that the index is of POSIXct class:
z[4, ] # fourth row
window(z, as.POSIXct("2008-04-06 00:03:00"))
window(z, as.POSIXct("2008-04-06")) # assumes time is 00:00:00
Added One can also subscript with a time:
z[as.POSIXct("2008-04-06 00:00:00"), ]
z[as.POSIXct("2008-04-06 00:00:00")] # same
See ?window.zoo for more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28302275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get more than one string as a variable into input separated by space I'm using Python 3.
I need to get three values from a input (separated by a space). The values are a integer, a string and a integer again.
Consider that the string can have more than one word.
If I set two words it does not work, because each word is like a value.
My code into the momment is:
list_a = {}
list_b = []
for i in range(4):
input_values = input("Press {}, {} and {}".format("id1", "name", "id2"))
id1, name, id2 = input_values.split()
list_a["id1"] = id1
list_a["name"] = name
list_a["id2"] = id2
list_b.append(dict(list_a))
print(list_b)
If my input is something like 1 name_ok 0, it works. But if my input is something like 1 pasta ok 0, doesn't works because 3 values are expected, not 4.
How could I do to consider that any character between the two integer values was the variable name?
Sorry about the english xD
A: You don't necessarily know that id2 is the third argument; it's the last argument. You can gather all the intervening arguments into a single tuple using extended iterable unpacking. Once you have the tuple of middle arguments, you can join them back together.
id1, *names, id2 = input_valores.split()
list_a["id1"] = int(id1)
list_a["name"] = " ".join(names)
list_a["id2"] = int(id2)
This is somewhat lossy, as it contracts arbitrary whitespace in the name down to a single space; you get the same result of 1, "foo bar", and 2 from "1 foo bar 2" and "1 foo bar 2", for instance. If that matters, you can use split twice:
# This is the technique alluded to in Ignacio Vazquez-Abrams' comment.
id1, rest = input_valores.split(None, 1)
name, id2 = rest.rsplit(None, 1)
rsplit is like split, but starts at the other end. In both cases, the None argument specifies the default splitting behavior (arbitrary whitespace), and the argument 1 limits the result to a single split. As a result, on the first and last space is used for splitting; the intermediate spaces are preserved.
A: You can use slicing.
args = input('Enter ID, name, and second ID').split()
id1 = int(args[0])
id2 = int(args[-1])
name = " ".join(args[1:-1])
A: you could use python's slicing notation for this
input_values = input("Press {}, o {} e o {}".format("id1", "name", "id2"))
listSplit = input_values.split()
id1 = listSplit[0]
name = join(listSplit[1:-1])
id2 = listSplit[-1]
def join(arr):
newStr = ""
for i in arr:
newStr += i + " "
return newStr[:-1]
where id1 is the first word, name is everything between the first index and the last which has been joined into one string and the third argument which is actually the last word.
Hope that helps.
A: this will work:
split = input_values.split()
id1 = int(split[0])
id2 = int(split[-1])
name = " ".join(split[1:-1])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49984224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Xwiki Access Rights (AppWithinMinutes) I apologize if the question has already been asked. I made an application with “AppWithinMinutes” in Xwiki. In this application I get user information (eg name, age, etc.)
My application will be 100-150 users.
Each user will enter information.
I have studied these connections:
https://www.xwiki.org/xwiki/bin/view/Documentation/AdminGuide/Access%20Rights/
https://www.xwiki.org/xwiki/bin/view/Documentation/AdminGuide/Access%20Rights/Permission%20types/
My English is a little bad. :slight_smile:
In my application every user just want to see their own information
For example, the AA user only sees the information he enters.
I don’t want you to see the information that other users have entered.(for example, CC,DD,EE users…etc)
How do I do this?
Thanks for your help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51410255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I tell if CLLocationManager is actively scanning for a beacon? When you set up an iOS device as a beacon (peripheral role), you can query its state by calling CBPeripheralManager.isAdvertising. I can't find the equivalent to query whether a device is scanning for a beacon (central role) on CLLocationManager. Any ideas?
Update:
Given David's answer, I encapsulated the code setting up the CLBeaconRegion with the specific UUID and added a boolean variable which is changed when calling startMonitoringRegion and stopMonitoringRegion on CLLocationManager.
A: I do not believe there is any way this is possible. Even though CoreLocation's iBeacon APIs use Bluetooth LE and CoreBluetooth under the hood, Apple appears to have gone to some lengths to hide this implementation. There is no obvious way to see whether a Bluetooth LE scan is going on at a specific point in time.
Generally speaking, a Bluetooth LE scan is always going on when an app is ranging for iBeacons in the foreground. When an app is monitoring for iBeacons (either in the foreground or background) or ranging in the background, indirect evidence suggests that scans for beacons take place every few minutes, with the exact number ranging from 1-15 depending on phone model and state. I know of no way to programmatically detect the exact times when this starts and stops, although it can be inferred by iBeacon monitoring entry/exit times. If you look at the graph below, the blue dots show the inferred scan times for one particular test case. Details of how I inferred this are described in this blog post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23478252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NewtonSoft json parsing Can somebody help me to parse the json and get the details.
Lets say i have Top2 input parameter as Police and i want to know the respective Top3 and in that Top3 array i need to check whether Test1Child value is there or not.
I am using newtonsoft json + c# and so far i can get till DeviceTypes using below code
var json = File.ReadAllText(jsonFile); // below json is stored in file jsonFile
var jObject = JObject.Parse(json);
JArray MappingArray =(JArray)jObject["Top1"];
string strTop1 = ObjZone.Top1.ToString();
string strTop2 = ObjZone.Top2.ToString();
var JToken = MappingArray.Where(obj => obj["Top2"].Value<string>() == strTop2).ToList();
//Json
{
"Top1": [
{
"Top2": "Test1",
"Top3": [
"Test1Child"
]
},
{
"Top2": "Test2",
"Top3": [
"Test2Child"
]
}
]
}
A: I'd use http://json2csharp.com/ (or any other json to c# parser) and then use C# objects (it's just easier for me)
This would look like that for this case:
namespace jsonTests
{
public class DeviceTypeWithResponseTypeMapper
{
public string DeviceType { get; set; }
public List<string> ResponseTypes { get; set; }
}
public class RootObject
{
public List<DeviceTypeWithResponseTypeMapper> DeviceTypeWithResponseTypeMapper { get; set; }
}
}
and the use it like that in code:
var rootob = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(str);
var thoseThatHaveNotUsed = rootob.DeviceTypeWithResponseTypeMapper.Where(dtwrtm =>
dtwrtm.ResponseTypes.Any(rt => rt == "NotUsed"));
foreach (var one in thoseThatHaveNotUsed)
{
Console.WriteLine(one.DeviceType);
}
this code lists all the Device types that have "NotUsed" among the responses.
version 2 (extending your code) would look like that, i believe:
static void Main(string[] args)
{
var json = str; // below json is stored in file jsonFile
var jObject = JObject.Parse(json);
JArray ZoneMappingArray = (JArray)jObject["DeviceTypeWithResponseTypeMapper"];
string strDeviceType = "Police";
string strResponseType = "NotUsed";
var JToken = ZoneMappingArray.Where(obj => obj["DeviceType"].Value<string>() == strDeviceType).ToList();
var isrespTypeThere = JToken[0].Last().Values().Any(x => x.Value<string>() == strResponseType);
Console.WriteLine($"Does {strDeviceType} have response type with value {strResponseType}? {yesorno(isrespTypeThere)}");
}
private static object yesorno(bool isrespTypeThere)
{
if (isrespTypeThere)
{
return "yes!";
}
else
{
return "no :(";
}
}
result:
and if you'd like to list all devices that have response type equal to wanted you can use this code:
var allWithResponseType = ZoneMappingArray.Where(jt => jt.Last().Values().Any(x => x.Value<string>() == strResponseType));
foreach (var item in allWithResponseType)
{
Console.WriteLine(item["DeviceType"].Value<string>());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49874755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save query results in blocks of 1000 rows I have the query
EXEC xp_cmdshell 'bcp "select * from foo.dbo.bar" QUERYOUT "c:\temp\export.csv" -c -t, -T -S'
Which exports fine to that file, but is it possible to break it down so that the first 1000 rows go into export.csv then the next 1000 rows go into export2.csv (etc etc)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26363614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Conform on-the-fly to PEP8 using flycheck on emacs I unpack flycheck to ~/. and put the following lines in ~/.emacs:
;; (package-initialize)
(setq load-path (cons "~/flycheck-20170415.1006" load-path))
(require 'flycheck)
(add-hook 'after-init-hook #'global-flycheck-mode)
Starting Emacs 24.5.1 I get:
File error: Cannot open load file, no such file or directory, let-alist
With Emacs 25.1.1 I get:
File error: Cannot open load file, No such file or directory, dash
(These errors do not change if I uncomment (package-initialize). Emacs 25 now inserts (package-initialize), nudging those of us with a long setup to adapt.)
My (subsequent) aim is to conform Python code on-the-fly to PEP8. Once the problem above is resolved, I'll add
(setq exec-path (append exec-path '("/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin")))
to this brief ~/.emacs (/opt/..2.7/bin is where MacPorts put flake8), but there is apparently an issue before I even specify the programming language.
Update
This is far more painful than I expected. Flycheck is heavy-handed about being installed through packages, and incorporating the steps described here to my usual ~/.emacs leads to the notorious
load-with-code-conversion: Symbol’s value as variable is void: <!DOCTYPE
error. (I'm pretty sure I have no HTML files hiding under a .el extension.)
Update2
Uh.. I stand corrected! Some dash.el made its way to my usual elisp directory, and flycheck depends on it, but it was indeed an HTML file.
A: Flycheck depends on dash, let-alist, and seq.
Download the files
84766 dash.el
381142 flycheck.el
6136 let-alist.el
17589 seq-24.el
17684 seq-25.el
1540 seq.el
and put them in ~/.concise-elisp. You need three files for seq because it has alternative implementations for Emacs 24 & 25.
Put the following lines in your ~/.emacs:
;; Even if you are not using packages, you need the following
;; commented-out line, or else Emacs 25 will insert one for you.
;; (package-initialize)
(setq load-path (cons "~/.concise-elisp" load-path))
(require 'flycheck)
(add-hook 'after-init-hook #'global-flycheck-mode)
(setq exec-path (append exec-path '("/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin")))
The last line points to where MacPorts would have put flake8. Flake8 is one of the programs to which flycheck delegates PEP8 checking.
Next exercise: Hook flycheck just for Python (and perhaps C/C++/Java/JS/..). In particular, don't worry about making elisp files kosher. Selectively activate flycheck for languages as needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43524859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Stack Overflow corrupt %ebp I'm trying to study for an exam, and looking over stack overflow stuff i was hoping someone could clear something up for me. (assume this is on a 32 bit system, so that all addresses are 4 bytes. Also I am studying it from a C function, so any code referenced is from C)
Say our code wants to take in buf[4] from standard input, and so it creates a four byte buffer. If we use the version of gets() that does not check for out of bounds, and input the string "12345" we will corrupt the saved %ebp on the stack. This will not, however, change the return address. Does this mean that the program will continue executing the correct code, since the return address is correct, and it will still go back into the calling function? Or does the corrupted %ebp mean trouble further down the line.
I understand that If we input something larger like "123456789" it would also corrupt the return address, thus rendering the program inoperable.
A: EBP is the base pointer for the current stack frame. Once you overwrite that base pointer with a new value, subsequent references to items on the stack will reference not the actual address of the stack, but the address your overwrite just provided.
Further behavior of the program depends on whether and how the stack is subsequently used in the code.
A: What exactly is corrupted heavily depends on generated code, so this is rather compiler and settings dependant. You also don't know if really ebp would be corrupted. Often compilers add additional bytes to the variables, so with one byte overrun nothing might happen at all. On newer Visual Studio code I saw that some safeguard code is added, which causes an exception to be thrown.
If the return address is corrupted, this can be used as an entrypoint for exploits installing their own code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20665996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: cordova ios build plugin Failed to restore I have simple cordova project that I made 1,5 years ago.
Few months ago I build it to android and it worked.
Now I try to build it for iOS but cordova build ios fails:
Discovered plugin "InAppBrowser" in config.xml. Adding it to the project
Failed to restore plugin "InAppBrowser" from config.xml. You might need to try adding it again. Error: Error: Registry returned 404 for GET on https://registry.npmjs.org/InAppBrowser
Discovered plugin "Network Information" in config.xml. Adding it to the project
Failed to restore plugin "Network Information" from config.xml. You might need to try adding it again. Error: Error: Invalid package.json
Building project: /Users/user1/projectname/platforms/ios/projectname.xcworkspace
Macbook, sierra, Xcode 8.1
npm version
{ npm: '3.10.9',
ares: '1.10.1-DEV',
http_parser: '2.7.0',
icu: '57.1',
modules: '48',
node: '6.9.2',
openssl: '1.0.2j',
uv: '1.9.1',
v8: '5.1.281.88',
zlib: '1.2.8' }
cordova version 6.5.0
In my config.xml it says:
-->
I commented out the first one but the second one does not work either
A: You will need to update you plugins to latest version, since as I assume you must have added ios as platform more recently and plugins would have been added 1.5 years ago.
So those plugins must have already been fetched into plugins directory 1.5 years ago and must be of lower version to whats recently available.
Also you must update your cordova version to latest. You update it by below command
npm install -g cordova@latest
You can fire below command inside you app directory from command line, to get names of plugins.
cordova plugins ls
Note down all plugins names. (e.g. cordova-plugin-splashscreen)
Remove each one of them by below command.
cordova plugin rm cordova-plugin-splashscreen
After all of them have been removed add them again using below command.
cordova plugin add cordova-plugin-splashscreen
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42391538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Turn pandas dataframe column into float I need to turn a pandas dataframe column into a float. This float is taken from a larger csv file. To get just the number I need to a dataframe I did:
m_df = pd.read_csv(input_file,nrows=1,header=None,skiprows=4)
m1=m_df.ix[:,1:1]
This gets me the dataframe with just the number I want in the first column. How do I turn that number into a float?
A: float((m_df.ix[:,1:1]).values)
For pandas dataframes, type casting works when done on the values, rather than the dataframe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34312708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: join() function doesnt work in javascript I tried using the join() function in my array and tried to document.write it but
the console says"birth.join() is not a function "
birthyear=[];
for(i=1800;i<2018;i++){
birthyear+=i
}
birth=birthyear.join();
document.write(birth);
A: Array.prototype.join() works on array and to insert an element to array you should call .push() instead of +=, read more about += here.
Always use var before declaring variables, or you end up declaring global variables.
var birthyear = [];
for (i = 1800; i < 2018; i++) {
birthyear.push(i);
}
var birth = birthyear.join(", ");
document.write(birth);
A: I your code your not appending data to array you are adding data to array variable which is wrong
1st Way
birthyear=[];
for(i=1800;i<2018;i++)
{
birthyear.push(i);
}
birth=birthyear.join();
document.write(birth);
2nd Way
birthyear=[];
k=0;
for(i=1800;i<2018;i++){
birthyear[k++]=i;
}
birth=birthyear.join();
document.write(birth);
A: You can't apply .push() to a primitive type but to an array type (Object type).
You declared var birthyear = []; as an array but in the body of your loop you used it as a primitive: birthyear+=i;.
Here's a revision:
var birthyear=[];
for(let i=1800;i<2018;i++){
birthyear[i]=i;
// careful here: birthyear[i] += i; won't work
// since birthyear[i] is NaN
}
var birth = birthyear.join("\n");
document.write(birth);
Happy coding! ^_^
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48959758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Confused on the css name css:
.a .b { position: relative; }
.c { position: relative; }
Then I though it would work the same way if I wrote it like this:
.a .b .c { position: relative; }
however, it doesn't, it has no effect about .c. So why it's not working when I put them together?
A: what you want is
.a .b, .c { position: relative; }
.a .b .c expects this
<div class="a">
<div class="b">
<div class="c"></div>
</div>
</div>
having a comma means .a .b OR .c
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32977523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Very large plots - generated on the fly? I have two very simple functions in python that calculate the size of a struct (C struct, numpy struct, etc) given the range of numbers you want to store. So, if you wanted to store numbers from 0 to 8389798, 8389798 would be the value you feed the function:
def ss(value):
nbits = 8
while value > 2**nbits:
nbits += 8
return nbits * value
def mss(value):
total_size = 0
max_bits = [(0,0)] # (bits for 1 row in struct, max rows in struct)
while value > 2 ** max_bits[-1][0] :
total_size += max_bits[-1][0] * max_bits[-1][1]
value -= max_bits[-1][1]
new_struct_bits = max_bits[-1][0]+8
max_bits.append( (new_struct_bits,2**new_struct_bits) )
total_size += max_bits[-1][0] * value
#print max_bits
return total_size
ss is for a single struct where you need as many bytes in the first row to store "1" as you would in the last row to store "8389798". However, this is not as space efficient as breaking your struct up into structs of 1 byte, 2 bytes, 3 bytes, etc, up until N bytes needed to store your value. This is what mss calculates.
So now i want to see how much more efficient mss is over ss for a range of values - that range being 1 to, say, 100 billion. That's much to much data to save and plot, and it's totally unnecessary to do so in the first place. Far better to take the plot window, and for every value of X that has a pixel in that window, calculate the value of y [which is ss(x) - mss(x)].
This sort of interactive graph is really the only way i can think of to look at the relationship between mss and ss. Does anyone know how i should plot such a graph? I'm willing to use a JavaScript solution because I can rewrite the python to that, as well as use "solutions" like Excel, R, Wolfram, if they offer a way to do interactive/generated graphs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40548448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cloud code not working i am new at parse..trying code..trying to run a trigger required in my project.but not able to track not even i am getting any error.
i am using cloud code i.e triggers...
what i want to do is, after update or save i want to run a trigger which will a column in a class with value of 200.
Parse.initialize('APPLICATION_ID', 'JAVASCRIPT_KEY');
Parse.Cloud.afterSave("match_status", function(request)
{
var query = new Parse.Query('Wallet');
query.set("wallet_coines_number", 200);
query.equalTo("objectId", "FrbLo6v5ux");
query.save();
});
i am using afterSave trigger in which match_status is my trigger name. after that i making a object called query of Wallet class. This object will set column 'wallet_coines_number' with the value 200 where objectId is FrbLo6v5ux. after that i used save function which will execute query.
Please guide me if i am wrong, or following wrong approach.
Thank You !
A: Have you read the Parse documentation on Cloud Code ?
The first line of your code is only relevant when you are initialising Parse JavaScript SDK in a web page, you do not need to initialise anything in Parse cloud code in the main.js file. Also you cannot use a query to save/update an object. A query is for searching/finding objects, when you want to save or update an object you need to create a Parse.Object and save that.
So you code should become something like:
Parse.Cloud.afterSave("match_status", function(request) {
var wallet = new Parse.Object('Wallet');
wallet.set("wallet_coines_number", 200);
wallet.set("objectId", "FrbLo6v5ux");
wallet.save();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33823538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Underline expanding on mouseover I am trying to implement a magic line with jquery and CSS. But instead of it following and only inheriting the width, I want it to extend to the next index item.
Scenario:
1: Element one hover
ELEMENT ONE ELEMENT TWO ELEMENT THREE
___________
2: Element two hover
ELEMENT ONE ELEMENT TWO ELEMENT THREE
__________________________
3: Element three hover
ELEMENT ONE ELEMENT TWO ELEMENT THREE
__________________________________________
This is what I have got so far but unfortunately I cant seem to get the elements to expand in accordance with the width of the entire list.
$('.carousel-image ul').slick({
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
fade: true,
asNavFor: '.carousel-info ul',
adaptiveHeight: true,
mobileFirst: true,
});
$('.carousel-info ul').slick({
slidesToShow: 3,
slidesToScroll: 1,
asNavFor: '.carousel-image ul',
dots: true,
// centerMode: true,
focusOnSelect: true
});
var $el, leftPos, newWidth,
$mainNav = $(".carousel-info ul");
$mainNav.append("<li id='magic-line'></li>");
var $magicLine = $("#magic-line");
$magicLine
.width($(".carousel-info ul li.slick-current").width())
.css("left", $(".carousel-info ul li.slick-current").position().left)
.data("origLeft", $magicLine.position().left)
.data("origWidth", $magicLine.width());
$('.carousel-info ul').on('mouseenter', '.slick-slide', function(e) {
var $currTarget = $(e.currentTarget);
var index = $currTarget.data('slick-index');
var slickObj = $('.carousel-image ul').slick('getSlick');
slickObj.slickGoTo(index);
var $el = $(".carousel-info ul li.slick-current");
leftPos = $el.position().left;
newWidth = $el.width();
$magicLine.stop().animate({
left: leftPos,
width: newWidth
});
});
#magic-line {
position: absolute;
bottom: -2px;
left: 0;
width: 100px;
height: 2px;
background: #fe4902;
}
.carousel {
position: relative;
overflow: hidden;
max-height: 42em;
}
.carousel .carousel-info {
position: absolute;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: 9;
padding: 30px 0;
opacity: .9;
color: #fff;
background-color: #37474f;
}
.carousel .carousel-info .container {
border-width: 15px;
border-top: 4px solid black;
}
.carousel .carousel-info ul {
position: relative;
max-width: 930px;
margin-right: auto;
margin-left: auto;
}
.carousel .carousel-info ul:after {
display: block;
clear: both;
content: ' ';
}
.carousel .carousel-info li {
float: left;
width: 31.56342%;
margin-right: 2.65487%;
}
.carousel .carousel-info li:last-child {
float: right;
width: 31.56342%;
margin-right: 0;
}
.slick-slider {
position: relative;
display: block;
box-sizing: border-box;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-touch-callout: none;
-ms-touch-action: pan-y;
touch-action: pan-y;
-webkit-tap-highlight-color: transparent;
}
.slick-list {
position: relative;
display: block;
overflow: hidden;
margin: 0;
padding: 0;
}
.slick-list:focus {
outline: none;
}
.slick-list.dragging {
cursor: pointer;
cursor: hand;
}
.slick-slider .slick-track,
.slick-slider .slick-list {
-webkit-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.slick-track {
position: relative;
top: 0;
left: 0;
display: block;
}
.slick-track:before,
.slick-track:after {
display: table;
content: '';
}
.slick-track:after {
clear: both;
}
.slick-loading .slick-track {
visibility: hidden;
}
.slick-slide {
display: none;
float: left;
height: 100%;
min-height: 1px;
}
[dir='rtl'] .slick-slide {
float: right;
}
.slick-slide img {
display: block;
}
.slick-slide.slick-loading img {
display: none;
}
.slick-slide.dragging img {
pointer-events: none;
}
.slick-initialized .slick-slide {
display: block;
}
.slick-loading .slick-slide {
visibility: hidden;
}
.slick-vertical .slick-slide {
display: block;
height: auto;
border: 1px solid transparent;
}
.slick-arrow.slick-hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.js"></script>
<div class="carousel">
<div class="carousel-image">
<div class="container-big">
<ul>
<li>
<img src="https://placeholdit.imgix.net/~text?txtsize=101&txt=Example+1&w=400&h=300" />
</li>
<li>
<img src="https://placeholdit.imgix.net/~text?txtsize=101&txt=Example+2&w=400&h=300" />
</li>
<li>
<img src="https://placeholdit.imgix.net/~text?txtsize=101&txt=Example+3&w=400&h=300" />
</li>
</ul>
</div>
</div>
<div class="carousel-info">
<div class="container">
<ul>
<li class="slick-current">
<div class="c-header">About Us</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
<li>
<div class="c-header">Others</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
<li>
<div class="c-header">Main</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
</ul>
</div>
</div>
</div>
A: You need to recalculate just width of a magicline, not its left position - it's always = 0;
$magicLine.stop().animate({
left: 0,
width: leftPos+newWidth
});
demo
A: You can do this by CSS and some JavaScript :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
</head>
<body>
<div class="carousel">
<div class="carousel-info">
<div class="container">
<div style="display:inline-block; position:relative;">
<ul>
<li class="slick-current" onmouseover="$('#line').css('width','34%');">
<div class="c-header">About Us</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
<li onmouseover="$('#line').css('width','68%');">
<div class="c-header">Others</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
<li onmouseover="$('#line').css('width','100%');">
<div class="c-header">Main</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
</ul>
<div id="line" style="position:absolute; bottom:0; left:0; width:34%; height:2px; background:red; transition:all 0.2s;"></div>
</div>
</div>
</div>
</div>
</body>
</html>
I've created an absolute div with transition, when mouse over on one of your elements the width will increase, that's it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38203966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: pyodbc will support connecting to an Azure SQL DB using the AD access token instead of user/password? Currently, I use device code credential to get the access to Azure AD.
device_code_credential = DeviceCodeCredential(
azure_client_id,
tenant_id=azure_tenant_id,
authority=azure_authority_uri)
But I still need to use Azure account username/password to connect to Azure SQL server
driver = 'ODBC Driver 17 for SQL Server'
db_connection_string = f'DRIVER={driver};SERVER={server};' \
f'DATABASE={database};UID={user_name};PWD={password};'\
f'Authentication=ActiveDirectoryPassword;'\
'Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;'
connector = pyodbc.connect(db_connection_string)
Is any way in python under linux/MacOS can allow me to use device_code_credential and access_token to connect to Azure SQL server?
https://github.com/mkleehammer/pyodbc/issues/228
I only got this link and it doesn't seem to work.
Anyone has a fully working sample?
A: You could reference this tutorial: AzureAD/azure-activedirectory-library-for-python: Connect to Azure SQL Database.
It is doable to connect to Azure SQL Database by obtaining a token from Azure Active Directory (AAD), via ADAL Python. We do not currently maintain a full sample for it, but this essay outlines some key ingredients.
*
*You follow the instruction of Connecting using Access Token to
provision your application. There is another similar blog post here.
*Your SQL admin need to add permissions for the app-registration to
the specific database that you are trying to access. See details in
this blog post Token-based authentication support for Azure SQL DB
using Azure AD auth by Mirek H Sztajno.
*It was not particularly highlighted in either of the documents
above, but you need to use https://database.windows.net/ as the
resource string. Note that you need to keep the trailing slash,
otherwise the token issued would not work.
*Feed the configuration above into ADAL Python's Client Credentials
sample.
*Once you get the access token, use it in this way in pyodbc to
connect to SQL Database.
This works with AAD access tokens. Example code to expand the token and prepend the length as described on the page linked above, in Python 2.x:
token = "eyJ0eXAiOi...";
exptoken = "";
for i in token:
exptoken += i;
exptoken += chr(0);
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;
conn = pyodbc.connect(connstr, attrs_before = { 1256:bytearray(tokenstruct) });
3.x is only slightly more involved due to annoying char/bytes split:
token = b"eyJ0eXAiOi...";
exptoken = b"";
for i in token:
exptoken += bytes({i});
exptoken += bytes(1);
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;
conn = pyodbc.connect(connstr, attrs_before = { 1256:tokenstruct });
(SQL_COPT_SS_ACCESS_TOKEN is 1256; it's specific to msodbcsql driver so pyodbc does not have it defined, and likely will not.)
Hope this helps.
A: You can get a token via
from azure.identity import DeviceCodeCredential
# Recommended to allocate a new ClientID in your tenant.
AZURE_CLI_CLIENT_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"
credential = DeviceCodeCredential(client_id=AZURE_CLI_CLIENT_ID)
databaseToken = credential.get_token('https://database.windows.net/.default')
Then use databaseToken.token as an AAD Access Token as described in Leon Yue's answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61069715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: mojoPortal Process after Recover Password The current process after hitting the submit button (in recoverPassword.aspx) is when a valid username is entered it will show a sentence that "email has been sent...", and the textbox will disappear and when an invalid username is entered the textbox will remain on the screen.
My question is where can I do the setting whereby doesn't matter valid or invalid username is entered, it will remain the textbox on the screen?
Thanks in advance.
A: I'll see about changing the page to show the textbox. Why is it that you need the textbox to be there after submitting?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44404202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the meaning of m-n relationship between two weak entities set? I'm doing some exercises in my textbook, and meet this ER diagram:
I tried to convert above diagram into relational database schema, but I think I doesn't make any sense:
• Assignments: assignmentNo, grade
• Enrollments: assignmentNo
• Students: studentID, takeAssignmentNo
• Courses: dept, courseNo, offerAssigmentNo
Can you please explain how should I understand this diagram? What is its practical usage? How can I implement score relationship in SQL Server, or convert it into relational database schema?
A: Try this:
Enrollments: Student ID, Course No
Score: Assignment No, Student ID, Course No.
Note: Some designers frown on composite primary keys. Not me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14374118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using swift 2 to scan an image for the color of its pixels I need to figure out how to scan an image for the color of its pixels for a Mac application. My desired end result is to group certain colors and filter them individually. Any and all tips or suggestions would be much appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35469060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Restarting Tomcat after a successful deployment with Jenkins How can I have Jenkins restart a Tomcat instance after a successful deployment?
I already tried using a batch script, but the Tomcat instance is killed when the build is finished.
A: Your answer lies in Jenkins ProcessTreeKiller. A more detailed explanation here.
It's a design decision to kill any processes that are spawned by the build to maintain a clean environment. Unfortunately that means you can't leave a process (such as Tomcat) running after the build.
You can disable this functionality globally (not recommended) by launching Jenkins like this:
java -Dhudson.util.ProcessTree.disable=true -jar jenkins.war
Or you can disable this on a per-case basis, by launching the process with a changed environment variable:
BUILD_ID=dontKillMe ./catalina restart
Some people report however that changing BUILD_ID is not enough. They recommend also unsetting:
JENKINS_COOKIE
JENKINS_SERVER_COOKIE
Edit:
Another issue that could be at play is that when you connect to remote shell, and start a process in that remote shell session, once you (Jenkins) disconnects, the session is killed and all processes spawned by the session are killed too. To get around that issue, you need to disassociate the process from the shell session.
One way is:
nohup ./catalina restart &
A: This is how I am restarting Tomcat after deployment via jenkins.
I am having two servers DEV and QA where I need to do the deployment and restart tomcat. I have Jenkins installed in DEV server.
*
*First you need to install Post build task Plugin in Jenkins.
*Then create this script tomcat-restart.ksh in the server where you have tomcat installed..
#!/bin/bash
echo "*********************Restarting Tomcat70.******************"
sh /apps/apache/sss-tomcat70.ksh status
echo "Trying to stop Tomcat."
sh /apps/apache/sss-tomcat70.ksh stop
echo "Getting Tomcat Status."
sh /apps/apache/sss-tomcat70.ksh status
echo "Trying to Start Tomcat"
sh /apps/apache/sss-tomcat70.ksh start
sleep 2
echo "Getting Tomcat Status"
sh /apps/apache/sss-tomcat70.ksh status
Restarting Tomcat on DEV server.
Since Jenkins and Tomcat is installed in the same machine I am directly calling the script.
In Jenkins go to Add post-build action and choose Post build task and in the Script textbox add the following : /apps/apache/tomcat-restart.ksh
Restarting Tomcat in QA server.
Since Jenkins is installed in different server, I am calling the script to restart Tomcat via Secure Shell.
In Jenkins go to Add post-build action select Post build task and in the Script textbox add the following : sshpass -p 'myPassword' ssh -tt username@hostname sudo sh /apps/apache/tomcat-restart.ksh
You need to install sshpass if its not already installed.
If everything went fine, then you may see something like this in your Jenkins log.
Running script : /apps/apache/tomcat-restart.ksh
[workspace] $ /bin/sh -xe /tmp/hudson43653169595828207.sh
+ /apps/apache/tomcat-restart.ksh
*********************Restarting Tomcat70.*********************
Tomcat v7.0 is running as process ID 3552
*********************Trying to stop Tomcat.*********************
Stopping Tomcat v7.0 running as process ID 3552...
*********************Getting Tomcat Status.*********************
Tomcat v7.0 is not running
*********************Trying to Start Tomcat*********************
Starting Tomcat v7.0 server...
*********************Getting Tomcat Status*********************
Tomcat v7.0 is running as process ID 17969
Hope this helps.
A: In some version of Jenkins "JENKINS_SERVER_COOKIE" not working so in that case u can use "JENKINS_NODE_COOKIE".
Ex:
JENKINS_NODE_COOKIE=dontKillMe
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26278117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Array Index selection C# I have a array of length 300 of type int. Most of the element is 0 and I want to get the index of the first element that is greater than 0. How can I achieve this.
Thank you
A: Use a for loop to go from index 0 to yourArray.length - 1 and record the index of the first element with a value greater than 0.
int firstIndex = -1;
for (int i = 0; i < yourArray.length; i++) {
if (yourArray[i] > 0) {
firstIndex = i;
break;
}
}
Alternately, use a method which returns i immediately on finding the index, instead of breaking the loop. In this case, return either -1 (or some other value that can't be a valid index, but -1 is fairly common in the .NET libraries) or an exception, depending on your tastes.
A: How about this?
array.ToList().FindIndex(value => value > 0)
Alternatively, create your own FindIndex extension method for generic arrays:
public static int FindIndex<T>(this T[] array, Predicate<T> predicate) {
for (int index = 0; index < array.length; index++) {
if (predicate(array[index]))
return index;
}
return -1;
}
which would remove the need for LINQ and ToList():
array.FindIndex(value => value > 0)
A: You can use Array.FindIndex to get the index of first element of the array which is greater than 0,
var array = new int[5];
array[0] = 0;
array[1] = 0;
array[2] = 1;
array[3] = 1;
array[4] = 0;
int index = Array.FindIndex(array, x=>x > 0);
Or,you can use Array.IndexOf method of Array,
int index = Array.IndexOf(array, array.First(x=>x > 0));
A: If you want to get its value, you can use LINQ:
array.Where(x=>x>0).First
If you want its index, you can use LINQ but it'll be more complicated than a straight loop - go over all elements and see if one of them is not 0.
A: int count=0;
for(int i=0;i<numbers.Length;i++)
{
if(numbers[i]>0)
{
break;
}
count++;
}
get the value of variable count at last, that is goint to be index.
A: int result;
foreach (int i in array)
if (i > 0)
{
result = i;
break;
}
Since you only want the first, you can break as soon as you find it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16183841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sweet Alert http request with Angular doesn't work I'm creating a form with Sweet Alert and I have a post request inside the swal function but when I hit submit nothing happens. Would appreciate some help.
$scope.formModal = function(){
swal({background:'#ACF1F4',html:"<form method='post' id='loginform'>Username:
<input id='username' name='username' >
<br><br>Password:<input type='password' id='password' name='password'><br> <br></form>",
confirmButtonText: 'Submit',showCancelButton: true}
, function(){
$http.post("login.php",{"username":username,"password":password})
.success(function(data){swal(data)})
}
);
}
A: There are multiple issues here:
*
*You cannot break a string in multiple lines the way you did.
*You're missing a ')' in the end of your swal call
*You're missing the title parameter, which is mandatory for swal
*The HTML must receive a boolean indicating that your message contains HTML code
I'm not very sure if you can create a form inside the SweetAlert, at least there are not examples in their page.
swal({background:'#ACF1F4', html:true, title:"<form method='post' id='loginform'>Username: <input id='username' name='username' style='width: 100%' ><br><br>Password:<input type='password' id='password' name='password'><br> <br></form>",
confirmButtonText: 'Submit',showCancelButton: true})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41004695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: No route matches error for spec post request I have a post method in scorecard controller which take event id as params and create a score card for that event. When I am trying to send to post request with event id I am getting no routes matches for action empty_scorecard error.
here is Rspec code
describe "POST empty_scorecard" do
it "should create empty scorecard for two team event" do
event = Event.first
post :empty_scorecard, :event_id => event.id
end
end
here is routes for controller action
match '/scorecards/event/:event_id/empty_scorecard', :to => "scorecards#empty_scorecard", :method => :post
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24990570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gradle density abi apks I am generating android apks using gradle with splits.
Following is an example of what I use:
splits {
density {
enable true
reset()
include "mdpi", "hdpi"
}
abi {
enable true
reset()
include "x86", "arm64-v8"
}
}
Based on the documentation, it should generate 4 apks mdpi-x86, mdpi-arm64-v8, hdpi-x86 and hpdi-arm64-v8.
However, when I run the gradle script is generated 6 apks, the four above and two more: x86.apk and arm64-v8.apk. I am not sure why those are generated and what is the reason for it. Is there a way not to generate those?
A: When you split by density, the Android plugin will always generate an "additional" APK for devices whose screen densities are not supported (at least yet).
As per their documentation:
Because each APK that's based on screen density includes a tag with specific restrictions about which screen types the APK supports, even if you publish several APKs, some new devices will not match your multiple APK filters. As such, Gradle always generates an additional universal APK that contains assets for all screen densities and does not include a tag. You should publish this universal APK along with your per-density APKs to provide a fallback for devices that do not match the APKs with a tag.
In your case, because you're also splitting by ABI, you get two "additional" APKs instead of just one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50053437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ Builder bccarm error when calling std::vector::push_back with TObject descendant I have some simple C++ code which won't be compiled by the Clang based C++11 compiler bccaarm of C++ Builder 10.1 Berlin.
This is the code:
TComponent* Comp = new TComponent(this);
std::vector<TComponent*> Comps;
Comps.push_back(Comp);
And this is the error:
[bccaarm error] stl_iterator.h(963): rvalue reference to type
'value_type' (aka 'System: classes::TComponent * __strong') can not be
bound to lvalue of type '__borland_class * isTObj __strong' (aka
'System::Classes::TComponent * __strong')
The compiler stops at line 963 in the file stl_iterator.h:
The other C++ compilers bcc32 and bcc32c(also Clang based) have no problems with this code.
When Compis not from type TComponent or another descendant from TObject the code compiles without any problem.
I have no idea what is wrong with this code and why there is a problem with R and L values...
Does anybody know what to do here?
A: To get the above code compiled the vector type has to be defined as an unsafe pointer.
TComponent* Comp = new TComponent(this);
std::vector<__unsafe TComponent*> Comps;
Comps.push_back(Comp);
I openened a support case for an other problem I had. The embarcadero support gave me the following information which I applied to this problem and it seems to work:
__unsafe tells the compiler that object lifetimes will be handled and no ARC code is generated for the objects
More about this topic:
http://docwiki.embarcadero.com/RADStudio/Berlin/en/Automatic_Reference_Counting_in_C%2B%2B#weak_and_unsafe_pointers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37134861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Radio buttons too wide Can someone help me with this problem. I have two radio buttons in View:
@Html.RadioButton("technology", "Basic") Basic
@Html.RadioButton("technology2", "Advanced") Advanced
And they are displayed like this:
Why are they displayed wide like that? Any ideas?
A: Load this page into Firefox and use Firebug to inspect it and see what CSS is being applied.
You can adjust the CSS right there in Firebug to figure out how you want it to look.
After you figure out the CSS you want to use, add it to your source file.
A: Debug this element in in Chrome if even firefox and try to add overflow: visible; to your css
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15953824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: SQL WHERE statement priority Please explain me priority of this statements in SQL query. What will be first checked and how, I can't understand it well.
SELECT * FROM table
WHERE (deleted_by <> :user AND deleted_by <> :nula)
OR deleted_by IS NULL
AND IDmessage=:ID
A: AND has higher precedence than OR, so it's equivalent to:
WHERE (deleted_by <> :user AND deleted_by <> :nula)
OR (deleted_by IS NULL AND IDmessage = :ID)
I recommend using explicit parentheses whenever you have a mix of AND and OR, because the results are not always intuitive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22231396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Solr supporting varying facets for different types of products I am using Solr for indexing different types of products. The product types (category) have different facets. For example:
camera: megapixel, type (slr/..), body construction, ..
processors: no. of cores, socket type, speed, type (core i5/7)
food: type, origin, shelf-life, weight
tea: type (black/green/white/..), origin, weight, use milk?
serveware: type, material, color, weight
...
And they have common facets as well:
Brand, Price, Discount, Listing timeframe (like new), Availability, Category
I need to display the relevant facets and breadcrumbs when user clicks on any category, or brand page or a global search across all types of products. This is same as what we see on several ecommerce sites.
The query that I have is:
Since the facet types are more or less unique across different types of products, do I put them in separate schemas? Is that the way to do it? The fundamental worry is that those fields will not have any data for other types of products. And are there any implementation principles here that makes retrieving the respective faces for a given product type easier?
I would like to have a design that is scalable to accommodate lots of items in each product type as we go forward, as well as that is easy to use and performance oriented, if possible. Right now I am having a single instance of Solr.
A: The only risk of underpopulated facets are when they misrepresent the search. I'm sure you've used a search site where the metadata you want to facet on is underpopulated so that when you apply the facet you also eliminate from your result set a number of records that should have been included. The thing to watch is that the facet values are populated consistently where they are appropriate. That means that your "tea" records don't need to have a number of cores listed, and it won't impact anything, but all of your "processor" records should, and (to whatever extent possible) they should be populated consistently. This means that if one processor lists its number of cores as "4", and another says "quadcore", these are two different values and a user applying either facet value will eliminate the other processor from their result. If a third quadcore processor is entirely missing the "number of cores" stat from the no_cores facet field (field name is arbitrary), then your facet could be become counterproductive.
So, we can throw all of these records into the same Solr, and as long as the facets are populated consistently where appropriate, it's not really necessary that they be populated for all records, especially when not applicable.
Applying facets dynamically
Most of what you need to know is in the faceting documentation of Solr. The important thing is to specify the appropriate arguments in your query to tell Solr which facets you want to use. (Until you actually facet on a field, it's not a facet but just a field that's both stored="true" and indexed="true".) For a very dynamic effect, you can specify all of these arguments as part of the query to Solr.
&facet=true
This may seem obvious, but you need to turn on faceting. This argument is convenient because it also allows you to turn off faceting with facet=false even if there are lots of other arguments in your query detailing how to facet. None of it does anything if faceting is off.
&facet.field=no_cores
You can include this field over and over again for as many fields as you're interested in faceting on.
&facet.limit=7
&f.no_cores.facet.limit=4
The first line here limits the number of values for returned by Solr for each facet field to 7. The 7 most frequent values for the facet (within the search results) will be returned, with their record counts. The second line overrides this limit for the no_cores field specifically.
&facet.sort=count
You can either list the facet field's values in order by how many appear in how many records (count), or in index order (index). Index order generally means alphabetically, but depends on how the field is indexed. This field is used together with facet.limit, so if the number of facet values returned is limited by facet.limit they will either be the most numerous values in the result set or the earliest in the index, depending on how this value is set.
&facet.mincount=1
There are very few circumstances that you will want to see facet values that appear zero times in your search results, and this can fix the problem if it pops up.
The end result is a very long query:
http://localhost/solr/collecion1/search?facet=true&facet.field=no_cores&
facet.field=socket_type&facet.field=processor_type&facet.field=speed&
facet.limit=7&f.no_cores.facet.limit=4&facet.mincount=1&defType=dismax&
qf=name,+manufacturer,+no_cores,+description&
fl=id,name,no_cores,description,price,shipment_mode&q="Intel"
This is definitely effective, and allows for the greatest amount of on-the-fly decision-making about how the search should work, but isn't very readable for debugging.
Applying facets less dynamically
So these features allow you to specify which fields you want to facet on, and do it dynamically. But, it can lead to a lot of very long and complex queries, especially if you have a lot of facets you use in each of several different search modes.
One option is to formalize each set of commonly used options in a request handler within your solrconfig.xml. This way, you apply the exact same arguments but instead of listing all of the arguments in each query, you just specify which request handler you want.
<requestHandler name="/processors" class="solr.SearchHandler">
<lst name="defaults">
<str name="defType">dismax</str>
<str name="echoParams">explicit</str>
<str name="fl">id,name,no_cores,description,price,shipment_mode</str>
<str name="qf">name, manufacturer, no_cores, description</str>
<str name="sort">score desc</str>
<str name="rows">30</str>
<str name="wt">xml</str>
<str name="q.alt">*</str>
<str name="facet.mincount">1</str>
<str name="facet.field">no_cores</str>
<str name="facet.field">socket_type</str>
<str name="facet.field">processor_type</str>
<str name="facet.field">speed</str>
<str name="facet.limit">10</str>
<str name="facet.sort">count</str>
</lst>
<lst name="appends">
<str name="fq">category:processor</str>
</lst>
</requestHandler>
If you set up a request hander in solrconfig.xml, all it does is serve as a shorthand for a set of query arguments. You can have as many request handlers as you want for a single solr index, and you can alter them without rebuilding the index (reload the Solr core or restart the server application (JBoss or Tomcat, e.g.), to put changes into effect).
There are a number of things going on with this request handler that I didn't get into, but it's all just a way of representing default Solr request arguments so that your live queries can be simpler. This way, you might make a query like:
http://localhost/solr/collection1/processors?q="Intel"
to return a result set with all of your processor-specific facets populated, and filtered so that only processor records are returned. (This is the category:processor filter, which assumes a field called category where all the processor records have a value processor. This is entirely optional and up to you.) You will probably want to retain the default search request handler that doesn't filter by record category, and which may not choose to apply any of the available (stored="true" and indexed="true") fields as active facets.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28821630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Reset A Map Polyline In my application I am using the new map control for wp8. I have my route being tracked when the user chooses to do so, but when the user opts to turn the route tracking off, I am not sure how to clear the Polyline from the map?
I call my InitializeMapPolyline in the constructor
private void InitializeMapPolyLine()
{
_line = new MapPolyline();
//_line.StrokeColor = (Color)Application.Current.Resources["PhoneAccentColor"];
_line.StrokeColor = Color.FromArgb(255, 106, 0, 255);
_line.StrokeThickness = 5;
Map.MapElements.Add(_line);
}
and as the position of the user changes I add the coordinate to the map
_line.Path.Add(myGeoCoordinate);
But then the user may opt to quit tracking of their route, in which case I need to remove this from the map control. How might I accomplish this correctly?
A: Have you tried simply removing it?
Map.MapElements.Remove(_line);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20831774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: why is String.split("£", 2) not working? I have a text file with 1000 lines in the following format:
19 x 75 Bullnose Architrave/Skirting £1.02
I am writing a method that reads the file line by line in - This works OK.
I then want to split each string using the "£" as a deliminater & write it out to
an ArrayList<String> in the following format:
19 x 75 Bullnose Architrave/Skirting, Metre, 1.02
This is how I have approached it (productList is the ArrayList, declared/instantiated outside the try block):
try{
br = new BufferedReader(new FileReader(aFile));
String inputLine = br.readLine();
String delim = "£";
while (inputLine != null){
String[]halved = inputLine.split(delim, 2);
String lineOut = halved[0] + ", Metre, " + halved[1];//Array out of bounds
productList.add(lineOut);
inputLine = br.readLine();
}
}
The String is not splitting and I keep getting an ArrayIndexOutOfBoundsException. I'm not very familiar with regex. I've also tried using the old StringTokenizer but get the same result.
Is there an issue with £ as a delim or is it something else? I did wonder if it is something to do with the second token not being read as a String?
Any ideas would be helpful.
A: Here are some of the possible causes:
*
*The encoding of the file doesn't match the encoding that you are using to read it, and the "pound" character in the file is getting "mangled" into something else.
*The file and your source code are using different pound-like characters. For instance, Unicode has two code points that look like a "pound sign" - the Pound Sterling character (00A3) and the Lira character (2084) ... then there is the Roman semuncia character (10192).
*You are trying to compile a UTF-8 encoded source file without tell the compiler that it is UTF-8 encoded.
Judging from your comments, this is an encoding mismatch problem; i.e. the "default" encoding being used by Java doesn't match the actual encoding of the file. There are two ways to address this:
*
*Change the encoding of the file to match Java's default encoding. You seem to have tried that and failed. (And it wouldn't be the way I'd do this ...)
*Change the program to open the file with a specific (non default) encoding; e.g. change
new FileReader(aFile)
to
new FileReader(aFile, encoding)
where encoding is the name of the file's actual character encoding. The names of the encodings understood by Java are listed here, but my guess is that it is "ISO-8859-1" (aka Latin-1).
A: This is probably a case of encoding mismatch. To check for this,
*
*Print delim.length and make sure it is 1.
*Print inputLine.length and make sure it is the right value (42).
If one of them is not the expected value then you have to make sure you are using UTF-8 everywhere.
You say delim.length is 1, so this is good. On the other hand if inputLine.length is 34, this is very wrong. For "19 x 75 Bullnose Architrave/Skirting £1.02" you should get 42 if all was as expected. If your file was UTF-8 encoded but read as ISO-8859-1 or similar you would have gotten 43.
Now I am a little at a loss. To debug this you could print individually each character of the string and check what is wrong with them.
for (int i = 0; i < inputLine.length; i++)
System.err.println("debug: " + i + ": " + inputLine.charAt(i) + " (" + inputLine.codePointAt(i) + ")");
A: Many thanks for all your replies.
Specifying the encoding within the read & saving the original text file as UTF -8 has worked.
However, the experience has taught me that delimiting text using "£" or indeed other characters that may have multiple representations in different encodings is a poor strategy.
I have decided to take a different approach:
1) Find the last space in the input string & replace it with "xxx" or similar.
2) Split this using the delimiter "xxx." which should split the strings & rip out the "£".
3) Carry on..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13969769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Too many www-data process on Apache2 server, WordPress website won't work On my website (WordPress), some times it runs so many processes as shown in the screenshot (Putty - top)
Then the site won't work.
Please help to resolve this.
A: I assume that you have a lot of httpd processes because you have a lot of users accessing your site. If not, please edit your question with details about the load on the server.
I recently had the same problem and I was using the same amount of memory as you. First I adjusted the swap space, because the default swap space is too small. The details of how to do this depend on your particular Linux distribution but if you google it you can easily find instructions.
Eventually though, I rented another server with twice as much memory. This is the best long-term solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69337967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Location Listener in Android Intent Service My app has an Intent Service which keeps checking on a web server if there is "start" or "stop" word on an html page every 100000ms.
If it receives "start" it starts a locationmanager.requestUpdateLocation(..), if it receives "stop" it stops it with locationmanager.removeUpdates(..).
But I've got this problem:
When I call locationmanager.requestUpdateLocation(..) I NEVER enter in my listener's onLocationChanged (that's implemented in the same scope of service).
Then, I observe that my Intent service doesn't live forever :( I put a receiver which captures the moment when Android boots up and starts it (and this work) and a ploy in which when my Intent service is closed by user it restarts himself :P
But it never lives forever, after few hours (or maybe only 30 minutes) it dies :(
Why?
Here's the code:
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i("Service", "Started");
LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//IT NEVER ENTER HERE
Log.i("LOC", "LAT: " + location.getLatitude() +" LONG: "+location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
//NEVER ENTER ALSO HERE
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
int localizzazioneAttiva=0;
int delay = 0;
while (true) {
Log.i("SERVICE_CheckSito", "Check Sito STARTED");
String inputLine = "";
StringBuffer stringBuffer = new StringBuffer();
//Check Permission and SKD_INT
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED)
{
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
URL url;
try
{
url = new URL("http://www.sito.com/file.html");
HttpURLConnection httpURLConnection;
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
try {
while ((inputLine = bufferedReader.readLine()) != null) {
stringBuffer.append(inputLine).append("\n");
}
} finally {
bufferedReader.close();
}
}
} catch (IOException e) {
// e.printStackTrace();
}
} else return;
}
if (stringBuffer.toString().equals("start\n") && 0==localizzazioneAttiva )
{
localizzazioneAttiva=1;
delay = 1000;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000, 0, locationListener);
}
if(stringBuffer.toString().equals("stop\n")) {
delay = 2000;
locationManager.removeUpdates(locationListener);
localizzazioneAttiva=0;
}
Log.i("SERVICE_CheckSito", "Message from server: " + stringBuffer.toString());
Log.i("SERVICE_CheckSito", "Check Sito FINISHED");
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
A: I should not answer after 3 beers. My bad, did not see you appending /n.
Consider using a plain Service and the FusedLocationProvider.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43147152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: typeerror when reading state React Trying to use zebra to set a state to a json, which is produced by zebras reading a csv in the class constructor.
import "./Maps.css";
import * as z from "zebras";
import df3 from "./df3.json"
class Maps extends Component {
constructor() {
super();
const data = z.readCSV(df3);
this.state = data
}
render()
{
console.log(this.state)
return (
<div>
</div>
);
}
}
export default Maps
Im getting the following error, when trying to console log the state (i have converted csv to json and imported file into js)
TypeError: fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFileSync is not a function
at Module.<anonymous> (readCSV.js:18)
at Module.f1 (_curry1.js:16)
at new Maps (Maps.js:9)
at constructClassInstance (react-dom.development.js:12905)
at updateClassComponent (react-dom.development.js:17040)
at beginWork (react-dom.development.js:18510)
at beginWork$1 (react-dom.development.js:23028)
at performUnitOfWork (react-dom.development.js:22019)
at workLoopSync (react-dom.development.js:21992)
at performSyncWorkOnRoot (react-dom.development.js:21610)
at react-dom.development.js:11130
at unstable_runWithPriority (scheduler.development.js:656)
at runWithPriority$1 (react-dom.development.js:11076)
at flushSyncCallbackQueueImpl (react-dom.development.js:11125)
at flushSyncCallbackQueue (react-dom.development.js:11113)
at scheduleUpdateOnFiber (react-dom.development.js:21053)
at updateContainer (react-dom.development.js:24191)
at legacyRenderSubtreeIntoContainer (react-dom.development.js:24590)
at Object.render (react-dom.development.js:24656)
at Module../src/index.js (index.js:10)
at __webpack_require__ (bootstrap:785)
at fn (bootstrap:150)
at Object.0 (index.js:12)
at __webpack_require__ (bootstrap:785)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at main.chunk.js:1
A: If you would like to import a json file (as I see in your code), You just need to fetch the file:
fetch('./data.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
and then update your state after you fetch it.
Hope this can fix the error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61898801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: up/down arrow scroll not working up/down arrow scroll not working in jquery scrolify plugin.I want to do the scroll with both page up/down button and in up/down arrow button click.
page up/down arrow working fine as I expect.up/down button click not scroll as page scroll
if(e.keyCode==33 ) { //working
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
} else if(e.keyCode==34) { //working
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
}
if(e.keyCode==38) { //not working
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('up arrow');
}
}
} else if(e.keyCode==40) { //not working
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('down arrow');
}
}
}
/*!
* jQuery Scrollify
* Version 1.0.5
*
* Requires:
* - jQuery 1.7 or higher
*
* https://github.com/lukehaas/Scrollify
*
* Copyright 2016, Luke Haas
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
If section being scrolled to is an interstitialSection and the last section on page
then value to scroll to is current position plus height of interstitialSection
*/
(function (global,factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], function($) {
return factory($, global, global.document);
});
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function( root, jQuery ) {
if ( jQuery === undefined ) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if ( typeof window !== 'undefined' ) {
jQuery = require('jquery');
} else {
jQuery = require('jquery')(root);
}
}
factory(jQuery, global, global.document);
return jQuery;
};
} else {
// Browser globals
factory(jQuery, global, global.document);
}
}(typeof window !== 'undefined' ? window : this, function ($, window, document, undefined) {
"use strict";
var heights = [],
names = [],
elements = [],
overflow = [],
index = 0,
currentIndex = 0,
interstitialIndex = 1,
hasLocation = false,
timeoutId,
timeoutId2,
$window = $(window),
top = $window.scrollTop(),
scrollable = false,
locked = false,
scrolled = false,
manualScroll,
swipeScroll,
util,
disabled = false,
scrollSamples = [],
scrollTime = new Date().getTime(),
firstLoad = true,
initialised = false,
wheelEvent = 'onwheel' in document ? 'wheel' : document.onmousewheel !== undefined ? 'mousewheel' : 'DOMMouseScroll',
settings = {
//section should be an identifier that is the same for each section
section: ".section",
//sectionName: "section-name",
interstitialSection: "",
easing: "easeOutExpo",
scrollSpeed: 500,
offset : 0,
scrollbars: true,
target:"html,body",
standardScrollElements: false,
setHeights: true,
overflowScroll:true,
before:function() {},
after:function() {},
afterResize:function() {},
afterRender:function() {}
};
function animateScroll(index,instant,callbacks) {
if(currentIndex===index) {
callbacks = false;
}
if(disabled===true) {
return true;
}
if(names[index]) {
scrollable = false;
if(callbacks) {
settings.before(index,elements);
}
interstitialIndex = 1;
if(settings.sectionName && !(firstLoad===true && index===0)) {
if(history.pushState) {
try {
history.replaceState(null, null, names[index]);
} catch (e) {
if(window.console) {
console.warn("Scrollify warning: This needs to be hosted on a server to manipulate the hash value.");
}
}
} else {
window.location.hash = names[index];
}
}
if(instant) {
$(settings.target).stop().scrollTop(heights[index]);
if(callbacks) {
settings.after(index,elements);
}
} else {
locked = true;
if( $().velocity ) {
$(settings.target).stop().velocity('scroll', {
duration: settings.scrollSpeed,
easing: settings.easing,
offset: heights[index],
mobileHA: false
});
} else {
$(settings.target).stop().animate({
scrollTop: heights[index]
}, settings.scrollSpeed,settings.easing);
}
if(window.location.hash.length && settings.sectionName && window.console) {
try {
if($(window.location.hash).length) {
console.warn("Scrollify warning: There are IDs on the page that match the hash value - this will cause the page to anchor.");
}
} catch (e) {
console.warn("Scrollify warning:", window.location.hash, "is not a valid jQuery expression.");
}
}
$(settings.target).promise().done(function(){
currentIndex = index;
locked = false;
firstLoad = false;
if(callbacks) {
settings.after(index,elements);
}
});
}
}
}
function isAccelerating(samples) {
function average(num) {
var sum = 0;
var lastElements = samples.slice(Math.max(samples.length - num, 1));
for(var i = 0; i < lastElements.length; i++){
sum += lastElements[i];
}
return Math.ceil(sum/num);
}
var avEnd = average(10);
var avMiddle = average(70);
if(avEnd >= avMiddle) {
return true;
} else {
return false;
}
}
$.scrollify = function(options) {
initialised = true;
$.easing['easeOutExpo'] = function(x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
};
manualScroll = {
/*handleMousedown:function() {
if(disabled===true) {
return true;
}
scrollable = false;
scrolled = false;
},*/
handleMouseup:function() {
if(disabled===true) {
return true;
}
scrollable = true;
if(scrolled) {
//instant,callbacks
manualScroll.calculateNearest(false,true);
}
},
handleScroll:function() {
if(disabled===true) {
return true;
}
if(timeoutId){
clearTimeout(timeoutId);
}
timeoutId = setTimeout(function(){
scrolled = f;
if(scrollable===false) {
return false;
}
scrollable = false;
//instant,callbacks
manualScroll.calculateNearest(false,false);
}, 200);
},
calculateNearest:function(instant,callbacks) {
top = $window.scrollTop();
var i =1,
max = heights.length,
closest = 0,
prev = Math.abs(heights[0] - top),
diff;
for(;i<max;i++) {
diff = Math.abs(heights[i] - top);
if(diff < prev) {
prev = diff;
closest = i;
}
}
if(atBottom() || atTop()) {
index = closest;
//index, instant, callbacks
animateScroll(closest,instant,callbacks);
}
},
/*wheel scroll*/
wheelHandler:function(e) {
if(disabled===true) {
return true;
} else if(settings.standardScrollElements) {
if($(e.target).is(settings.standardScrollElements) || $(e.target).closest(settings.standardScrollElements).length) {
return true;
}
}
if(!overflow[index]) {
e.preventDefault();
}
var currentScrollTime = new Date().getTime();
e = e || window.event;
var value = e.originalEvent.wheelDelta || -e.originalEvent.deltaY || -e.originalEvent.detail;
var delta = Math.max(-1, Math.min(1, value));
//delta = delta || -e.originalEvent.detail / 3 || e.originalEvent.wheelDelta / 120;
if(scrollSamples.length > 149){
scrollSamples.shift();
}
//scrollSamples.push(Math.abs(delta*10));
scrollSamples.push(Math.abs(value));
if((currentScrollTime-scrollTime) > 200){
scrollSamples = [];
}
scrollTime = currentScrollTime;
if(locked) {
return false;
}
if(delta<0) {
if(index<heights.length-1) {
if(atBottom()) {
if(isAccelerating(scrollSamples)) {
e.preventDefault();
index++;
locked = true;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
return false;
}
}
}
} else if(delta>0) {
if(index>0) {
if(atTop()) {
if(isAccelerating(scrollSamples)) {
e.preventDefault();
index--;
locked = true;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
return false
}
}
}
}
},
/*end of wheel*/
keyHandler:function(e) {
if(disabled===true) {
return true;
}
if(locked===true) {
return false;
}
if(e.keyCode==33 ) {
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
} else if(e.keyCode==34) {
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
}
if(e.keyCode==38) {
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('up arrow');
}
}
} else if(e.keyCode==40) {
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('down arrow');
}
}
}
/*home, end button testing*/
if(e.keyCode==35) {
for(index=6;index<1;index--)
{
console.log("worked on end button");
}
}
else if(e.keyCode==36) {
for(index=0;intex<1;index++)
{
console.log("worked on home button");
}
}
/*home,end button end*/
},
init:function() {
if(settings.scrollbars) {
$window.on('mousedown', manualScroll.handleMousedown);
$window.on('mouseup', manualScroll.handleMouseup);
$window.on('scroll', manualScroll.handleScroll);
} else {
$("body").css({"overflow":"hidden"});
}
$window.on(wheelEvent,manualScroll.wheelHandler);
$(document).bind(wheelEvent,manualScroll.wheelHandler);
$window.on('keydown', manualScroll.keyHandler);
}
};
swipeScroll = {
touches : {
"touchstart": {"y":-1,"x":-1},
"touchmove" : {"y":-1,"x":-1},
"touchend" : false,
"direction" : "undetermined"
},
options:{
"distance" : 30,
"timeGap" : 800,
"timeStamp" : new Date().getTime()
},
touchHandler: function(event) {
if(disabled===true) {
return true;
} else if(settings.standardScrollElements) {
if($(event.target).is(settings.standardScrollElements) || $(event.target).closest(settings.standardScrollElements).length) {
return true;
}
}
var touch;
if (typeof event !== 'undefined'){
if (typeof event.touches !== 'undefined') {
touch = event.touches[0];
switch (event.type) {
case 'touchstart':
swipeScroll.touches.touchstart.y = touch.pageY;
swipeScroll.touches.touchmove.y = -1;
swipeScroll.touches.touchstart.x = touch.pageX;
swipeScroll.touches.touchmove.x = -1;
swipeScroll.options.timeStamp = new Date().getTime();
swipeScroll.touches.touchend = false;
case 'touchmove':
swipeScroll.touches.touchmove.y = touch.pageY;
swipeScroll.touches.touchmove.x = touch.pageX;
if(swipeScroll.touches.touchstart.y!==swipeScroll.touches.touchmove.y && (Math.abs(swipeScroll.touches.touchstart.y-swipeScroll.touches.touchmove.y)>Math.abs(swipeScroll.touches.touchstart.x-swipeScroll.touches.touchmove.x))) {
//if(!overflow[index]) {
event.preventDefault();
//}
swipeScroll.touches.direction = "y";
if((swipeScroll.options.timeStamp+swipeScroll.options.timeGap)<(new Date().getTime()) && swipeScroll.touches.touchend == false) {
swipeScroll.touches.touchend = true;
if (swipeScroll.touches.touchstart.y > -1) {
if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
swipeScroll.up();
} else {
swipeScroll.down();
}
}
}
}
}
break;
case 'touchend':
if(swipeScroll.touches[event.type]===false) {
swipeScroll.touches[event.type] = true;
if (swipeScroll.touches.touchstart.y > -1 && swipeScroll.touches.touchmove.y > -1 && swipeScroll.touches.direction==="y") {
if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
swipeScroll.up();
} else {
swipeScroll.down();
}
}
swipeScroll.touches.touchstart.y = -1;
swipeScroll.touches.touchstart.x = -1;
swipeScroll.touches.direction = "undetermined";
}
}
default:
break;
}
}
}
},
down: function() {
if(index<=heights.length-1) {
if(atBottom() && index<heights.length-1) {
index++;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
if(Math.floor(elements[index].height()/$window.height())>interstitialIndex) {
interstitialScroll(parseInt(heights[index])+($window.height()*interstitialIndex));
interstitialIndex += 1;
} else {
interstitialScroll(parseInt(heights[index])+(elements[index].height()-$window.height()));
}
}
}
},
up: function() {
if(index>=0) {
if(atTop() && index>0) {
index--;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
if(interstitialIndex>2) {
interstitialIndex -= 1;
interstitialScroll(parseInt(heights[index])+($window.height()*interstitialIndex));
} else {
interstitialIndex = 1;
interstitialScroll(parseInt(heights[index]));
}
}
}
},
init: function() {
if (document.addEventListener) {
document.addEventListener('touchstart', swipeScroll.touchHandler, false);
document.addEventListener('touchmove', swipeScroll.touchHandler, false);
document.addEventListener('touchend', swipeScroll.touchHandler, false);
}
}
};
util = {
refresh:function(withCallback) {
clearTimeout(timeoutId2);
timeoutId2 = setTimeout(function() {
sizePanels();
calculatePositions(true);
if(withCallback) {
settings.afterResize();
}
},400);
},
handleUpdate:function() {
util.refresh(false);
},
handleResize:function() {
util.refresh(true);
}
};
settings = $.extend(settings, options);
sizePanels();
calculatePositions(false);
if(true===hasLocation) {
//index, instant, callbacks
animateScroll(index,false,true);
} else {
setTimeout(function() {
//instant,callbacks
manualScroll.calculateNearest(true,false);
},200);
}
if(heights.length) {
manualScroll.init();
swipeScroll.init();
$window.on("resize",util.handleResize);
if (document.addEventListener) {
window.addEventListener("orientationchange", util.handleResize, false);
}
}
function interstitialScroll(pos) {
if( $().velocity ) {
$(settings.target).stop().velocity('scroll', {
duration: settings.scrollSpeed,
easing: settings.easing,
offset: pos,
mobileHA: false
});
} else {
$(settings.target).stop().animate({
scrollTop: pos
}, settings.scrollSpeed,settings.easing);
}
}
function sizePanels() {
var selector = settings.section;
overflow = [];
if(settings.interstitialSection.length) {
selector += "," + settings.interstitialSection;
}
$(selector).each(function(i) {
var $this = $(this);
if(settings.setHeights) {
if($this.is(settings.interstitialSection)) {
overflow[i] = false;
} else {
if(($this.css("height","auto").outerHeight()<$window.height()) || $this.css("overflow")==="hidden") {
$this.css({"height":$window.height()});
overflow[i] = false;
} else {
$this.css({"height":$this.height()});
if(settings.overflowScroll) {
overflow[i] = true;
} else {
overflow[i] = false;
}
}
}
} else {
if(($this.outerHeight()<$window.height()) || (settings.overflowScroll===false)) {
overflow[i] = false;
} else {
overflow[i] = true;
}
}
});
}
function calculatePositions(resize) {
var selector = settings.section;
if(settings.interstitialSection.length) {
selector += "," + settings.interstitialSection;
}
heights = [];
names = [];
elements = [];
$(selector).each(function(i){
var $this = $(this);
if(i>0) {
heights[i] = parseInt($this.offset().top) + settings.offset;
} else {
heights[i] = parseInt($this.offset().top);
}
if(settings.sectionName && $this.data(settings.sectionName)) {
names[i] = "#" + $this.data(settings.sectionName).replace(/ /g,"-");
} else {
if($this.is(settings.interstitialSection)===false) {
names[i] = "#" + (i + 1);
} else {
names[i] = "#";
if(i===$(selector).length-1 && i>1) {
heights[i] = heights[i-1]+parseInt($this.height());
}
}
}
elements[i] = $this;
try {
if($(names[i]).length && window.console) {
console.warn("Scrollify warning: Section names can't match IDs on the page - this will cause the browser to anchor.");
}
} catch (e) {}
if(window.location.hash===names[i]) {
index = i;
hasLocation = true;
}
});
if(true===resize) {
//index, instant, callbacks
animateScroll(index,false,false);
} else {
settings.afterRender();
}
}
function atTop() {
if(!overflow[index]) {
return true;
}
top = $window.scrollTop();
if(top>parseInt(heights[index])) {
return false;
} else {
return true;
}
}
function atBottom() {
if(!overflow[index]) {
return true;
}
top = $window.scrollTop();
if(top<parseInt(heights[index])+(elements[index].outerHeight()-$window.height())-28) {
return false;
} else {
return true;
}
}
}
function move(panel,instant) {
var z = names.length;
for(;z>=0;z--) {
if(typeof panel === 'string') {
if (names[z]===panel) {
index = z;
//index, instant, callbacks
animateScroll(z,instant,true);
}
} else {
if(z===panel) {
index = z;
//index, instant, callbacks
animateScroll(z,instant,true);
}
}
}
}
$.scrollify.move = function(panel) {
if(panel===undefined) {
return false;
}
if(panel.originalEvent) {
panel = $(this).attr("href");
}
move(panel,false);
};
$.scrollify.instantMove = function(panel) {
if(panel===undefined) {
return false;
}
move(panel,true);
};
$.scrollify.next = function() {
if(index<names.length) {
index += 1;
animateScroll(index,false,true);
}
};
$.scrollify.previous = function() {
if(index>0) {
index -= 1;
//index, instant, callbacks
animateScroll(index,false,true);
}
};
$.scrollify.instantNext = function() {
if(index<names.length) {
index += 1;
//index, instant, callbacks
animateScroll(index,true,true);
}
};
$.scrollify.instantPrevious = function() {
if(index>0) {
index -= 1;
//index, instant, callbacks
animateScroll(index,true,true);
}
};
$.scrollify.destroy = function() {
if(!initialised) {
return false;
}
if(settings.setHeights) {
$(settings.section).each(function() {
$(this).css("height","auto");
});
}
$window.off("resize",util.handleResize);
if(settings.scrollbars) {
$window.off('mousedown', manualScroll.handleMousedown);
$window.off('mouseup', manualScroll.handleMouseup);
$window.off('scroll', manualScroll.handleScroll);
}
$window.off(wheelEvent,manualScroll.wheelHandler);
$window.off('keydown', manualScroll.keyHandler);
if (document.addEventListener) {
document.removeEventListener('touchstart', swipeScroll.touchHandler, false);
document.removeEventListener('touchmove', swipeScroll.touchHandler, false);
document.removeEventListener('touchend', swipeScroll.touchHandler, false);
}
heights = [];
names = [];
elements = [];
overflow = [];
};
$.scrollify.update = function() {
if(!initialised) {
return false;
}
util.handleUpdate();
};
$.scrollify.current = function() {
return elements[index];
};
$.scrollify.disable = function() {
disabled = true;
};
$.scrollify.enable = function() {
disabled = false;
if (initialised) {
//instant,callbacks
manualScroll.calculateNearest(false,false);
}
};
$.scrollify.isDisabled = function() {
return disabled;
};
$.scrollify.setOptions = function(updatedOptions) {
if(!initialised) {
return false;
}
if(typeof updatedOptions === "object") {
settings = $.extend(settings, updatedOptions);
util.handleUpdate();
} else if(window.console) {
console.warn("Scrollify warning: Options need to be in an object.");
}
};
}));
A: I think you are listening wrong event. Use keydown event this will work.
working fiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42298548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Animating element with jQuery I have successfully animated a div from bottom to top on window load as fallow:
<script>
$(function(){
$('#wrapper').animate({'margin-top': '20px'}, 1000);
});
</script>
#wrapper {
float: none;
margin: 600px auto;
max-width: 850px;
min-width: 200px;
padding: 0 2%;
}
However, I now need to animate the div from right to left instead.
I tried initial css as:
margin-top: 20px;
margin-right: auto;
margin-left: 100%;
and then:
<script>
$(function(){
$('#wrapper').animate({'margin-left': 'auto'}, 1000);
});
</script>
auto doesn't seem to be a valid value, but I need to have the div stop in the center so I tried
getting width of browser window and then dividing it by two and substracting half of the size
of the wrapper but I couldn't get the width of wrapper as I'm using max-width intead of hardcoding the width.
I need to keep the site responsive.
How could I accomplish left to right animation having the div stop once it is centered?
A: Try it with
$("#wrapper").animate({"marginLeft":"50%"}, 1000);
A: $('#wrapper').animate({right: (parseInt($(this).css('right'))-200)+"px"}, 1000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19854634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What does closing a descriptor mean? I thought a descriptor was simply a numerical index in the global file table, so I'm confused by what "close a descriptor" actually means. Can someone clarify the relationship between processes, descriptors, and open files and explain what it means to open, duplicate, and close descriptors?
A: A descriptor is a kind of a key. When you want to access some room you need to get the key for it. open grants you an access to the room (the file) by giving you a key for it.
To access (read/write) the room (the file) you need the key.
Then to be fair (the number of key in the system is bounded), when you no more need access to the room you should release the key (close the descriptor). Thus, the key is now globally available to other clients...
This is the same for all ressources that a process (a client) want to access. Get a key, use the key, release the key for the ressource. You can have many different sets of keys : keys for files, keys for memory, etc.
The system is the owner of the keys and manage them, process ask system for keys and just use them.
For duplication is just a way to provide key sharing. Two process can use the same key to access the room. If you want to understand what sharing such a key exactly means, you need to understand what an open file exactly is.
In fact, what the system gaves you is not just a simple key as in real life. A descriptor is an entry in a system table that describes the state of a file being manipulated. When you open a file, some data where allocated.
*
*first in the process own space, there is some data initialized to prepare the process to be able to manipulated a file. These data where placed in the process' descriptors table. Your descriptor is exactly an index in that table. That entry refers to a system open-file table.
*second the system tracks all opened files in its opened-file table. In such a table entry you have many data that helps the system to realize operations you need on the file (which file it is, buffer caching structures, current position to the file, current opening mode, etc).
Now in many cases, there is only one process entry associated to a system entry. But this is not always the case! Think about two different processes writing on the same terminal, then in each process you have an descriptor that represents its access to the terminal (in Unix a terminal is just a file), but both of these entries points to the same system table entry which contains data that says which terminal it is, etc.
duplicating a descriptor realize exactly the situation : you have in the same process 2 entries that points the the same system entry. Another way to duplicate descriptors is to fork a process, that clones a process, and that cloning clones process descriptors table... This is the way two process can share the same terminal for example. A first process (maybe a shell) opens the terminal, and then forks to execute a sub-command such that sub-command can access the same terminal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20084247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Import list of strings to tuples Say if I have a text file containing a list of strings eg:
111 234324 john smith
123 123113 edward jones
131 423432 ben david
How could I import the strings from a text file and create a tuple for each line?
So they would read
(131, 234324, "john", "smith")
(123, 123113, "edward", "jones")
(131, 423432, "ben", "david")
and then print each tuple out line by line?
Thanks.
A: This should do it:
result = None
with open('input.txt') as f:
result = [tuple(line.split()) for line in f]
for t in result:
print(t)
A: Try this :
# open your_file
for line in your_file:
t = tuple(line.split())
print t
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20456519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to solve python/pip/pip3 is not recognized as an internal or external command | python command error after changing path? I. Have installed python 3.7.8 on windows 10. But when I run the commands python/pip/pip3 from command prompt it gives an error
python/pip/pip3 is not recognized as an internal or external command | python command error
Thought I have changed the path on user variables as python's location. I have no permissions to change the system path
What can I do now.
A: Make sure you add python to the Windows path environment variable.
Check this resource to find out how to do that.
A: Control Panel -> add/remove programs -> Python -> change-> optional Features (you can click everything) then press next -> Check "Add python to environment variables" -> Install
enter image description here
I followed the link specially the image ....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65173568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error while creating layout template in codigniter I have two layout templates in my project and always loading first template. How to load second template also.
In main Usercontroller how to differentiate them. They are,
Learncontroller.php
class Learncontroller extends Usercontroller{
public function __construct(){
parent::__construct();
$this->load->model("Usermodel","",true);
}
public function index(){
$id=$this->session->userdata('cp_userid');
$menuActive= "learning";
$data['menuActive'] = $menuActive;
$userdetails=$this->Usermodel->getuserdetails($id);
$data['userdetails']=$userdetails;
$result=$this->Usermodel->currentlearningcourses($id);
$data['details']=$result;
$data['content']=$this->load->view("user/currentlearningcourses",$data,true);
$data['title']='My Courses';
//$this->load->view("user/layout",$data);
$headerContent = $this->load->view("user/layout",$data,true);
$this->render($headerContent);
}
}
Unitcontroller.php
class Unitcontroller extends Usercontroller{
public function __construct(){
parent::__construct();
$this->load->model("Usermodel","",true);
}
public function courselearn($id){
$r=$this->Usermodel->getsectiontopic($id);
$data['topicId']=$id;
$data['topicQ']=$r;
$data['video']=$this->input->post("id");
$data['id']=$id;
$data['content']=$this->load->view("user/unit_content",$data, true);
$courselearnheaderContent = $this->load->view("user/courselearn_layout",$data,true);
$this->render($courselearnheaderContent);
}
}
Learncontroller and Unitcontroller has separate layouts but always loading protected $layout = 'user/layout';. How to load this 'user/courselearn_layout'; when control comes from Unitcontroller.
Usercontroller.php
protected $layout = 'user/layout';
protected $courselearn_layout = 'user/courselearn_layout';
protected function render($headerContent) {
$view_data = array( 'headerContent' => $headerContent);
$this->load->view($this->layout);
}
Always loading first page. How to make load the second page also please help me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43840983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Background position does not animate in full screen Here is my CSS:
div.movement {
background-image: url('image.png');
background-repeat: repeat;
background-size: contain;
animation: 60s linear 0s infinite alternate moving-background;
}
@keyframes moving-background {
to {
background-position: 2000% 0%;
}
}
The background moves constantly when I load the webpage in regular mode. However, it stops moving as soon as I go fullscreen by pressing F11. I have tried both Chrome and Firefox and both behave in the same way.
Is there any way to animate a background image's position in full-screen mode? I would prefer a CSS-based solution but I am open to using JavaScript as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67980837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: vb6 "regfreecom" autocreate manifest for ocx file I think I need to create a manifest file for MSCOMCTL.ocx to use in my VB6 application (reg free)
I will also need to update/create the .res file Then I will need to use ManifestCreatorII It has been a few years (2017) and I have forgotten the steps and cannot find my old notes.
I ~remember how to work with the NSI to generate the install package. Without this, I cannot get my applications to run on a new Win 10 PC.
My Development PC is a virtual PC running Windows XP (32bit) Service Pack 3. I am programming with Visual Basic 6.0 (SP6).
Working through these experiments taught me that I do NOT really need manifest files for each of the Dependency .ocx files used for the Components in my VB6 programs.
I really only need the one manifest file for the application program as a whole and that is used to create the Resource file for the project.
My problem was first indicated when I installed the NSIS package and ran its VB6 program on a new Win10(64) PC:
Run-time error 339: Component 'MSCOMCTL.OCX' or one of its dependencies not correctly registered: a file is missing or invalid
I got this Error message when I tried to open one of the more recently added forms.
A unique feature of this form is the use of Tabbed Dialogue Controls (TabStrip) which references MSCOMCTL.ocx.
re: https://www.processlibrary.com/en/directory/files/mscomctl/19764/
mscomctl.ocx is an ActiveX Control module that contains common controls used by Windows, such as ImageCombo, ImageList, ListView, ProgressBar, Slider, StatusBar, TabStrip, ToolBar, and TreeView controls.
I created a tiny program, zMSCOMCTL, which has one form containing only two controls (TabStrip and ProgressBar) both from the one MSCOMCTL.ocx Component.
I plagiarized from VB6 code and NSIS of my similar tiny programs (e.g.: zRichTx, zThreeD, zCOMDLG).
When I install and try to run zMSCOMCTL on my new Win10(64) PC, I get this same error message: Run-time error 339: Component 'MSCOMCTL.OCX' or one of its dependencies not correctly registered: a file is missing or invalid
I downloaded a copy MSCOMCTL.ocx version 6.1.98.46 from https://www.ocxme.com
These instructions are based on: https://originaldll.com/file/mscomctl.ocx/16903.html
*
*Made a backup copy of: C:\WINDOWS\system32\MSCOMCTL.*
*In the Command Prompt Window: regsvr32 /u MSCOMCTL.ocx
*Deleted C:\WINDOWS\system32\MSCOMCTL.*
*Copied the new MSCOMCTL.ocx into C:\WINDOWS\system32
*REBOOT
*In the Command Prompt Window: regsvr32 MSCOMCTL.ocx
FIRST trial method:
A. create MSCOMCTL.ocx.manifest:
*
*In the Command Prompt Window:regsvr42 MSCOMCTL.ocx
*I used NotePad++ to Modify
*
*.sxs. changed to .ocx.
*type="win32" changed to processorArchitecture="x86" type="win32"
*<file name="MSCOMCTL.ocx"> changed to <file name="Dependencies\MSCOMCTL.ocx">
To improve chances of ManifestCreatorv2.0.3 accepting MSCOMCTL.ocx.manifest file instead of requiring ClipBoard copy. (No srtrange characters or blanks)
*
*First, Edit MSCOMCTL.ocx.manifest with Notepad++
*Select All, Copy, Paste into NotePad and Save to MSCOMCTL.ocx.manifest
B. Create zMSCOMCTL.exe.manifest
*
*Open ManifestCreatorv2.0.3:
*The Manifest > Create from Project File (vbp) zMSCOMCTL.vbp
*The Manifest > Append/Merge Manifest - From file MSCOMCTL.ocx.manifest
*The Manifest > Export Manifest - Destination Disk File
*save to zMSCOMCTL.exe.manifest (Replace)
re: http://www.vbforums.com/showthread.php?845909-VB6-Manifest-Creator-II
C. Create zMSCOMCTL.res
*
*Shut Down VB6 zMSCOMCTL Project or remove zMSCOMCTL.res from Project
*Open ManifestCreatorv2.0.3:
*The Manifest > Create from Project File (vbp) zMSCOMCTL.vbp
*The Manifest > Append/Merge Manifest - From file MSCOMCTL.ocx.manifest
*The Manifest > Export Manifest
*
*[_] Indent Manifest
*[_] Do Not Use Prefixed Name Spaces
*[x] Do Not Export Empty/Blank Attributes
*Destination Resource File - save to zMSCOMCTL.res (Replace)
D. Make new zMSCOMCTL.exe
*
*Open VB6 zMSCOMCTL Project or Add zMSCOMCTL.res back into Project
*Within VB6 zMSCOMCTL Project, start with full compile: Runs OK
*Within VB6 zMSCOMCTL Project, File -> Make new executable:
Running the new executable: zMSCOMCTL.exe Results in:
This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
This is the end of the FIRST trial method (which failed)
Re: VB6 RegFreeCom SideBySide SxS Manifest Test for TABCTL32.ocx
Successful Process:
I downloaded UMMM from https://github.com/wqweto/UMMM
[Find_file] [_Clone_or_download_v] Click on the Green Button
Clone with HTTPS
Use Git or checkout with SVN using the web URL.
[https://github.com/wqweto/UMMM.git]
[Open_in_Desktop] [Download_ZIP] Then Click on Download_ZIP Button
*
*I expanded the downloaded UMMM-master.zip file.
*The resulting .\src folder contained files: mdUmmm.bas and Ummm.vbp.
*I copied them to their own UMMM-master Project folder
*I took a quick look at mdUmmm.bas and Ummm.vbp.
*The Ummm.vbp referred to SysWOW64.
*In Notepad, I changed it to System32. Development platform is WinXP(32)
*I opened Ummm.vbp with VB6
*I did a File - Make to create UMMM.exe
*I copied UMMM.exe to C:\Program Files\Support Tools\ in %path%
These are the reference links I have found for UMMM Unattended Make My Manifest :
*
*https://github.com/wqweto/UMMM
*Generate manifest files for registration-free COM
*Registration free COM: VB6 Executable referencing VB6 DLL
*https://github.com/wqweto/UMMM/blob/master/Sample.ini
*http://www.vbforums.com/showthread.php?840333-SXS-and-UMMM-with-inter-thread-marshalling
*https://github.com/wqweto/UMMM/issues/9
*https://github.com/wqweto/UMMM/issues/16
The 1st link is where I got my clues to create the .ini file.
The 6th link helped me create a bat file that seems to work!
zMSCOMCTLUMMM.ini
This .ini file, following the Identity line, contains a list of dependency files. They are listed in the .vbp file (e.g.: Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.2#0; mscomctl.ocx ).
You can also find them itemized within VB6 Menu > Project > Components ...
On that Components form, you can choose [x] Selected Items Only to more easily view the list.
Highlighting each Component in the list will display, below: (e.g.: Location C:\ ... \MSCOMCTL.OCX )
In the .ini file, I specify the path to the dependency file because it is not stored in the local Project folder.
Identity zMSCOMCTL.exe zMSCOMCTL.exe "MSCOMCTL Test program 1.0"
File C:\WINDOWS\system32\mscomctl.ocx
zMSCOMCTLUMMM.bat
UMMM.exe zMSCOMCTLUMMM.ini .\manifest\zMSCOMCTL.exe.manifest
pause done?
Is there a way to specify File Name= in UMMM (Unattended Make My Manifest) creation of Program.exe.manifest?
I edited the resulting zMSCOMCTL.exe.manifest with Notepad and changed:
From: <file name="..\..\..\..\WINDOWS\system32\MSCOMCTL.ocx">
To: <file name="Dependencies\MSCOMCTL.ocx">
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<assemblyIdentity name="zMSCOMCTL" processorArchitecture="X86" type="win32" version="1.1.0.24" />
<description>MSCOMCTL Test program 1.0</description>
<file name="Dependencies\MSCOMCTL.ocx">
<typelib tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" version="2.2" flags="control,hasdiskimage" helpdir="" />
<comClass clsid="{1EFB6596-857C-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.TabStrip.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
<progid>MSComctlLib.TabStrip</progid>
</comClass>
<comClass clsid="{24B224E0-9545-4A2F-ABD5-86AA8A849385}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{9A948063-66C3-4F63-AB46-582EDAA35047}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{66833FE6-8583-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.Toolbar.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,simpleframe,setclientsitefirst">
<progid>MSComctlLib.Toolbar</progid>
</comClass>
<comClass clsid="{7DC6F291-BF55-4E50-B619-EF672D9DCC58}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,simpleframe,setclientsitefirst" />
<comClass clsid="{8B2ADD10-33B7-4506-9569-0A1E1DBBEBAE}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,simpleframe,setclientsitefirst" />
<comClass clsid="{8E3867A3-8586-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.SBarCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst">
<progid>MSComctlLib.SBarCtrl</progid>
</comClass>
<comClass clsid="{627C8B79-918A-4C5C-9E19-20F66BF30B86}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst" />
<comClass clsid="{585AA280-ED8B-46B2-93AE-132ECFA1DAFC}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst" />
<comClass clsid="{35053A22-8589-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.ProgCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst">
<progid>MSComctlLib.ProgCtrl</progid>
</comClass>
<comClass clsid="{A0E7BF67-8D30-4620-8825-7111714C7CAB}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,actslikelabel,alignable,setclientsitefirst" />
<comClass clsid="{C74190B6-8589-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.TreeCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
<progid>MSComctlLib.TreeCtrl</progid>
</comClass>
<comClass clsid="{9181DC5F-E07D-418A-ACA6-8EEA1ECB8E9E}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{95F0B3BE-E8AC-4995-9DCA-419849E06410}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{DD2DBE12-F9F8-4E32-B087-DAD1DCEF0783}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{BDD1F04B-858B-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.ListViewCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
<progid>MSComctlLib.ListViewCtrl</progid>
</comClass>
<comClass clsid="{996BF5E0-8044-4650-ADEB-0B013914E99C}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{979127D3-7D01-4FDE-AF65-A698091468AF}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{CCDB0DF2-FD1A-4856-80BC-32929D8359B7}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{2C247F23-8591-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.ImageListCtrl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,invisibleatruntime,alignable,setclientsitefirst">
<progid>MSComctlLib.ImageListCtrl</progid>
</comClass>
<comClass clsid="{F91CAF91-225B-43A7-BB9E-472F991FC402}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,invisibleatruntime,alignable,setclientsitefirst" />
<comClass clsid="{556C2772-F1AD-4DE1-8456-BD6E8F66113B}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,invisibleatruntime,alignable,setclientsitefirst" />
<comClass clsid="{F08DF954-8592-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.Slider.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
<progid>MSComctlLib.Slider</progid>
</comClass>
<comClass clsid="{0B314611-2C19-4AB4-8513-A6EEA569D3C4}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
<comClass clsid="{DD9DA666-8594-11D1-B16A-00C0F0283628}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" progid="MSComctlLib.ImageComboCtl.2" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst">
<progid>MSComctlLib.ImageComboCtl</progid>
</comClass>
<comClass clsid="{87DACC48-F1C5-4AF3-84BA-A2A72C2AB959}" tlbid="{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,setclientsitefirst" />
</file>
</assembly>
Next use ManifestCreatorv2.0.3 to create zMSCOMCTL.res file
*
*The Manifest > Create from Project File (vbp) zMSCOMCTL.vbp
*The Manifest > Append/Merge Manifest - From file [e.g.:
.\manifest\MSCOMCTL.exe.manifest]
*The Manifest > Export Manifest >
*[_] Indent Manifest
*
*[_] Do Not Use Prefixed Name Spaces
*[x] Do Not Export Empty/Blank Attributes
*Destination Resource File - save to zMSCOMCTL.res (Replace)
*Open VB6 zMSCOMCTL Project or Add zMSCOMCTL.res back into Project
Compile, Build and Test the program.
*
*Within VB6 zMSCOMCTL Project, start witn full compile: Runs OK
*Within VB6 zMSCOMCTL Project, File -> Make new executable:
*Save Project
Running zMSCOMCTL.exe from with in its Project folder:
`[Run-Error 7 out of memory?]`
Build and use the NSIS file to create the SxS installation file for testing on any target PCs.
The NSIS file builds an executable program to:
- Determine if the target operating system is [AtLeastWinVista] and if it is [RunningX64].
- Request a selection from the available Harddrives / Partitions for installation.
- Based on this criteria, it creates an InstallDirectory and an InstallDirectory\Dependencies subdirectory.
- Copies the Program.exe into the InstallDirectory.
- Copies the Dependency files into the InstallDirectory\Dependencies subdirectory.
- Also based on this criteria it creates a Public read/write data directory.
- Creates desktop shortcut
- Creates start-menu items
- Creates an Uninstall mechanism
I adjusted the NSIS file to install only the dependency files listed in the .vbp file, the UMMM.ini file and in the resulting .exe.manifest file.
Installed on WinXP(32) works OK
Installed on Win7(64) works OK
Installed on Win10(64) works OK
A: Here is the entry from the manifest file from one of the VB6 apps I maintain:
<assemblyIdentity name="name of application" processorArchitecture="X86" type="win32" version="a.b.c.d" />
...
<file name="tabctl32.ocx">
<typelib tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" version="1.1" flags="control,hasdiskimage" helpdir="" />
<comClass clsid="{BDC217C5-ED16-11CD-956C-0000C04E4C0A}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" progid="TabDlg.SSTab.1" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst">
<progid>TabDlg.SSTab</progid>
</comClass>
<comClass clsid="{942085FD-8AEE-465F-ADD7-5E7AA28F8C14}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst" />
</file>
generated from OCS version 6.1.98.39 using https://github.com/wqweto/UMMM using a INI configuration file line like so:
File tabctl32.ocx
This is somewhat different from the one in the question:
*
*Has a relative path to the file
*Different list of classes
*Various different attributes
Hard to say without experimentation how important those differences might be.
I highly recommend logging your program in Process Monitor and seeing what if any errors you get in the log. This is usually how I identify tricky manifest problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61667173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: iPhone SDK: Text between UITableView sections? In the settings on the iphone, there is text between some of the UITableView sections. Sometimes larger text, sometimes smaller text. How do I do this?
Safari http://www.zedsaid.com/__data/assets/image/0019/1765/safari.png
I would like to know how to do the "Security" text, as well as the "Warn when visiting fraudulent websites." text.
Ideas?
A: They are section headers and footers. You can set them in table view datasource tableView:titleForHeaderInSection: and tableView:titleForFooterInSection: methods
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2889282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create a coordinate pair Have a list of coordinate pairs based on the provided longitudes and latitudes and I want to store the list in a variable coordpairs.
I try using the code below. When I checked the coordinate pair I only get the value for the longitude.
for x in range(len(longitudes)):
longitudes[x]
for y in range(len(latitudes)):
latitudes[y]
coordpairs = (longitudes[x], latitudes[y])
print(coordpairs)
I have about 20 latlon point that I want to pass to a coordinate pair and then use the coordinate pair to create a polygon using this code: poly = Polygon(coordpairs)
A: Due to your current indentation, coordpairs is only seeing the last value of longitudes each time it loops through y.
If you would like to use loops, you could do something like this (assuming your longitudes and latitudes lists are the same length)
coordpairs = []
for coord_num in range(len(longitudes)):
coord_pair = [longitudes[coord_num], latitudes[coord_num]]
coordpairs.append(coord_pair)
If you want to combine each item in longitudes with each item in latitudes without using loops, you can use
list(zip(longitudes, latitudes))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68370416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How convert telegram session to json file I searched the internet for a solution, but couldn't find anything
I tried to parse the session data, but the problem is that you can't get all the data, I couldn't find "register time"
What I want to see in Json:
{"session_file": "6285351202414", "phone": "6285351202414", "register_time": 1665007347, "app_id": id, "app_hash": "hash", "sdk": "iOS", "app_version": "1.52.10 Z", "device": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/100.0.5120.93 Mobile/15E148 Safari/604.1", "last_check_time": 1666735347, "avatar": "img/default.png", "first_name": "TGBOSS", "last_name": "Accounts", "username": "shykhiworyvi2", "sex": 1, "lang_pack": "en", "system_lang_pack": "en-US", "twoFA": "shykhiworyvi2_5631309146", "ipv6": false, "status": "ok", "status_time": 1666735347, "is_old": false, "proxy": []}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74421001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 'Dynamic' fields in DRF serializers My aim is to build endpoint which will surve to create objects of model with GenericForeignKey. Since model also includes ContentType, the actual type of model which we will reference is not known before object creation.
I will provide an example:
I have a 'Like' model which can reference a set of other models like 'Book', 'Author'.
class Like(models.Model):
created = models.DateTimeField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
Serializer may look like this:
class LikeSerializer(serializers.ModelSerializer):
class Meta:
model = models.Like
fields = ('id', 'created', )
What I want to achieve is to determine type of Like based on keys passed in request. The problem is that DRF do not pass those keys from request if they were not expilictly specified in Serializer fields. For example, POST request body contains:
{
"book":2
}
I want to do next
def restore_object(self, attrs, instance=None)
if attrs.get('book', None) is not None:
# create Like instance with Book contenttype
elif attrs.get('author', None) is not None:
# create Like instance with Author contenttype
In this case first if clause will be executed.
As you can see, The type determined based on key passed in request, without specifying special Field.
Is there any way to achieve this?
Thanks
A: You might try instantiating your serializer whenever your view is called by wrapping it in a function (you make a serializer factory):
def like_serializer_factory(type_of_like):
if type_of_like == 'book':
class LikeSerializer(serializers.ModelSerializer):
class Meta:
model = models.Like
fields = ('id', 'created', )
def restore_object(self, attrs, instance=None):
# create Like instance with Book contenttype
elif type_of_like == 'author':
class LikeSerializer(serializers.ModelSerializer):
class Meta:
model = models.Like
fields = ('id', 'created', )
def restore_object(self, attrs, instance=None):
# create Like instance with Author contenttype
return LikeSerializer
Then override this method in your view:
def get_serializer_class(self):
return like_serializer_factory(type_of_like)
A: Solution 1
Basically there is a method you can add on GenericAPIView class called get_context_serializer
By default your view, request and format class are passed to your serializer
DRF code for get_context_serializer
def get_serializer_context(self):
"""
Extra context provided to the serializer class.
"""
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}
you can override that on your view like this
def get_serializer_context(self):
data = super().get_serializer_context()
# Get the book from post and add to context
data['book'] = self.request.POST.get('book')
return data
And use this on your serializer class
def restore_object(self, attrs, instance=None):
# Get book from context to use
book = self.context.get('book', None)
author = attrs.get('author', None)
if book is not None:
# create Like instance with Book contenttype
pass
elif author is not None:
# create Like instance with Author contenttype
pass
Solution 2
Add a field on your serializer
class LikeSerializer(serializers.ModelSerializer):
# New field and should be write only, else it will be
# return as a serializer data
book = serializers.IntegerField(write_only=True)
class Meta:
model = models.Like
fields = ('id', 'created', )
def save(self, **kwargs):
# Remove book from validated data, so the serializer does
# not try to save it
self.validated_data.pop('book', None)
# Call model serializer save method
return super().save(**kwargs)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26829811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Zurb class show-for-large-only aligns all text left I'm building a small site which makes use of the show-for-XXXX-only classes.
My text is center aligned however applying the show-for-large-only class (or small/medium) aligns the text left. I cannot seem to override this.
Here's my HTML:
<div class="content">
<div class="row">
<div>
<div class="large-offset-2 large-8 small-offset-2 small-8 columns">
<div class="hero-table show-for-large-up">
<div class="hero-copy">
Here is my text. It keeps aligning left!
</div>
</div>
</div>
</div>
</div>
</div>
Here is my CSS:
.hero-table {
display: table;
width: 100%;
height: 320px;
}
.hero-copy {
display: table-cell;
vertical-align: middle;
font-family: "adobe-garamond-pro",serif;
font-size: 22px;
-webkit-font-smoothing: antialiased;
font-style: italic;
font-weight: 400;
color: #f2f2f2;
height: 320px;
background-color: red;
}
I wonder if the table code I am using to vertically align the content is clashing with the Zurb class.
A: The show-for-large-up and related classes apply display: inherit !important;, which is overriding your display: table. As a result, the whole div shrinks down to the minimum width that it can be (just large enough to fit the text), making it left aligned within its container.
The text itself appears to be left-aligned in all scenarios, regardless of the value of display. You will need text-align: center to change that (or you could apply a Foundation class like large-text-left).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27031154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flutter native admob is not working on iPhone I added flutter native admob in my app. It's working very well on Android devices but when I try run the app on IOS devices it turns loading screen. I added my code and also screenshot about this issue. How can I fix that? Thanks in advance.
new Container(
margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
height: 180,
width: double.infinity,
decoration: BoxDecoration(
color: Color(0xFFE7EFFF),
borderRadius: BorderRadius.circular(20),
),
child: NativeAdmob(
adUnitID:
'ca-app-pub-3940256099942544/2247696110',
loading: Center(
child: CircularProgressIndicator(
color: Color(0xFFEEA86C),
backgroundColor: Color(0xFFE7EFFF),
),
),
error: Text('Failed to load the ads'),
controller: _controller,
type: NativeAdmobType.full,
numberAds: 1,
options: NativeAdmobOptions(
ratingColor: Colors.orange,
showMediaContent: true,
headlineTextStyle:
NativeTextStyle(color: Colors.blue)),
),
)
This is how it works on Android devices.
This is how it works on IOS devices.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69837034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP - Filenames in HTTP-headers: Problem with whitespaces Working with CakePHP and Java Web Start I'm generating the necessary .jnlp-file within a controller in which among other things I set the filename as a header-field. That works fine as long I'm not trying to use special chars in the filenames. However, I'd like to enable every character that is possible on the main operating systems as a filename. So what I try to do is removing all the invalid characters by replacing them through empty strings. But there seems to be a problem with whitespaces which should be allowed in filenames.
That's the code:
$panel_id = 1
$panelname = 'w h i t e s p a c e s';
$filename = sprintf('"Project_%d_%s.jnlp"', $panel_id, $panelname);
$invalid_chars = array('<', '>', '?', '"', ':', '|', '\\', '/', '*', '&');
$filename = str_replace($invalid_filenamechars, '', $filename);
$this->header('Content-Disposition: attachment; filename=' . $filename);
When I do that, the resulting filename in the header is 'Project_1_w h i t e s p a c e', while Windows 7 wants to save the file as 'Project_1_w'. So it seems that my OS doesn't accept unescaped whitespaces in filenames? I would be happy with that explanation if it wasn't for the following: I left the lines 4 and 5, so that the code looks
$panel_id = 1
$panelname = 'w h i t e s p a c e s';
$filename = sprintf('"Project_%d_%s.jnlp"', $panel_id, $panelname);
$this->header('Content-Disposition: attachment; filename=' . $filename);
And now Windows is willing to save the file with all its whitespaces, still I cannot understand why. If I look at the filenames in the headers by using wireshark, both are the same. And if the sprintf-line is replaced by $filename = 'w h i t e s p a c e' or even $filename = $panelname it cuts the filename as in the first codesnippet. But I can replace the sprintf with the dottet-string-concat syntax and it works.
Can anyone tell me, what I'm overlooking?
A: The difference is the double quotes. With the first code you'll end up with:
Content-Disposition: attachment; filename=Project_1_w h i t e s p a c e s.jnlp
with the second code you'll end up with:
Content-Disposition: attachment; filename="Project_1_w h i t e s p a c e s.jnlp"
What you probably want is something like:
$panel_id = 1;
$panelname = 'w h i t e s p a c e s';
$filename = sprintf('"Project_%d_%s.jnlp"', $panel_id, $panelname);
$invalid_chars = array('<', '>', '?', '"', ':', '|', '\\', '/', '*', '&');
$filename = str_replace($invalid_filenamechars, '', $filename);
$this->header('Content-Disposition: attachment; filename="'.$filename.'"');
This strips any double quotes within $filename, but then makes sure that $filename is always surrounded by double quotes.
A: RFC2616, which is the HTTP/1.1 spec, says this:
The Content-Disposition response-header field has been proposed as a
means for the origin server to suggest a default filename if the user
requests that the content is saved to a file. This usage is derived
from the definition of Content-Disposition in RFC 1806.
content-disposition = "Content-Disposition" ":"
disposition-type *( ";" disposition-parm )
disposition-type = "attachment" | disp-extension-token
disposition-parm = filename-parm | disp-extension-parm
filename-parm = "filename" "=" quoted-string
disp-extension-token = token
disp-extension-parm = token "=" ( token | quoted-string )
An example is
Content-Disposition: attachment; filename="fname.ext"
Thus, sending this:
header('Content-Disposition: attachment; filename="' . $filename . '"');
conforms to the second form (quoted-string) and should do what you expect it to - take care to only send SPACE (ASCII dec 32 / hex 20) as whitespace, not some of the other fancy whitespace characters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7255628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: React: check if props undefined I want to do some things in componentDidUpdate if a prop is undefined, however, I can't because I just get the error Cannot read property 'serial' of undefined. Is there a way to solve this?
This is what I tired, but it doesn't work - I get the error:
componentDidUpdate(prevProps) {
if (typeof this.props.location.state.serial == "undefined"){
const database = db.ref().child("Devices/" + prevProps.location.state.serial);
...
Thanks in advance!
A: First you should make a test on the location and the location.state objects because they may be undefined because this method is called immediately after any update in the state or in the props from the parent component. you can see the Official doc. Rather you should do this:
componentDidUpdate(prevProps) {
if (this.props.location && this.props.location.state && typeof this.props.location.state.serial === "undefined"){
const database = db.ref().child("Devices/" + prevProps.location.state.serial);
...
Or if you'd like to take advantage of new EcmaScript syntax Optional chaining:
componentDidUpdate(prevProps) {
if (typeof this.props.location?.state?.serial === "undefined"){
const database = db.ref().child("Devices/" + prevProps.location.state.serial);
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65172662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to compare a substring from char array with some valid range? I have a char * which contains year and month lets say YYYYMM. How can I compare MM within the range of 01 to 12 ? Do I have to do atoi for the substring and do it or anything else exists?
A: If the first character of the month portion of the string is '0' the second must be between '1' and '9' inclusive to be valid. If the first character is '1' the second must be between '0' and '2' inclusive to be valid. Any other initial character is invalid.
In code
bool valid_month (const char * yyyymm) {
return ((yyymm[4] == '0') && (yyymm[5] >= '1') && (yyymm[5] <= '9')) ||
((yyymm[4] == '1') && (yyymm[5] >= '0') && (yyymm[5] <= '2'));
}
A: You can do atoi() of the substring or you can simply compare the ASCII values. For example:
if (buf[4] == '0')
{
// check buf[5] for values between '1' and '9'
}
else if (buf[4] == '1')
{
// check buf[5] for values between '0' and '2'
}
else
{
// error
}
Either way is acceptable. I guess it really depends on how you will eventually store the information (as int or string).
A: Assuming your char* variable is called "pstr" and is null terminated after the MM you can do:
int iMon = atoi(pstr + 4);
if ( (iMon >= 1) && (iMon <= 12) )
{
// Month is valid
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7813163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the file's path from file input? please tell me how to get a full file path from an <input type="file">
i have tried fileinput.value but it shows fakepath.
i have also tried mozFullPath.
A: For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () {
console.log(this.files[0].mozFullPath);
});
https://jsfiddle.net/SCK5A/
A: Due to major security reasons, most browsers don't allow getting it so JavaScript when ran in the browser doesn't have access to the user file system. having said that, the Firefox is exceptional and provides the mozFullPath property but it will only return an empty string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71015564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Logstash can't create index in elasticsearch for metricbeat file output I am trying to ingest metricbeat file output through logstash but logstash is not creating any index in elasticsearch. Below is my logstash .conf file
input {
file {
type => "my-metricbeat"
path => ["C:/tmp/metricbeat/metric*"]
codec => "json"
start_position => beginning
sincedb_path => "/dev/null"
}
}
output {
if([type] == "my-metricbeat") {
elasticsearch {
hosts => "http://localhost:9200"
index => "metricbeat-test-%{+YYYY.MM.dd}"
}
}
stdout { codec => rubydebug }
}
ELK version is 5.2.1
A: I see a missing bracket in your output.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44512424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a vectorized version of this code in Matlab I tried to vectorized my code but hit this roadblock and can't find an answer to it.
I have this array of 0 and 1, that works like a stopwatch. The way I create it is already vectorized. Here is a sample of it:
array of 0 and 1
Now, whenever the array is 1, a counter must be started multiplied by a sample rate, to give me the current measured time. And every time the first array is 0, the stopwatch must be reset for the next set of 1s. Here is a result of it.
array of calculated time
The code is this:
timearray = zeros(size(array01));
for ii = 1:size(array01)
if (array01(ii) == 0)
timearray(ii) = 0;
else
timearray(ii) = 0.005 + timearray (ii-1);
end
end
The issue with this for loop it's painfully slow. For a large array01 it takes many seconds and I'm pretty sure there's a clever way to do it, but I'm too dumb to see it.
Thanks for the help!
A: Here's a vectorized approach based on sparse matrices:
array01 = [0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0].'; % example data
sample_period = 0.005; % example data
t = sparse(1:numel(array01), cumsum([true; diff(array01(:))>0]).', array01);
timearray = sample_period*full(max(cumsum(t, 1).*t, [], 2));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67642796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get circle shaped image in swift 3 From the below code I got only oval shaped image I don't know why and what I did wrong..?
self.viewCirlce.layer.cornerRadius = self.viewCirlce.frame.size.width / 2
self.viewCirlce.clipsToBounds = true
A: This code used to display the circle image
image.layer.borderWidth = 1
image.layer.masksToBounds = false
image.layer.borderColor = UIColor.blackColor().CGColor
image.layer.cornerRadius = image.frame.height/2
image.clipsToBounds = true
A: My guess would be that the component you have called viewCirlce is a rectangle to start with, you are just setting the corner radius. If the component has the same width and height then this could give you a circle. If it's a rectangle, then you'll get an ellipse.
A: import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
image.layer.borderWidth = 1
image.layer.masksToBounds = false
image.layer.borderColor = UIColor.blackColor().CGColor
image.layer.cornerRadius = image.frame.height/2
image.clipsToBounds = true
}
A: add this code and make sure your viewCirlce is a square view
self.viewCirlce.layer.masksToBounds = true
A: Make sure height and width of viewCirlce are equal and put your this code in a method which is called after viewCirlce is loaded for e.g :
override func viewDidLayoutSubviews() {
self.viewCirlce = self.viewCirlce.frame.size.height / 2.0
self.viewCirlce.layer.masksToBounds = true
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43040451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error when trying to select event data with BigQuery I'm trying to select the event_dim.date within BigQuery but am unable to actually access it due to an error
Error: Cannot access field date on a value with type ARRAY<STRUCT<date STRING, name STRING, params ARRAY<STRUCT<key STRING, value STRUCT<string_value STRING, int_value INT64, float_value FLOAT, ...>>>, ...>> at [1:18]
My Query:
SELECT event_dim.date FROM `table`
I know I'm doing something wrong and any help would be greatly appreciated. Thanks!
A: Are you trying to get an array of the dates for each row? Then you want an ARRAY subquery:
SELECT ARRAY(SELECT date FROM UNNEST(event_dim)) AS dates
FROM `table`;
If you are trying to get all dates in separate rows, then you want to cross join with the array:
SELECT event.date
FROM `table`
CROSS JOIN UNNEST(event_dim) AS event;
To filter for a particular date:
SELECT event.date
FROM `table`
CROSS JOIN UNNEST(event_dim) AS event
WHERE event.date = '20170104';
Or you can parse the date string as a date type, which would let you filter on the year or week, for example:
SELECT date
FROM (
SELECT PARSE_DATE('%Y%m%d', event.date) AS date
FROM `table`
CROSS JOIN UNNEST(event_dim) AS event
)
WHERE EXTRACT(YEAR FROM date) = 2017;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41509117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CMFCToolBarComboBoxEdit handle delete button CMFCToolBarComboBoxEdit handles the BackSpace button but it doesn't handle the delete button.
Is there any way to handle the delete button except PreTranslateMessage?
if yes, what is this way?
if no, then how can I get the current cursor position in the control and how to remove specific char using its index so I can remove the char which on the right of the cursor if nothing is selected?
Thanks in advance.
A: Yes use, PreTranslateMessage. If you detected the sequence that should be handled, call:
if (..) // Check if you have a message that should
// be passed to the window directly
{
TranslateMessage(pMsg);
DispatchMessage(pMsg);
return TRUE;
}
You can do this always in PreTranslateMessage, when you detect that the message should be handled by the default control, and should not be handled by any other control in the chain of windows that execute PreTranslateMessage. This is also helpful if you have a combo box open and want the Page Down/Up handled internally and not by the view or any accelerator.
A: I've handled the delete key in the PreTranslateMessage as follows:
BOOL PreTranslateMessage(MSG* pMsg)
{
if(WM_KEYDOWN == pMsg->message && VK_DELETE == pMsg->wParam)
{
int iStartChar = -1, iEndChar = -1;
GetSel(iStartChar, iEndChar);
if(iStartChar != iEndChar)
Clear(); //clear the selected text
else
{
SetSel(iStartChar, iStartChar + 1);
Clear();
}
}
return CMFCToolBarComboBoxEdit::PreTranslateMessage(pMsg);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42607823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does a type assertion of "as any" fix this "No overload matches this call" error I am using React Navigation in a React Native project with TypeScript. The code below is somewhat simplified - hopefully it makes my question clearer.
I have a file <navigator.tsx> which sets up the navigator and type checks it ...
// navigator.tsx
// ...
import {NavigationContainer} from "@react-navigation/native"
import {createStackNavigator} from "@react-navigation/stack"
import {screen1, screen2} from "@screens"
export type StackNavigatorParams = {
screen1: undefined
screen2: undefined
}
const Stack = createStackNavigator<StackNavigatorParams>()
const Navigator = (): ReactElement => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="screen1" screenOptions={{headerShown: false}}>
<Stack.Screen name="screen1" component={screen1}></Stack.Screen>
<Stack.Screen name="screen2" component={screen2}></Stack.Screen>
</Stack.Navigator>
</NavigationContainer>
)
}
export default Navigator
I then have a button component which expects a screen name as a prop (nextPage)
// ButtonComponent.tsx
// ...
import { StackNavigatorParams } from "@config/navigator";
import { StackNavigationProp } from "@react-navigation/stack";
import { useNavigation } from "@react-navigation/native";
type dummyButtonProps = {
nextPage: "screen1" | "screen2";
};
export type StackNavigation = StackNavigationProp<StackNavigatorParams>;
const DummyButton = ({ nextPage }: dummyButtonProps) => {
const navigation = useNavigation<StackNavigation>();
return (
// ...
<Pressable
onPress={() => {
navigation.navigate(nextPage); // <-- TypeScript error here, however, if I pass "nextPage as any" the error goes away.
}}
></Pressable>
// ...
);
};
export default dummyButtonProps;
If I pass nextPage to navigation.navigate(nextPage) I get the lengthy error
No overload matches this call. specifically that Argument of type '["screen1" | "screen2"]' is not assignable ....
However, if I pass nextPage as any, the error goes away and the type checking works as expected, that is, I can only pass the strings 'screen1' or 'screen2' as props - anything else gets a TypeScript error. Why does making this type assertion work? Is this the best way to handle the problem?
Many thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74382517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Haskell incorrect indentation I have an error saying "Possibly incorrect indentation"
boyerMooreSearch :: [Char] -> [Char] -> [Int] -> Int
boyerMooreSearch string pattern skipTable
| skip == 0 = 0
| skip > 0 && (string length > pattern length) = boyerMooreSearch (substring string skip (string length)) pattern skipTable
| otherwise = -1
where
subStr = (substring 0 (pattern length))
skip = (calculateSkip subStr pattern skipTable)
Whats wrong with it? Can anyone explain indentation rules in Haskell?
A: On the line with substr, you have a string of whitespace followed by a literal tab character, and on the line with skip you have the same string followed by four spaces. These are incompatible; one robust, flexible way to get this right is to line things in a block up with exact the same string of whitespace at the beginning of each line.
The real rule, though, since you asked, is that tabs increase the indentation level to the next multiple of eight, and all other characters increase the indentation level by one. Different lines in a block must be at the same indentation level. do, where, let, and of introduce blocks (I may be forgetting a few).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13749850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to hide soft input keyboard on flutter after clicking outside TextField/anywhere on screen? Currently, I know the method of hiding the soft keyboard using this code, by onTap methods of any widget.
FocusScope.of(context).requestFocus(new FocusNode());
But I want to hide the soft keyboard by clicking outside of TextField or anywhere on the screen. Is there any method in flutter to do this?
A: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
behavior: HitTestBehavior.translucent,
child: rootWidget
)
A: onPressed: () {
FocusScope.of(context).unfocus();
},
This works for me.
A: This will work in the latest flutter version.
GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus.unfocus();
}
},
child: MaterialApp(
theme: ThemeData.dark().copyWith(
primaryColor: Color(0xFF0A0E21),
scaffoldBackgroundColor: Color(0xFF0A0E21),
),
home: LoginUI(),
),
);
A: Updated
Starting May 2019, FocusNode now has unfocus method:
Cancels any outstanding requests for focus.
This method is safe to call regardless of whether this node has ever requested focus.
Use unfocus if you have declared a FocusNode for your text fields:
final focusNode = FocusNode();
// ...
focusNode.unfocus();
My original answer suggested detach method - use it only if you need to get rid of your FocusNode completely. If you plan to keep it around - use unfocus instead.
If you have not declared a FocusNode specifically - use unfocus for the FocusScope of your current context:
FocusScope.of(context).unfocus();
See revision history for the original answer.
A: Best for me.
I wrap since Material App because global outside touch
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus.unfocus();
}
Resolve below,
I check Platform iOS only because Android can dismiss the keyboard the back button.
Listener(
onPointerUp: (_) {
if (Platform.isIOS) {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus.unfocus();
}
}
},
child: MaterialApp(
debugShowCheckedModeBanner: true,
home: MyHomePage(),
...
),
),
So happy your coding.
Flutter version
A: If you want to do this "the right way", use Listener instead of GestureDetector.
GestureDetector will only work for "single taps", which isn't representative of all possible gestures that can be executed.
Listener(
onPointerDown: (_) {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.focusedChild.unfocus();
}
},
child: MaterialApp(...),
);
A: You are doing it in the wrong way, just try this simple method to hide the soft keyboard. you just need to wrap your whole screen in the GestureDetector method and onTap method write this code.
FocusScope.of(context).requestFocus(new FocusNode());
Here is the complete example:
new Scaffold(
body: new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: new Container(
//rest of your code write here
),
),
)
Updated (May 2021)
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Body(),
),
);
This will work even when you touch the AppBar, new is optional in Dart 2. FocusManager.instance.primaryFocus will return the node that currently has the primary focus in the widget tree.
Conditional access in Dart with null-safety
A: Wrap whole screen in GestureDetector as
new Scaffold(
body: new GestureDetector(
onTap: () {
// call this method here to hide soft keyboard
FocusScope.of(context).requestFocus(new FocusNode());
},
child: new Container(
-
-
-
)
)
A: I just developed a small package to give any widget the kind of behavior you are looking for: keyboard_dismisser on pub.dev. You can wrap the whole page with it, so that the keyboard will get dismissed when tapping on any inactive widget.
A: With Flutter 2.5 GestureDetector.OnTap hasn't worked for me.
Only this worked:
return GestureDetector(
//keyboard pop-down
onTapDown: (_) => FocusManager.instance.primaryFocus?.unfocus(),
behavior: HitTestBehavior.translucent,
child: Scaffold(
A: child: Form(
child: Column(
children: [
TextFormField(
decoration: InputDecoration(
labelText: 'User Name', hintText: 'User Name'),
onTapOutside: (PointerDownEvent event) {
FocusScope.of(context).requestFocus(_unUsedFocusNode);
},
),
],
),
),
define focus Node
FocusNode _unUsedFocusNode = FocusNode();
override the onTapOutside method in TextFromField
onTapOutside: (PointerDownEvent event) {
FocusScope.of(context).requestFocus(_unUsedFocusNode);
},
Edit:
Note: it will work in sdk Flutter 3.6.0-0.1.pre Dart SDK 2.19.0-374.1.beta
A: I've added this line
behavior: HitTestBehavior.opaque,
to the GestureDetector and it seems to be working now as expected.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).calculatorAdvancedStageTitle),
),
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: Padding(
padding: const EdgeInsets.only(
left: 14,
top: 8,
right: 14,
bottom: 8,
),
child: Text('Work'),
),
)
);
}
A: Just as a small side note:
If you use ListView its keyboardDismissBehavior property could be of interest:
ListView(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
children: [],
)
A: try this if you are on a stack
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: Container(
height: double.infinity,
width: double.infinity,
color: Colors.transparent,
child: Stack(children: [
_CustomBody(_),
Positioned(
bottom: 15, right: 20, left: 20, child: _BotonNewList()),
]),
),
),
A: This will work
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return GestureDetector(
onTap: () {
FocusScopeNode focus = FocusScope.of(context);
if (!focus.hasPrimaryFocus && focus.focusedChild != null) {
focus.focusedChild.unfocus();
}
},
child: MaterialApp(
title: 'Flutter Demo',
A: so easy solution for beginner here is the smoothest solution for you while you need to hide-keyboard when user tap on any area of screen. hope its help you a lot.
Step - 1 : you need to create this method in Global class,
this method wrap you main widget into GestureDetector so when user tap outside the textfield it will hide keyboard automatically
Widget hideKeyboardWhileTapOnScreen(BuildContext context, {MaterialApp child}){
return GestureDetector(
onTap: () {
if (Platform.isIOS) { //For iOS platform specific condition you can use as per requirement
SystemChannels.textInput.invokeMethod('TextInput.hide');
print("Keyboard Hide");
}
},
child: child,
);
}
this method wrap you main widget into Listener so when user touch and scroll up it will hide keyboard automatically
Widget hideKeyboardWhileTapOnScreen(BuildContext context, {MaterialApp child}){
return Listener(
onPointerUp: (_) {
if (Platform.isIOS) {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus.unfocus();
print("Call keyboard listner call");
}
}
},
child: child,
);
}
Step - 2 : here is how to use Global method
@override
Widget build(BuildContext context) {
return hideKeyboardWhileTapOnScreen(context,
child: MaterialApp(
debugShowCheckedModeBanner: false, home: Scaffold(body: setAppbar())),
);
}
Widget setAppbar2() {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.orange),
home: Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(),
),
);
}
A: The simplest way - just write some code in your MaterialApp's builder method:
void main() {
runApp(const MyApp());
}
Widget build(BuildContext context) {
return MaterialApp(
home: const MyHomePage(),
builder: (context, child) {
// this is the key
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: child,
);
},
);
}
Then in all the pages it works.
A: As of Flutters latest version v1.7.8+hotfix.2, you can hide keyboard using unfocus() instead of requestfocus()
FocusScope.of(context).unfocus()
so whenever you tap in the body part keyboard gets hidden
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Login"),
),
body: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: Container(...)
),
);
}
A: If you want the behavior to be accessible on any screen in your app, wrap MaterialApp with GestureDetector:
// main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
),
);
}
}
Checking hasPrimaryFocus is necessary to prevent Flutter from throwing an exception when trying to unfocus the node at the top of the tree.
(Originally given by James Dixon of the Flutter Igniter blog)
A: *Update sept 2022 :: on flutter 3.0.2
if you have complex screen, i recommend to use Listener instead.
here i face issue before :
There is a lag/delay when catch the event on `GestureDetector` with `HitTestBehavior.opaque`?
documentation said:
Rather than listening for raw pointer events, consider listening for
higher-level gestures using GestureDetector
GestureDetector listening to high-level gesture. I think its caused some delay or lagging.
my workaround:
Listener(
behavior: HitTestBehavior.opaque,
onPointerDown: (_) {
FocusManager.instance.primaryFocus?.unfocus();
},
child: Scaffold()
this will be catch event when you tap anywhere.
A: It is true what maheshmnj said that from version v1.7.8+hotfix.2, you can hide keyboard using unfocus() instead of requestfocus().
FocusScope.of(context).unfocus()
But in my case I was still presented with a lot of layout errors, as the screen I navigated to was not capable of handling the layout.
════════ Exception Caught By rendering library ═════════════════════════════════
The following JsonUnsupportedObjectError was thrown during paint():
Converting object to an encodable object failed: Infinity
When the exception was thrown, this was the stack
#0 _JsonStringifier.writeObject (dart:convert/json.dart:647:7)
#1 _JsonStringifier.writeMap (dart:convert/json.dart:728:7)
#2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:683:21)
#3 _JsonStringifier.writeObject (dart:convert/json.dart:638:9)
#4 _JsonStringifier.writeList (dart:convert/json.dart:698:9)
This was handled by inserting "resizeToAvoidBottomInset: false" in the receiving screens Scaffold()
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false, // HERE
appBar: AppBar(
centerTitle: true,
title: Text("Receiving Screen "),
),
body: Container(...)
),
);
}
A: FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
You should check here https://flutterigniter.com/dismiss-keyboard-form-lose-focus/
A: This is best
Scaffold(
body: GestureDetector(
onTap: () {
if (messageFocusNode.hasFocus) {
messageFocusNode.unfocus();
}
},
child: new Container(
//rest of your code write here
)
)
A: I've found the easiest way to do it,
now you can use onTapOutside in the TextField widget
TextField(
onTapOutside: (event) {
print('onTapOutside');
FocusManager.instance.primaryFocus?.unfocus();
},)
This is called for each tap that occurs outside of the[TextFieldTapRegion] group when the text field is focused.
A: UPDATE NOVEMBER 2021
According to the new flutter webview documentation:
Putting this piece of code inside the given full example will solve the keyboard dismiss the issue.
@override
void initState() {
super.initState();
// Enable hybrid composition.
if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}
Full example code:
import 'dart:io';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewExample extends StatefulWidget {
@override
WebViewExampleState createState() => WebViewExampleState();
}
class WebViewExampleState extends State<WebViewExample> {
@override
void initState() {
super.initState();
// Enable hybrid composition.
if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}
@override
Widget build(BuildContext context) {
return WebView(
initialUrl: 'https://flutter.dev',
);
}
}
A: Wrap your material app with GestureDetector and use below code to hide keyboard from anywhere in app.
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus?.unfocus();
}
},
child: MaterialApp(
...
),
),
It will hide keyboard from whole app
A: You can dismiss the keyboard thoughout the app. Just by putting this code under builder in MaterialApp and if using Getx then under GetMaterialApp
MaterialApp(
builder: (context, child) => GestureDetector( onTap: (){
FocusManager.instance.primaryFocus?.unfocus();
}, child: child, ))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51652897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "179"
} |
Q: How do I investigate my java-based web service from .NET? I have publicised a Java method as a Web Service and I use the Web Service Explorer in Eclipse to invoke it and it works as expected. See http://soa2world.blogspot.com/2008/05/soap-client-eclipse-web-service.html for screen shots (not taken by me).
To ensure that this will also work against clients written in .NET I'd like to repeat the same excercise in a .NET based GUI thing, which given the WSDL creates a GUI interface (standalone or webbased) allowing me to put in values, and execute the result.
Visual Studio Express is fine as it is available for free, while the full Visual Studio requires a license purchase, so if I need it I require a good reason :)
What would be a clean, simple approach to this particular task? If it could do simple load testing that would be really nice :)
Thanks,
Edit: The WCF Test Client with Visual Web Studio Express 2008 speaks SOAP 1.2 only. The Metro stack from Sun only speaks SOAP 1.1. Is there an version of WCF Test CLient which speaks SOAP 1.1?
A: I'm not sure why Visual Studio express is fine as opposed to full VS.NET given your reasons. Both develop for Windows based platforms.
Have you looked at the WCF Test Client (WcfTestClient.exe)? You can find out more information about it here:
http://msdn.microsoft.com/en-us/library/bb552364.aspx
A: This is really simple, or I found it really simple when I did it with our Java based web-service hosted in tomcat.
*
*Start a new Solution of any kind in Visual Studio (should work in express).
*Right click the References folder in your Project and select Service Reference.
*Then put in your wsdl path into the address box and click Go.
*This retrieves information about your webservice from the wsdl and you'll be able to create a WebService reference from that.
*Then you can just use this like a Class and call the methods.
Sorry this isn't really well written and thought out but I don't currently have much time, good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/570096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Find PRs which were merged to branch, but aren't yet in any release I'm trying to get information from GitHub using GraphQL, on what pull requests aren't released - but are merged.
What queries I actually got:
// for getting latest release name
query {
repository(name: "${project.name}", owner: "${project.owner}") {
latestRelease {
name
}
}
}
// getting PRs (main struggle)
query {
repository(name: "${project.name}", owner: "${project.owner}") {
pullRequests(last: 100, baseRefName: "${project.branch}", states: MERGED) {
nodes {
title
number
}
}
}
}
And, of course, not everything is as I would like it to be, because I only collect the last 100 PRs for a given branch.
My case with the repo causes some PRs to be merged before the release is set, but aren't in the release itself. "Thanks to this", therefore, I can't, for example, base on the time I would put in after, which I would take from the query:
latestRelease {
name
createdAt <-- added
}
Any ideas for something like this to help me achieve my goal?
(A pseudo argument, because I don't have an idea for it yet. Unfortunately, the github documentation has no such argument/similar.)
pullRequests(...previous arguments, notIn: "${lastReleaseName}")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73587077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: laravel update and select I have a situation to update the row based on id and return the complete row. I can do it in two queries but i want to do it in one query only. I have write this...
$result= DB::table($this->table)
->whereRaw($where['rawQuery'], $where['bindParams'] ? $where['bindParams'] : array())
->increment($updateField);
if($result){
return DB::table($updateTable)
->select('id')
->where('campaign_id',$where['bindParams'])
->where('date',date("Y-m-d"))
->get();
}else{
throw Exception("Error in fetching data");
}
A: I copied this from what you commented in your question:
No i want to return the id of the updated row or complete row if possible
If you want to return the ID of the just updated 'row' you're talking about. You can use Eloquent to accomplish this.
You can use a route like this:
Route::put('demo/{id}', Controller@update);
Then in your update function in your controller you can get the ID.
Find the model with $model = Model::find(id);
do things with the data you get.
Like $model->name = Input::get('name');
Then use $model->save();
After saving you can do $model->id;
Now you get back the ID about the row you just updated.
Refer back to this question:
Laravel, get last insert id using Eloquent
A: But any way it'll always be at least 2 queries (a SELECT and an UPDATE in MySQL, however you do it)
You can check Laravel Eloquent if you want a "cleaner" way to to this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40013965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I optimize omp pragmas to run code between parallel regions? I have this C code that I need to optimize with OpenMP, I can't write the original code, but here is a surrogate:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif
void Funct(double *vec, int len)
{
int i;
double tmp;
//Section 1
#pragma omp parallel for
for ( i = 0; i < len; i++ ) //Code that initialize vec, it simulates an initialization in the original code
vec [ i ] = i;
//Section 2
//This code must be run sequentially
tmp = vec [ 0 ];
vec [0 ] = vec [ len - 1 ];
vec [ len - 1 ] = tmp;
tmp = vec [ 0 ];
vec [0 ] = vec [ len - 1 ];
vec [ len - 1 ] = tmp;
//End of the sequential code
//Section 3
#pragma omp parallel for
for ( i = 0; i < len; i++ ) //Code to simulate loadwork on vec
{
vec [ i ] = pow(vec[i], 2 );
vec [ i ] = sqrt ( vec [ i ] );
vec [ i ] += 1;
vec [ i ] = pow(vec[i], 2 );
vec [ i ] = sqrt ( vec [ i ] );
vec [ i ] -= 1;
}
}
int main ()
{
double *vec;
int i;
vec = (double *) malloc ( sizeof ( double ) * 5104 ); //Length of the vector in the original code
for ( i = 0; i < 1000000; i++ ) //Iteration in the original code
Funct(vec, 5104 );
for ( i = 0; i < 5; i++ ) // Access the array to avoid -O2 cancellations
printf ("%.2f ", vec [ i * 1000 ] );
return 0;
}
In Funct, Section 1, 2 and 3 must be executed sequentially; Section 2 is strictly sequential.
In the original code I'm forced to use parallelization inside the function Funct(...), so, sadly, the cost of the creation of the threads are multiplied by the number of iterations, but is not a problem since it still permits some time optimization when the for inside the main or the vec length arise ( If you have suggestions I'm very open to listen ). The problem is "Section 2", in fact it makes OMP, I think, create a barrier or a wait, but that slows down the execution; If I remove that section I get a pretty acceptable optimization, respect to the sequential code; saddly I can't.
I've tried omp single, omp critical, and so on, to see if it would have assigned the code to some of threads of the prvious pool, but none, is there a way to make more performant? ( Like drastically change the pragmas, not a problem )
( Compiled with gcc file.c -o file.out -lm -O2 -fopenmp, tested under Linux Lubuntu using time ./file.out )
Edit 1:
I'd like to point out that
tmp = vec [ 0 ];
vec [0 ] = vec [ len - 1 ];
vec [ len - 1 ] = tmp;
tmp = vec [ 0 ];
vec [0 ] = vec [ len - 1 ];
vec [ len - 1 ] = tmp;
Is just random code I've put inside the method to make clear that must be run sequentially ( it performs two time the same operation, it swaps vec [ 0 ] and vec [ len - 1 ], so at the end of the execution nothing really happend );
I could have written any other function or code instead;
For instance I could have put
Foo1();
Foo2();
Foo3();
A: Set your loop indices to
for ( i = 1; i < len-1; i++ )
and treat the first and last elements as special cases. They can be executed outside of the OpenMP regions.
A: There is an implicit barrier at the end of a parallel section. A way to improve the code would be to enclose all the function into a #pragma omp parallel directive, so that threads are spawned only once at the beginning rather than twice at sections 1 and 3.
The implicit barrier will still be there at the end of the omp for loops, but this is still less overhead than spawning new threads. Section 2 would then have to be enclosed in an omp single block (this may well be what you have done as you mention that omp single did not work better, but it is not 100% clear).
void Funct(double *vec, int len)
{
// Create threads
#pragma omp parallel
{
//Section 1
#pragma omp for
for (int i = 0; i < len; i++ ){
//Code that initialize vec, it simulates an initialization in the original code
vec [ i ] = i;
} // Implicit barrier here (end of omp for loop)
//Section 2
//This code must be run sequentially
// It will start only once the section 1 has been completed
#pragma omp single
{
double tmp;
tmp = vec [ 0 ];
vec [0 ] = vec [ len - 1 ];
vec [ len - 1 ] = tmp;
tmp = vec [ 0 ];
vec [0 ] = vec [ len - 1 ];
vec [ len - 1 ] = tmp;
} // Implicit barrier here (end of omp single block)
//End of the sequential code
//Section 3
#pragma omp for
for ( i = 0; i < len; i++ ) //Code to simulate loadwork on vec
{
vec [ i ] = pow(vec[i], 2 );
vec [ i ] = sqrt ( vec [ i ] );
vec [ i ] += 1;
vec [ i ] = pow(vec[i], 2 );
vec [ i ] = sqrt ( vec [ i ] );
vec [ i ] -= 1;
} // Implicit barrier here end of for
} // Implicit barrier here end of parallel + destroy threads
}
The best would be to move the omp parallel directive to the main function, so that threads are spawned only once.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53949716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Encrypted URL results in Bad Request Before stating the problem I want to say that I've read all the posts that suggest that what I'm doing is a bad idea and I AGREE WITH YOU 100% but, our customer insists that he wants the id on the URL to be encrypted so we don't have much choice.
The application is ASP .Net MVC 2 and we are using the basic default route of
"{controller}/{action}/{id}" in which the id is encrypted.
The code that returns the encrypted id is as follows:
return HttpUtility.UrlEncode(Encryptor.Encrypt(inputText));
The Encrypt method is using the System.Security.Cryptography.RijndaelManaged class and we get something like:
http://localhost:3396/MyController/MyAction/%253fval%253dWrikkm9UeEmHdsaMJyjgzA%253d%253d
Now when I click on the link I always get a blank page saying:
Server Error in '/' Application.
HTTP Error 400 - Bad Request.
I guess this error is being sent by IIS since the request never reaches the controller.
Any help will be very much appreciated.
A: Perhaps your customer doesn't want people "guessing" incremental or string IDs in the URL, which is how a lot of insecure web applications get hacked (E.g. Sony) right? It's a slightly-uninformed demand, but well intentioned. I understand your pain.
Would your customer know the difference between a hashed and encrypted ID? Maybe your life could be simpler if you just used salted+hashed IDs, which adds just as much obfuscation (not security!) to the URL, minus the need to URLEncode the encrypted value.
Ideally, you could get this "encrypted ID" requirement punted in favor of a combination of SSL, an authentication system with page level rights-enforcement, and solid audit trail logging. This is standard web application security stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8273111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fill NAs with Previous non-NA available value R I am trying to fill the NA values with the non-NA previous available in a set of data of 3 million rows. At the moment I am able to do it but it takes about 3hrs.
Constrains - I cannot use any library, it has to be done with R basic
Data - My data looks as following (Extract)
Data Extract As Example
At the moment I have been using the following code
CHARDIF <- diff(VERINDEX_VEC)
k = 1
for (j in VERINDEX_VEC){
#when value is in vector calculate difference to next value and copy VER.
Special cases for First and Last value
ifelse(j == 1, ALL_POS$C01[j:CHARDIF[k]] <- ALL_POS$C01[j],
ifelse(j == max(VERINDEX_VEC), ALL_POS$C01[j:max(as.numeric
(row.names(ALL_POS)))] <- ALL_POS$C01[j],ALL_POS$C01[j:(j+CHARDIF[k]-1)] <-
ALL_POS$C01[j]))
k = k + 1
}
As you can see I have a vector with the non-NA positions, and then I calculate the difference between the positions, and that helps me to select the range I want to paste as I know when the next non-NA value is happening.
Does anyone have a better solution? a faster one in particular
A: First I will generate random data to test this
# generate random data
test_data <- data.frame(x = 1:100, y = rnorm(100))
# add random NAs
test_data$y[sample(1:100, 50)] <- NA
Now try this:
# locate non NAs in the wanted column
not_na <- which(!is.na(test_data$y))
# define the function replace_NAs_custom
replace_NAs_custom <- function(i, col){
if(is.na(col[i])){
col[i] <- col[max(not_na[not_na < i] )]
}
return(col[i] )
}
test_data$y_2 <- unlist(lapply(1:nrow(test_data), replace_NAs_custom, test_data$y))
A: It looks like your code is doing a lot of calculating and memory allocation every time it loops. To decrease time we want to decrease how much work the loop does each iteration.
I'm not 100% clear on your problem, but I think I've got the gist of it. It sounds like you just want to take the last non-NA value and copy it into the row with the NA value. We can use a pair or indexes to do this.
In the following method all of the memory is already pre-allocated before I enter the loop. The only memory action is to replace a value (NA) with another value. Other then that operation there is a check to see if the value is NA and there is an addition operation on the index. In order to get significantly faster on this problem you would need to use c-optimized vector functions (probably from a package/library).
To use the previous value to fill NA:
# Fill with previous non-NA value
VERINDEX_VEC <- c(NA,"A1","A2",NA,NA,"A3",NA)
VERINDEX_VEC
# [1] NA "A1" "A2" NA NA "A3" NA
non_na_positions <- which(!is.na(VERINDEX_VEC))
# If the first value is NA we need to fill with NA until we hit a known value...
if(is.na(VERINDEX_VEC[1])){
non_na_positions <- c(NA,non_na_positions)
}
index = 1
for(i in 1:length(VERINDEX_VEC)){
if(is.na(VERINDEX_VEC[i])) {
VERINDEX_VEC[i] <- VERINDEX_VEC[non_na_positions[index]]
} else {
index <- index + 1
}
}
VERINDEX_VEC
# [1] NA "A1" "A2" "A2" "A2" "A3" "A3"
To use the next value to fill NA:
# Fill with next non-NA Value
VERINDEX_VEC <- c(NA,"A1","A2",NA,NA,"A3",NA)
VERINDEX_VEC
# [1] NA "A1" "A2" NA NA "A3" NA
non_na_positions <- which(!is.na(VERINDEX_VEC))
# Never need the first position of the vector if we are looking-ahead...
index <- ifelse(non_na_positions[1]==1,2,1)
for(i in 1:length(VERINDEX_VEC)){
if(is.na(VERINDEX_VEC[i])) {
VERINDEX_VEC[i] <- VERINDEX_VEC[non_na_positions[index]]
} else {
index <- index + 1
}
}
VERINDEX_VEC
# [1] "A1" "A1" "A2" "A3" "A3" "A3" NA
A: I believe I may have found a faster way, at least a lot faster than my last answer, however I couldn't compare it with your code, since I couldn't reproduce the output.
(see below for the Benchmarking results)
Can you try this:
set.seed(223)
# generate random data
test_data <- data.frame(x = 1:1000, y = rnorm(1000))
# add random NAs
test_data$y[sample(1:1000, 500)] <- NA
# which records are filled
not_na <- which(!is.na(test_data$y))
# calculate the distance from the previous filled value
# this is to identify how many times should each value be repeated
dist <- unlist(lapply(1:(length(not_na) - 1),
function(i){
not_na[i+1] - not_na[i]
}))
# compine both to create a kind of "look-up table"
not_na <- data.frame(idx = not_na,
rep_num = c(dist, nrow(test_data) - not_na[length(not_na)] + 1))
test_data$y_3 <- unlist(lapply(1:nrow(not_na),
function(x){
rep(test_data[not_na$idx[x], "y"], times = not_na$rep_num[x])
}))
The Benchmarking :
f1() is the last answer
f2() is this answer
*
*For 100.000 rows in test_data
# microbenchmark(f1(), times = 10)
# Unit: seconds
# expr min lq mean median uq max neval
# f1() 39.54495 39.72853 40.38092 40.7027 40.76339 41.29006 10
# microbenchmark(f2(), times = 10)
# Unit: seconds
# expr min lq mean median uq max neval
# f2() 1.578852 1.610565 1.666488 1.645821 1.736301 1.755673 10
*For 1.000.000 rows the new approach needed about 16 seconds
# microbenchmark(f2(), times = 1)
# Unit: seconds
# expr min lq mean median uq max neval
# f2() 16.33777 16.33777 16.33777 16.33777 16.33777 16.33777 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50586602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Datatables js: custom css I'm using Datatables.js with Laravel. I'm post a request with ajax and I want to show the returned response in the table. Is there a way to customize this table? Can we customize the tags by giving them an id or class name? I tried this but didn't get any results.
For example: I want to make the text color in the first column green or I want to add a photo next to the text in the second column.
$(function() {
$("#ordersTable").DataTable({
processing: true,
serverSide: false,
ajax: "{{route('index22')}}",
data : [{"orderId":"1","orderNumber":"ABC123", "orderDate" : "12/Jun/2022"}],
columns: [{
data: 'orderId'
},
{
data: 'orderNumber'
},
{
data: 'orderDate'
},
]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<table id="ordersTable" class="table-striped table">
<thead>
<tr>
<td>ORDER NUMBER</td>
<td>STORE</td>
<td>STATUS DATE</td>
</tr>
</thead>
</table>
A: You can change the text colour simply using css.
To add an image, you can add a custom render function as below:
$(function() {
$("#ordersTable").DataTable({
processing: true,
serverSide: false,
ajax: "{{route('index22')}}",
data : [{"orderId":"1","orderNumber":"ABC123", "orderDate" : "12/Jun/2022"}, {"orderId":"2","orderNumber":"DEF987", "orderDate" : "11/Jun/2022"}],
columns: [{
data: 'orderId'
},
{
data: 'orderNumber',
render: function (data, type)
{
if (type === 'display')
{
return "<img src='https://via.placeholder.com/80x40.png?text=ORDER' />" + data;
}
return data;
}
},
{
data: 'orderDate'
},
]
});
});
#ordersTable tbody tr td:first-child
{
color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<table id="ordersTable" class="table-striped table">
<thead>
<tr>
<td>ORDER ID</td>
<td>ORDER NUMBER</td>
<td>ORDER DATE</td>
</tr>
</thead>
</table>
A: Please, refer to datatable documentation: datatable examples , and for suggestion I would go with Bootstrap 5 for some decent look.
Also, these are CSS selectors:
For Table Header
table>thead>tr>th{
your styling
}
For Pagination
.dataTables_paginate{
styles
}
For Pagination Links
.dataTables_paginate a {
padding: 6px 9px !important;
background: #ddd !important;
border-color: #ddd !important;
}
Also, if you using Bootstrap, you will might have to modify the bootstrap.min.css at line :3936
.pagination>li>a, .pagination>li>span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #337ab7;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72588156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to test modal screens of react-navigation in React Native app? In the app we open modal screens in the following way:
navigation.navigate('BottomSheetModal', {
title: 'Some Title',
children: (
<SomeChildren
{...someProps}
/>
),
});
/* OR */
navigation.navigate('PopUpModal', {
title: 'Some Title',
icon: <Icons.Fingerprint />,
buttonText: 'Some Text',
onButtonPress: someFunction,
{...someOtherProps}
});
Here is the root navigator structure:
export const RootStackNavigator = () => {
return (
<>
<StatusBar barStyle="dark-content" backgroundColor={COLORS.TRANSPARENT} translucent />
<NavigationContainer ref={navigationRef}>
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="App" component={AppTabNavigator} />
{/* ... other screens ... */}
<Stack.Group
screenOptions={{
animation: 'fade',
presentation: 'transparentModal',
gestureEnabled: false,
}}
>
<Stack.Screen name="PopUpModal" component={PopUpModal} />
<Stack.Screen name="LoadingModal" component={LoaderModal} />
<Stack.Screen name="BottomSheetModal" component={BottomSheetModal} />
</Stack.Group>
</Stack.Navigator>
</NavigationContainer>
</>
);
};
During a test, I can check the call of mocked navigate method, but I can't get access to any modal screen's tree and interact with its elements (buttons, inputs, etc.). renderWithProviders is just a regular call of create() method of react-test-renderer wrapped with providers
it('should show a modal', async () => {
const tree = await renderWithProviders(<Dashboard {...props} />, preloadedState);
// The modal window should be opened after <Dashboard /> mount
await act(async () => {
await wait(1000); // Wait for the API request to complete
});
expect(mockedNavigate).toBeCalledWith(
'PopUpModal',
expect.objectContaining({
...someFields
})
);
const modal = tree.root.findByType(PopUpModal); // Error: No instances found with node type: "PopUpModal"
});
Unfortunately, I am limited to the use of react-test-renderer only, and can't use React Native Testing Library.
Is there a way to get access to modal screens from the test of the current screen?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73624651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to use vba to open text files that are fixed column delimited and different sizes I have many text files which are first opened through vba and then processed. Nevertheless, all my text files are fixed length delimited. The only problem is that each file has a different column size.
FieldInfo:=Array(Array(0, 1), Array(6, 1), Array(11, 1), Array(46, 1), Array(51, 1), Array(57, 1), Array(71, 1), Array(79, 1), Array(86, 1), Array(96, 1), Array(100, 1), Array(107, 1), Array(114, 1), Array(123, 1), Array(132, 1), Array(141, 1)), TrailingMinusNumbers:=True
and another one might be:
FieldInfo:=Array(Array(0, 1), Array(7, 1), Array(22, 1), Array(77, 1), Array(141, 1)), TrailingMinusNumbers:=True
But if I do it manually, Excel always suggests the correct array independently of the file.
Is it possible to either let Excel suggest these Arrays or at least get these Arrays some other way?
A: I assume you are using the Workbooks.OpenText method to open the file, i.e. something like:
Workbooks.OpenText Filename:="C:\Temp\myFile.txt", _
Origin:=xlWindows, _
StartRow:=1, _
DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 1), Array(6, 1), Array(11, 1), Array(46, 1), Array(51, 1), Array(57, 1), Array(71, 1), Array(79, 1), Array(86, 1), Array(96, 1), Array(100, 1), Array(107, 1), Array(114, 1), Array(123, 1), Array(132, 1), Array(141, 1)), _
TrailingMinusNumbers:=True
If so, you can just drop off the FieldInfo parameter and force Excel to make its own guess:
Workbooks.OpenText Filename:="C:\Temp\myFile.txt", _
Origin:=xlWindows, _
StartRow:=1, _
DataType:=xlFixedWidth, _
TrailingMinusNumbers:=True
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42175729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cancelled amount and a corresponding entry - Postgres I have the payment table:
There could be erroneous entries when a payment was made by mistake - see row 5 and then, this payment gets cancelled out - see row 6. I cannot figure out the query where I don't only cancel the negative amounts but also the corresponding pair. Here is the desired outcome:
You could also see the cases when several wrong payments were made and then, I need to cancel out all payments which if summed up give the cancelled amount.
The desired outcome:
I found Remove Rows That Sum Zero For A Given Key, Selecting positive aggregate value and ignoring negative in Postgres SQL and https://www.sqlservercentral.com/forums/topic/select-all-negative-values-that-have-a-positive-value but it is not exactly what I need
I already don't mind cases like case 2. At least, find a reliable way to exclude those like 5;-5.
A: you can try this for deleting the rows from the table :
WITH RECURSIVE cancel_list (id, total_cancel, sum_cancel, index_to_cancel) AS
( SELECT p.id, abs(p.amount), 0, array[p.index]
FROM payment_table AS p
WHERE p.amount < 0
AND p.id = id_to_check_and_cancel -- this condition can be suppressed in order to go through the full table payment
UNION ALL
SELECT DISTINCT ON (l.id) l.id, l.total_cancel, l.sum_cancel + p.amount, l.index_to_cancel || p.index
FROM cancel_list AS l
INNER JOIN payment_table AS p
ON p.id = l.id
WHERE l.sum_cancel + p.amount <= l.total_cancel
AND NOT l.index_to_cancel @> array[p.index] -- this condition is to avoid loops
)
DELETE FROM payment_table AS p
USING (SELECT DISTINCT ON (c.id) c.id, unnest(c.index_to_cancel) AS index_to_cancel
FROM cancel_list AS c
ORDER BY c.id, array_length(c.index_to_cancel, 1) DESC
) AS c
WHERE p.index = c.index_to_cancel;
you can try this for just querying the table without the hidden rows :
WITH RECURSIVE cancel_list (id, total_cancel, sum_cancel, index_to_cancel) AS
( SELECT p.id, abs(p.amount), 0, array[p.index]
FROM payment_table AS p
WHERE p.amount < 0
AND p.id = id_to_check_and_cancel -- this condition can be suppressed in order to go through the full table payment
UNION ALL
SELECT DISTINCT ON (l.id) l.id, l.total_cancel, l.sum_cancel + p.amount, l.index_to_cancel || p.index
FROM cancel_list AS l
INNER JOIN payment_table AS p
ON p.id = l.id
WHERE l.sum_cancel + p.amount <= l.total_cancel
AND NOT l.index_to_cancel @> array[p.index] -- this condition is to avoid loops
)
SELECT *
FROM payment_table AS p
LEFT JOIN (SELECT DISTINCT ON (c.id) c.id, c.index_to_cancel
FROM cancel_list AS c
ORDER BY c.id, array_length(c.index_to_cancel, 1) DESC
) AS c
ON c.index_to_cancel @> array[p.index]
WHERE c.index_to_cancel IS NULL ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69723431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to build a retrieved data from a form page to another page using list view builder Hi there I’m new to flutter and this app takes an input from a user and outputs a list with the value from the text field all in one page but what I wanted was it to output the list view builder in another page with the value from the text field in another page I’ll be greatful if anyone can help,this is the code:-
import 'package:flutter/material.dart';
class Demo extends StatefulWidget {
@override
_DemoState createState() => new _DemoState();
}
class _DemoState extends State<Demo> {
List<String> _items = new List(); // to store comments
final myController = TextEditingController();
void _addComment() {
if (myController.text.isNotEmpty) {
// check if the comments text input is not empty
setState(() {
_items.add(myController.text); // add new commnet to the existing list
});
myController.clear(); // clear the text from the input
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("DEMO")),
body: Container(
padding: EdgeInsets.all(15),
child: Column(children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: TextField(
style: TextStyle(color: Colors.black),
controller: myController,
maxLines: 5,
keyboardType: TextInputType.multiline,
)),
SizedBox(width: 15),
InkWell(
onTap: () {
_addComment();
},
child: Icon(Icons.send))
]),
SizedBox(height: 10),
Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (BuildContext ctxt, int index) {
return Padding(
padding: EdgeInsets.all(10),
child: Text("${(index + 1)}. " + _items[index]));
}))
])));
}
}
A: You can move the ListView in some other widget, I have made an example for reference:
class OtherPage extends StatelessWidget {
final List<String> items;
const OtherPage({Key key, this.items}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Details'),
),
body: Center(
child: ListView.builder(
shrinkWrap: true,
itemCount: items.length,
itemBuilder: (BuildContext ctxt, int index) {
return Card(
child: Padding(
padding: EdgeInsets.all(10),
child: Text(
"${(index + 1)}. " + items[index],
style: TextStyle(
fontSize: 20.0,
),
),
),
);
},
),
),
);
}
}
What you need to do is replace the Existing ListView.Builder from the column with the following Code:
RaisedButton(
child: Text('OtherPage'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => OtherPage(
items: _items,
),
),
);
},
),
Check this out and let me know in comments if you have any doubts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59444167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to add a title property to a label to use in a webpartcontrol I'm trying to add a title to web label control. Here is the code where I am trying to use a title on a label:
<asp:WebPartZone ID="WebPartZone1" runat="server"
HeaderText="Welcome to my web page!"
LayoutOrientation="horizontal" Width="160px">
<ZoneTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"
**Title**="Welcome to my web page!">
Welcome to the page!
</asp:Label>
</ZoneTemplate>
Any help will be greatly appreciated.
Tom Magaro
A: What are you trying to do with the Title specifically? If you want a custom property on a label control you will need to create a custom control that inherits from the Label control. If you just want to set the text then use the Text property. If you want a tooltip then set the ToolTip property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6669635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to run a script block locally as admin using powershell I am trying to write a powershell script that runs a specific code block as a domain admin and moves a computer to a specific OU.
If I run it as a domain admin, it works fine, but the problem is it usually runs it as a local admin; which obviously won't add the computer to the domain.
So I added the credentials as part of the script, but it doesn't seem to be working.
Here is my code:
CLS
$command = {
# Specify, or prompt for, NetBIOS name of computer.
$Name = $env:COMPUTERNAME
# Retrieve Distinguished Name of current domain.
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Root = $Domain.GetDirectoryEntry()
$Base = ($Root.distinguishedName)
# Use the NameTranslate object.
$objTrans = New-Object -comObject "NameTranslate"
$objNT = $objTrans.GetType()
# Initialize NameTranslate by locating the Global Catalog.
$objNT.InvokeMember("Init", "InvokeMethod", $Null, $objTrans, (3, $Null))
# Retrieve NetBIOS name of the current domain.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (1, "$Base"))
$NetBIOSDomain = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 3)
# Retrieve Distinguished Name of specified object.
# sAMAccountName of computer is NetBIOS name with trailing "$" appended.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (3, "$NetBIOSDomain$Name$"))
$ComputerDN = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 1)
#Bind to computer object in AD.
$Computer = [ADSI]"LDAP://$ComputerDN"
#Specify target OU.
$TargetOU = "OU=Block-Policies,OU=Windows 10,OU=LAPTOPS,OU=COMPUTERS,OU=COMPUTER-SYSTEMS,DC=domain,DC=com"
#Bind to target OU.
$OU = [ADSI]"LDAP://$TargetOU"
# Move computer to target OU.
$Computer.psbase.MoveTo($OU)
}
#Credentials
$domain = "domain.com"
$password = "2093dhqwoe3212" | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\DomainAdmin"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
#Run the command with escalation
Invoke-Command -Credential credential -ComputerName localhost -ScriptBlock {$command}
I know the credentials work because if I manually type them in and run the script, it works. I have tried using invoke-command as well as
start-job -ScriptBlock {$command} -Credential $credential
Neither seem to be working for me.
The start-job seems to go through, but doesn't actually move the computer. The invoke-command gives me an error.
"[localhost] Connecting to remote server localhost failed with the following error message: The client cannot connect to the destination specified in the request ..."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59257180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to redirect to another domain while clicking on chart in asp.net I am using the asp.net chart control.
I need to redirect to a url of another domain by clicking an X-axis value or series that should open as a new window. I used to Series.Points[index].url = "http://www.domainxxx.com/abc.aspx?abcvalue=1000".
How can I open it as a new window?
A: Add the target attribute to open in new window:
$("SeriesId").attr("target", "_blank");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41562656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't import .xlsx into R using readxl Here's my code:
library(readxl)
datasets <- system.file("C:/Users/tyeg/Documents/Gamma Counter Processing/Inflammation/Study Compilation Sheet2.xlsx", package = "readxl")
read_excel(datasets)
Here's the error I get:
'' does not exist in current working directory
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41047990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Memory optimisation I'm just curious to know if I can reduce memory usage of Matlab by using some option.
Clicking on a variable in workspace shows a long digit which may not be necessary in most of cases. e.g.,
[20, 25.0540913632159, 16.2750000000000, 3.08852992798468];
for me 25.054091 may be more than ok. Are there any options that Matlab just reduce numbers for internal calculation and does it make any difference.
A: Modern PC's use floating point numbers to calculate non-integral values.
These come in two standardized variants: float and double, where the latter is twice the size of the former.
Matlab, by default uses (complex) doubles for all its calculations.
You can force it to use float (or as Matlab calls them, single) by specifiying the type:
a = single([20, 25.0540913632159, 16.2750000000000, 3.08852992798468]);
This should use half the memory, and you lose some precision that may or may not be important in your application. Make sure the optimization is worth it before doing this, as execution speed may even be slower (due to builtin functions only operating on double, hence requiring two conversions extra).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16164761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I create an export to Google Sheet button on a web page? Say I have a page like this:
textarea {width:300px;height:200px}
button {display:block}
<textarea value="f">id,value
2,alpha
3,beta
14,test</textarea>
<button>Open in Google Sheet</button>
I want the user to click the button "Open in Google Sheet" and open the csv as a spreadsheet.
I saw that Google Analytics and some other Google products have this button. But I didn't find 3rdparty webapps have this. Is that possible for me to use it?
A: I believe your goal is as follows.
*
*From I want the user to click the button "Open in Google Sheet" and open the CSV as a spreadsheet., you want to retrieve the text value from the textarea tab and create a Google Spreadsheet using the text value, and then, want to open the Google Spreadsheet.
In order to achieve your goal, how about the following flow?
*
*Retrieve the text value from the textarea tab.
*Send the text value to Web Apps created by Google Apps Script.
*At Web Apps, a new Google Spreadsheet is created and the text value is put to the sheet.
*In order to open the created Spreadsheet, change the permission of the Spreadsheet. In this case, it is publicly shared as the read-only. This is the sample situation.
*Return the URL of the Spreadsheet.
When this flow is reflected in the script, it becomes as follows.
Usage:
1. Create a new project of Google Apps Script.
Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.
If you want to directly create it, please access https://script.new/. In this case, if you are not logged in to Google, the log-in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.
2. Sample script.
Please copy and paste the following script to the created Google Apps Script project and save it. This script is used for Web Apps. In this sample, the value is sent as the POST request.
function doPost(e) {
const csv = Utilities.parseCsv(e.postData.contents);
const ss = SpreadsheetApp.create("sample");
ss.getSheets()[0].getRange(1, 1, csv.length, csv[0].length).setValues(csv);
DriveApp.getFileById(ss.getId()).setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
return ContentService.createTextOutput(ss.getUrl());
}
3. Deploy Web Apps.
The detailed information can be seen at the official document.
*
*On the script editor, at the top right of the script editor, please click "click Deploy" -> "New deployment".
*Please click "Select type" -> "Web App".
*Please input the information about the Web App in the fields under "Deployment configuration".
*Please select "Me" for "Execute as".
*
*This is the importance of this workaround.
*Please select "Anyone" for "Who has access".
*
*In this case, the user is not required to use the access token. So please use this as a test case.
*Of course, you can also access to your Web Apps using the access token. Please check this report.
*Please click "Deploy" button.
*Copy the URL of the Web App. It's like https://script.google.com/macros/s/###/exec.
*
*When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.
*You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".
4. Testing.
As the test of this Web Apps, I modified your script as follows. Before you use this script, please set the URL of your Web Apps to url. When you open this HTML and click the button, a new Spreadsheet including the text value in the textarea tab is opened with new window as the read-only.
<textarea id="sampletext" value="f">id,value
2,alpha
3,beta
14,test</textarea>
<button onclick="sample()">Open in Google Sheet</button>
<script>
function sample() {
const url = "https://script.google.com/macros/s/###/exec"; // Please set the URL of your Web Apps.
fetch(url, { method: "POST", body: document.getElementById("sampletext").value })
.then((res) => res.text())
.then((url) => window.open(url, "_blank"));
}
</script>
Note:
*
*When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.
*You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".
*My proposed script is a simple script. So please modify it for your actual situation.
References:
*
*Web Apps
*Taking advantage of Web Apps with Google Apps Script
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69465833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Audio players in Chrome packaged apps I'm trying to embed a music player in a Chrome app, and at the moment I'm using the default tag to embed music, but the problem is that I can't seek the song unless the song has been fully downloaded before playing (I'm streaming it from a file host).
The file host has its own music player, but is made in flash and so it doesn't work in Chrome apps. What should I do?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24101749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does knockout dataFor/contextFor work, exactly? Background:
When the equivalent of javascript blur happens, I want to be able to edit the selectedOptions bound to a select list through knockout. For instance, select a specific element from a list, or clear the selection.
I found this topic which suggests two methods of implementing the "blur" part.
I would prefer to use the solution offered by Chris Pratt, as the system involves a lot of generated code, and it is much simpler if I don't have to change the knockout portion of it. All of my attempts so far have been using Chris Pratt's solution.
In my javascript, I am getting a handle on the relevant DOM elements with no problems. However, I am having difficulties getting a handle on the selectedOptions koobservablearray which is bound to the select. When I call ko.dataFor(DOMobject), it seems to return functions which return regular javascript arrays which are copies of my koobservablearrays, meaning that I can't edit them in order to change which option is selected.
Question:
So, is it possible to achieve what I am trying to do from "outside" of knockout, using methods like ko.dataFor or ko.contextFor? How are these methods intended to work? What are they good for?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24173826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Replace() function with multiple values simultaneously recoded in r This is a very basic question, but I am using the replace() function to recode values that switch half-way through the years of reporting in my dataset. The key switches, so I am converting old character values to new ones.
Example: For the variable "animaltype": Old code, cat is reported as "CAT". New code, cat is reported as "CAT_unit"
I use the basic code:
animaltype = replace(animaltype, animaltype == "CAT", "CAT_unit")
within my dplyr piping to make sure all old responses of "CAT" and the new ones coded as "CAT_unit" are now both counted as "CAT_unit".
Individually, this works. However, I want to do this for other units. For example, I want to simultaneously convert all "DOG"s to "DOG_unit". Is there a way to do this within the same function/line of code. Or, do I need to create another replace function entirely?
I have seen using casewhen and ifelse as alternatives, but for convenience it would be ideal to use the replace function within my dplyr piping. I particularly want to avoid casewhen to avoid the conversion of other unspecified values to NAs, because I only have to recode certain units and retain the majority as is. Is this possible? Or would I have to recode them all individually? What is the most succinct way to do this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72969299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Querying MongoDB, List all unique using GROUP BY and INNER JOIN in the same query I'm doing a college job, but I'm not able to do these queries in the MongoDB database, I'll put the database links right down here for those who are kind enough to test, because I'm not getting it.
Question: List all unique employees’ last and first names (using GROUP BY method) that have a current salary (i.e. to_date equals to 9999-01-01) greater than 90000, outputting both names in descending order (sort by the last name first and then the first name) and also displaying their current salaries (using the INNER JOIN method).
I have tried some SQL conversions on Studio 3T, but I do not know what is wrong:
SELECT employees.emp_id, employees.first_name, employees.last_name, salaries.salary FROM employees
INNER JOIN salaries ON employees.emp_id = salaries.emp_id
WHERE to_date=9999-01-01 and salary > 90000
GROUP BY employees.emp_id
Some Data Employees:
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacf6"),
"birth_date" : "1953-09-02",
"emp_id" : NumberInt(10001),
"first_name" : "Georgi",
"gender" : "M",
"hire_date" : "1986-06-26",
"last_name" : "Facello",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacf7"),
"birth_date" : "1964-06-02",
"emp_id" : NumberInt(10002),
"first_name" : "Bezalel",
"gender" : "F",
"hire_date" : "1985-11-21",
"last_name" : "Simmel",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacf8"),
"birth_date" : "1959-12-03",
"emp_id" : NumberInt(10003),
"first_name" : "Parto",
"gender" : "M",
"hire_date" : "1986-08-28",
"last_name" : "Bamford",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacf9"),
"birth_date" : "1954-05-01",
"emp_id" : NumberInt(10004),
"first_name" : "Chirstian",
"gender" : "M",
"hire_date" : "1986-12-01",
"last_name" : "Koblick",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacfa"),
"birth_date" : "1955-01-21",
"emp_id" : NumberInt(10005),
"first_name" : "Kyoichi",
"gender" : "M",
"hire_date" : "1989-09-12",
"last_name" : "Maliniak",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacfb"),
"birth_date" : "1953-04-20",
"emp_id" : NumberInt(10006),
"first_name" : "Anneke",
"gender" : "F",
"hire_date" : "1989-06-02",
"last_name" : "Preusig",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacfc"),
"birth_date" : "1957-05-23",
"emp_id" : NumberInt(10007),
"first_name" : "Tzvetan",
"gender" : "F",
"hire_date" : "1989-02-10",
"last_name" : "Zielinski",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacfd"),
"birth_date" : "1958-02-19",
"emp_id" : NumberInt(10008),
"first_name" : "Saniya",
"gender" : "M",
"hire_date" : "1994-09-15",
"last_name" : "Kalloufi",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacfe"),
"birth_date" : "1952-04-19",
"emp_id" : NumberInt(10009),
"first_name" : "Sumant",
"gender" : "F",
"hire_date" : "1985-02-18",
"last_name" : "Peac",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dacff"),
"birth_date" : "1963-06-01",
"emp_id" : NumberInt(10010),
"first_name" : "Duangkaew",
"gender" : "F",
"hire_date" : "1989-08-24",
"last_name" : "Piveteau",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dad00"),
"birth_date" : "1953-11-07",
"emp_id" : NumberInt(10011),
"first_name" : "Mary",
"gender" : "F",
"hire_date" : "1990-01-22",
"last_name" : "Sluis",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dad01"),
"birth_date" : "1960-10-04",
"emp_id" : NumberInt(10012),
"first_name" : "Patricio",
"gender" : "M",
"hire_date" : "1992-12-18",
"last_name" : "Bridgland",
"email_address" : "[email protected]"
}
{
"_id" : ObjectId("5fc157d9ba1b05372b2dad02"),
"birth_date" : "1963-06-07",
"emp_id" : NumberInt(10013),
"first_name" : "Eberhardt",
"gender" : "M",
"hire_date" : "1985-10-20",
"last_name" : "Terkki",
"email_address" : "[email protected]"
}
Some Salaries data:
{
"_id" : ObjectId("5fc157daba1b05372b2db050"),
"emp_id" : NumberInt(10001),
"from_date" : "1986-06-26",
"salary" : NumberInt(60117),
"to_date" : "1987-06-26"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db052"),
"emp_id" : NumberInt(10001),
"from_date" : "1987-06-26",
"salary" : NumberInt(62102),
"to_date" : "1988-06-25"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db054"),
"emp_id" : NumberInt(10001),
"from_date" : "1988-06-25",
"salary" : NumberInt(66074),
"to_date" : "1989-06-25"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db056"),
"emp_id" : NumberInt(10001),
"from_date" : "1989-06-25",
"salary" : NumberInt(66596),
"to_date" : "1990-06-25"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db058"),
"emp_id" : NumberInt(10001),
"from_date" : "1990-06-25",
"salary" : NumberInt(66961),
"to_date" : "1991-06-25"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db059"),
"emp_id" : NumberInt(10001),
"from_date" : "1991-06-25",
"salary" : NumberInt(71046),
"to_date" : "1992-06-24"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db05b"),
"emp_id" : NumberInt(10001),
"from_date" : "1992-06-24",
"salary" : NumberInt(74333),
"to_date" : "1993-06-24"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db05d"),
"emp_id" : NumberInt(10001),
"from_date" : "1993-06-24",
"salary" : NumberInt(75286),
"to_date" : "1994-06-24"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db05f"),
"emp_id" : NumberInt(10001),
"from_date" : "1994-06-24",
"salary" : NumberInt(75994),
"to_date" : "1995-06-24"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db062"),
"emp_id" : NumberInt(10001),
"from_date" : "1995-06-24",
"salary" : NumberInt(76884),
"to_date" : "1996-06-23"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db064"),
"emp_id" : NumberInt(10001),
"from_date" : "1996-06-23",
"salary" : NumberInt(80013),
"to_date" : "1997-06-23"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db066"),
"emp_id" : NumberInt(10001),
"from_date" : "1997-06-23",
"salary" : NumberInt(81025),
"to_date" : "1998-06-23"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db068"),
"emp_id" : NumberInt(10001),
"from_date" : "1998-06-23",
"salary" : NumberInt(81097),
"to_date" : "1999-06-23"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db06a"),
"emp_id" : NumberInt(10001),
"from_date" : "1999-06-23",
"salary" : NumberInt(84917),
"to_date" : "2000-06-22"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db06c"),
"emp_id" : NumberInt(10001),
"from_date" : "2000-06-22",
"salary" : NumberInt(85112),
"to_date" : "2001-06-22"
}
{
"_id" : ObjectId("5fc157daba1b05372b2db06e"),
"emp_id" : NumberInt(10001),
"from_date" : "2001-06-22",
"salary" : NumberInt(85097),
"to_date" : "2002-06-22"
}
Employees table image
Salaries table image
MongoDbDump BSON files: employees.agz
Employees sample database (created by Fusheng Wang and Carlo Zaniolo
at Siemens Corporate Research)
Thanks
A: You can do with $project and $lookup.
*
*$project to include or exclude the fields $project
*$lookup to join collections. Here I have used uncorrelated-sub-queries. But there is a standard $lookup too
Here is the code
db.Employees.aggregate([
{
"$project": {
_id: 1,
emp_id: 1,
first_name: 1,
last_name: 1
}
},
{
"$lookup": {
"from": "Salaries",
let: { eId: "$emp_id" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: [ "$$eId", "$emp_id" ] },
{ $gt: [ "$salary", 80000 ] },
{ $eq: [ "$to_date", "2002-06-22" ] }
]
}
}
}
],
"as": "salary"
}
}
])
Working Mongo playground
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65192521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why doesn't 100vh fill whole page? I'm currently using React and I'm having issues getting a div to equal 100% of the height of the page. Originally, I had an issue with there always being about 24px of empty space above the body. I couldn't fit it no matter what. I eventually used this on my app.css (a reset)
* {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
It fixed the issue, but still, a measurement of 100% or 100vh doesn't actually equal 100% of the total view. Here's a screenshot of the page:
https://gyazo.com/3407b6bd0032f402f3bb97acdb725e40
The blue div is a div that fills 100vh. Yet, it doesn't fully fill the page. I tried 100% as well.
Blue div:
.loginWrapper {
margin-left: 260px;
height: 100vh;
background-color: #29B6F6;
}
I noticed that the html had this styling on it, yet even when removed no changes were noticeable:
html {
box-sizing: border-box;
}
If someone could please explain this phenomenon, I would be very grateful. If you need any extra information, just let me know. Thanks!
A: You will have to reset the basics margin and padding if applied from html and other top level tags.
body, html {margin: 0;padding: 0;}
Or just use something like reset.css
http://meyerweb.com/eric/tools/css/reset/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41421224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JDA cant find the gateway intents class I have built my jda discord to a jar file and it raises the class not found error for the gateway intents class saying that its not found or this error specifically
Exception in thread "main" java.lang.NoClassDefFoundError: net/dv8tion/jda/api/requests/GatewayIntent
at banos.bot.Main.main(Main.java:14)
Caused by: java.lang.ClassNotFoundException: net.dv8tion.jda.api.requests.GatewayIntent
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
... 1 more
Edit: Here is my build.gradle if that helps.
plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version "7.1.0"
id 'application'
}
group 'banos.bot'
version '1.1.0-SNAPSHOT'
ext {
javaMainClass = "banos.bot.Main"
}
application {
mainClass = 'banos.bot.Main'
}
repositories {
mavenCentral()
maven {
name 'm2-dv8tion'
url 'https://m2.dv8tion.net/releases'
}
maven {
name 'duncte123-jfrog'
url 'https://duncte123.jfrog.io/artifactory/maven'
}}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2'
implementation group: 'net.dv8tion', name: 'JDA', version: '4.3.0_324'
implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'
implementation group: 'me.duncte123', name: 'botCommons', version: '2.3.9'
}
test {
useJUnitPlatform()
}
jar {
manifest {
attributes 'Main-Class': 'banos.bot.Main', 'Class-Path': './build/libs/Banos_Bot-1.1.0-SNAPSHOT.jar'
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70717490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using jQuery to set multiple selects using each I have a page full of selects, and they all have a common class. I need to set every one of them to their first option. Easy, right? But what I finally wound up getting to work feels like such a hack... is there a better way?
$('.myclass').each(function() {
var firstOptSelector = '#' + $(this).attr('id') + ' option:first'; // HACK
$(firstOptSelector).attr('selected','selected');
});
A: Try like below,
$('.myclass').each(function() {
this.selectedIndex = 0;
});
DEMO: http://jsfiddle.net/ZDYjP/
A: How about this short one?
$(".myclass :first-child").prop("selected", true);
DEMO: http://jsfiddle.net/u8S54/
A: Do it like this:
$('.myclass').each(function() {
$(this).find('option:first').attr('selected','selected');
});
A: You don't need to use each. Here's an example.
$('.select').find('option:first').prop('selected', true );
A: $("option:first", ".myselect").prop('selected', true);
Working sample
A: If you remove the selected property then the first one by default is what is shown.
$('.myclass').find('option:selected').removeAttr("selected");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10854638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to record error messages when mapping a shared server to a network drive with VBS? The following snippet of script maps shared servers, stored as strings ( "\server\shared" ), in an array to the (A:) drive and record any errors encountered during the process. Then removes it to map the following item.
When some drives are mapped, depending on the user's administrative privileges, it may display an "access is denied" error message.
How can I write that message to a file in case it occurs.
Set objNetwork = WScript.CreateObject("WScript.Network")
' loop through array and write shared servers to reult excel sheet
For Each item in arrServerValues
Echo item
objNetWork.MapNetworkDrive "A:", item
' record potential error message to a result file: Results.txt
objNetWork.RemoveNetworkDrive "A:"
Next
A: Learn about the following:
*
*On Error statement: to catch the error
*Err object: to grab the error message
*File operations (File System Object): to write to a file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35951669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Character Repetition I am writing a simple program to calculate the repetition of characters in a string sequence. The program I have for now is as below, but I am looking to see if it can be optimized any further. I believe the program right now is O(n) worst case time and I would like to see if there is something that can give me O(log n) running time.
using System;
using System.Collections.Generic;
namespace Algos
{
class CharacterRepitition
{
private char[] checkStringArray;
private bool[] discovered;
public CharacterRepitition(string toCheck)
{
checkStringArray= toCheck.ToCharArray();
discovered= new bool[checkStringArray.Length];
for (int i = 0; i < checkStringArray.Length; i++)
{
discovered[i] = false;
}
}
public void CheckRepetitions()
{
int charIndex=0;
Dictionary<char, int> repetitions = new Dictionary<char, int>();
while (charIndex < checkStringArray.Length)
{
int count = 0;
if(discovered[charIndex].Equals(false))
{
count = RunThroughTheString(charIndex, checkStringArray);
if (count > 0)
{
repetitions.Add(checkStringArray[charIndex], count+1);
}
}
charIndex++;
}
if (repetitions.Count == 0)
{
Console.WriteLine("\nNo characters repeated.");
}
else
{
foreach (KeyValuePair<char, int> result in repetitions)
{
Console.WriteLine("\n'"+ result.Key + "' is present: " + result.Value + " times.");
}
}
}
private int RunThroughTheString(int currentCharIndex, char[] checkStringArray)
{
int counter = 0;
for (int i = 0; i < checkStringArray.Length; i++)
{
if (checkStringArray[currentCharIndex].Equals(checkStringArray[i]) && i !=currentCharIndex)
{
counter++;
discovered[i] = true;
}
}
return counter;
}
}
}
I know i can achieve this with LINQ as well. But that is not something I am looking for. Appreciate your help.
A: Not sure if I read the question correctly, but would this work in you situation
public void FindCharRepetitions(string toCheck)
{
var result = new Dictionary<char, int>();
foreach (var chr in toCheck)
{
if (result.ContainsKey(chr))
{
result[chr]++;
continue;
}
result.Add(chr, 1);
}
foreach (var item in result)
{
Console.WriteLine("Char: {0}, Count: {1}", item.Key, item.Value);
}
}
A: If the number of different characters is known (say only A-Z) then the code could be like this:
int[] counters = new int['Z' - 'A' + 1];
foreach(char c in toCheck)
if (c >= 'A' && c <= 'Z')
counters[c - 'A']++;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14915626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Could someone explain the regex /(.*)\.(.*)/? I want to get the file extension in Groovy with a regex, for let's say South.6987556.Input.csv.cop.
http://www.regexplanet.com/advanced/java/index.html shows me that the second group would really contain the cop extension. Which is what I want.
0: [0,27] South.6987556.Input.csv.cop
1: [0,23] South.6987556.Input.csv
2: [24,27] cop
I just don't understand why the result won't be
0: [0,27] South.6987556.Input.csv.cop
1: [0,23] South
2: [24,27] 6987556.Input.csv.cop
What should be the regex to get this kind of result?
A: To get the desired output, your regex should be:
((.*?)\.(.*))
DEMO
See the captured groups at right bottom of the DEMO site.
Explanation:
( group and capture to \1:
( group and capture to \2:
.*? any character except \n (0 or more
times) ? after * makes the regex engine
to does a non-greedy match(shortest possible match).
) end of \2
\. '.'
( group and capture to \3:
.* any character except \n (0 or more
times)
) end of \3
) end of \1
A: Here is a visualization of this regex
(.*)\.(.*)
Debuggex Demo
in words
*
*(.*) matches anything als large as possible and references it
*\. matches one period, no reference (no brackets)
*(.*) matches anything again, may be empty, and references it
in your case this is
*
*(.*) : South.6987556.Input.csv
*\. : .
*(.*) : cop
it isn't just only South and 6987556.Input.csv.cop because the first part (.*) isn't optional but greedy and must be followed by a period, so the engine tries to match the largest possible string.
Your intended result would be created by this regex: (.*?)\.(.*). The ? after a quantifier (in this case *) switches the behaviour of the engine to ungreedy, so the smallest matching string will be searched. By default most regex engines are greedy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24989252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Form submit function seems to only change a value for a split second I have a list that changes value according to gold and silver spot prices. So having the ability to edit these always changing spot prices is crucial but i can't seem to get my form submit button to do anything permanently.
HTML
<form>
Silver Spot: <input type="text" name="fname" id="silverSpotPrice"><br>
Gold Spot: <input type="text" name="lname" id="goldSpotPrice"><br>
<button class ="submit" onclick="submitSpots()">SUBMIT</button>
</form>
Javascript function the form button submits too (variables are called at begining of the javascript form)
function submitSpots(){
silverSpot = document.getElementById("silverSpotPrice").value;
document.getElementById('silverSpot').innerHTML = silverSpot;
goldSpot = document.getElementById("goldSpotPrice").value;
document.getElementById('goldSpot').innerHTML = goldSpot;
}
the function does change the form for a split second when I click it rapidly, but always goes back to the original HTML side preset.
<th>Spot</th>
<td><span id="silverSpot">SilverSpot</span></td>
<td><span id="goldSpot">GoldSpot</span></td>
</tr>
I.E. the silverSpot and goldSpot spots go back to "SilverSpot" and "GoldSpot". after showing another piece of text for only a split second.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42425657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Making strings equal when compared to public class StringEqual
{
public static void main(String[] args)
{
String str1 = "abcd";
String str2 = "abcdefg";
String str3 = str1 + "efg";
System.out.println("str2 = " + str2);
System.out.println("str3 = " + str3);
if (str2 == str3)
{
System.out.println("The strings are equal");
}
else
{
System.out.println("The strings are not equal");
}
}
}
so far i've created this code. Now i am trying to figure out how do i make it so that str2 and str3 are equal when they are compared?
A: If you ant compare strings you have to use equals method:
if (str2.equals(str3))
A: == compares the Object Reference
String#equals compares the content
So replace str2==str3 with
String str2 = "abcdefg";
String str3 = str1 + "efg";
str2.equals(str2); // will return true
A: You know, you need to differentiate between string equality and object idendity. The other answers already told you that it would work with .equals().
But if you actually asking on how to get the same object by your string expressions: if it is a compile time constant expression it will be the same object. The str3 would come from the constant pool if it is a constant expression, and in order for that, you may only use final string variables or string literals:
public class FinalString
{
final static String fab = "ab";
static String ab = "ab";
static String abc = "abc";
static String nonfin = ab + "c"; // nonfinal+literal
static String fin = fab + "c"; // final+literal
public static void main(String[] args)
{
System.out.println(" nonfin: " + (nonfin == abc));
System.out.println(" final: " + (fin == abc));
System.out.println(" equals? " + fin.equals(nonfin));
}
}
prints
nonfin: false
final: true
equals? true
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28520138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Represent a Mixture with a Django Model I'm trying to represent a mixture in Django. Something like:
Chemical #1 - 50%
Chemical #2 - 30%
Chemical #3 - 20%
I figured I would use a wrapper called composition as follows:
class Composition(models.Model):
""" Just a Wrapper """
def save(...):
#Validate ingredients add up to 100% and such
class Ingredient(models.Model):
composition = models.ForeignKey('Composition',related_name='ingredients')
name = models.CharField(max_length = 10)
percentage = models.IntegerField()
I'm pretty sure there's a better way to do this. Keep in mind that I'm doing it like this so I can later use inlines in the Django admin. What do you guys recommend? Thanks a lot =)
A: It seems to me as though it would be preferable to keep a list of ingredients then reference those when you create your compositions, rather than entering the ingredient names each time. You could do it using a many to many relationship and a through table, like so:
class Ingredient(models.Model):
name = models.CharField(max_length=10)
class Composition(models.Model):
name = models.CharField(max_length=255)
ingredients = models.ManyToManyField(Ingredient, through='CompositionIngredient')
def save(...):
#Validate ingredients add up to 100% and such
class CompositionIngredient(models.Model):
composition = models.ForeignKey(Composition)
ingredient = models.ForeignKey(Ingredient)
proportion = models.DecimalField()
See the Django docs for more information.
EDIT: Here's the documentation on how to deal with through tables in the admin interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8235055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: STL-Like range, What could go wrong if I did this? I am writing (as a self-teaching exercise) a simple STL-Like range. It is an Immutable-Random-Access "container". My range, keeps only the its start element, the the number of elements and the step size(the difference between two consecutive elements):
struct range
{
...
private:
value_type m_first_element, m_element_count, m_step;
};
Because my range doesn't hold the elements, it calculates the desired element using the following:
// In the standards, the operator[]
// should return a const reference.
// Because Range doesn't store its elements
// internally, we return a copy of the value.
value_type operator[](size_type index)
{
return m_first_element + m_step*index;
}
As you can see, I am not returning a const reference as the standards say. Now, can I assume that a const reference and a copy of the element are the same in terms of using the non-mutating algorithms in the standard library?
Any advice about the subject is greatly appreciated.
@Steve Jessop: Good point that you mentioned iterators.
Actually, I used sgi as my reference. At the end of that page, it says:
Assuming x and y are iterators from the same range:
Invariants Identity
x == y if and only if &*x == &*y
So, it boils down to the same original question I've asked actually :)
A: Items in STL containers are expected to be copied around all the time; think about when a vector has to be reallocated, for example. So, your example is fine, except that it only works with random iterators. But I suspect the latter is probably by design. :-P
A: Do you want your range to be usable in STL algorithms? Wouldn't it be better off with the first and last elements? (Considering the fact that end() is oft required/used, you will have to pre-calculate it for performance.) Or, are you counting on the contiguous elements (which is my second point)?
A: The standard algorithms don't really use operator[], they're all defined in terms of iterators unless I've forgotten something significant. Is the plan to re-implement the standard algorithms on top of operator[] for your "ranges", rather than iterators?
Where non-mutating algorithms do use iterators, they're all defined in terms of *it being assignable to whatever it needs to be assignable to, or otherwise valid for some specified operation or function call. I think all or most such ops are fine with a value.
The one thing I can think of, is that you can't pass a value where a non-const reference is expected. Are there any non-mutating algorithms which require a non-const reference? Probably not, provided that any functor parameters etc. have enough const in them.
So sorry, I can't say definitively that there are no odd corners that go wrong, but it sounds basically OK to me. Even if there are any niggles, you may be able to fix them with very slight differences in the requirements between your versions of the algorithms and the standard ones.
Edit: a second thing that could go wrong is taking pointers/references and keeping them too long. As far as I can remember, standard algorithms don't keep pointers or references to elements - the reason for this is that it's containers which guarantee the validity of pointers to elements, iterator types only tell you when the iterator remains valid (for instance a copy of an input iterator doesn't necessarily remain valid when the original is incremented, whereas forward iterators can be copied in this way for multi-pass algorithms). Since the algorithms don't see containers, only iterators, they have no reason that I can think of to be assuming the elements are persistent.
A: Since you put "container" in "quotes" you can do whatever you want.
STL type things (iterators, various member functions on containers..) return references because references are lvalues, and certain constructs (ie, myvec[i] = otherthing) can compile then. Think of operator[] on std::map. For const references, it's not a value just to avoid the copy, I suppose.
This rule is violated all the time though, when convenient. It's also common to have iterator classes store the current value in a member variable purely for the purpose of returning a reference or const reference (yes, this reference would be invalid if the iterator is advanced).
If you're interested in this sort of stuff you should check out the boost iterator library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2170064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Enable SSL on tomcat on Docker I have local docker running up on my linux system. I'm trying to enable SSL on the docker container which runs tomcat. However I'm unable to get the SSL working.
I get the below error when I try to access the REST endpoint deployed locally on docker.
Aug 13, 2018 5:36:25 AM org.apache.coyote.http11.AbstractHttp11Processor process
INFO: Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
I have added the below code to the server.xml:
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="/usr/java/default/lib/security/***.cert.p12" keystoreType="PKCS12" keystorePass="***" />
The same piece of code works fine when I try to deploy my java application on my local tomcat without docker.
Why is the same thing not working in tomcat on docker?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51825162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: npm local prefix always set to current working directory I've been searching for a while to try to find the answer to this. I've tried everything I've found that makes sense and more. Nothing has worked. Here's the breakdown:
*
*I'm on linux (12.3-RELEASE FreeBSD 12.3-RELEASE r371270 NFSN64 amd64)
*I've installed a package called hexo-cli using npm.
*My home directory is /home/private
*My global npm install directory is /home/private/.npm-global
*My npm prefix -g location is: /home/private/.npm-global
*When my cwd is /home/public/ and I execute hexo, hexo runs
*hexo then fails to find itself because it's using the npm prefix (this is my guess)
*When I type npm prefix it always returns my cwd
*I have checked /home/private/.npmrc file. A grep "prefix" /home/private/.npmrc returns:
*prefix=/home/private/.npm-global
*There are no other lines or entries returned from the grep
*npm config set prefix=/home/private/.npm-global only modifies the global prefix, not my local prefix
How do I get my local prefix var to be /home/private/.npm-global?
Edit:
Here is the output of my terminal when running hexo:
[username /home/public]$ hexo
ERROR Cannot find module 'hexo' from '/home/public'
ERROR Local hexo loading failed in /home/public
ERROR Try running: 'rm -rf node_modules && npm install --force'
Edit #2:
Forgot to mention. I also tried adding the following two lines to my ~/.profile file:
export PATH=~/.npm-global/bin:$PATH
export PATH=~/.npm-global/lib/node_modules:$PATH
I would then source ~/.profile.
This made absolutely no difference.
Edit #3:
Fixed a path in the 6th bullet point.
Edit #4
This is the output of my npm config list:
[username /home/public]$ npm config list
; "user" config from /home/private/.npmrc
prefix = "/home/private/.npm-global"
; node bin location = /usr/local/bin/node
; node version = v16.16.0
; npm local prefix = /home/public
; npm version = 8.13.0
; cwd = /home/public
; HOME = /home/private/
; Run `npm config ls -l` to show all defaults.
Notice it says npm local prefix. Attempting to npm config set local prefix ... does not work. local prefix is not a variable you can assign a value to. I tried localprefix as well. This did not work.
A: I don't know what the problem was. However I've nuked everything from orbit and started over. I deleted everything except a single html file in my /home/public directory. I deleted /home/private/.npm-global. I recreated /home/private/.npm-global. I followed the steps listed in the answer to:
Global Node modules not installing correctly. Command not found
Specifically the steps provided by Vicente, posted Feb 9, 2019 at 16:30. Which were:
[username /home/public]$ mkdir /home/private/.npm-global
[username /home/public]$ npm config set prefix '~/.npm-global'
[username /home/public]$ export PATH=~/.npm-global/bin:$PATH
[username /home/public]$ source ~/.profile
[username /home/public]$ npm install -g hexo-cli
Then I tried to run from /home/public: hexo init blog
This command worked and it creates a blog directory in the cwd. However, then I tried to run hexo server from the same directory I was still in. This did not work. I changed directories to /home/public/blog/ and then typed hexo server. This still did not work and would only print out some help message about a few commands you could run.
Their website says this is generally due to a missing version line in the dependency of the blog/package.json file. I edited the file and added version 3.2.2, and then re-ran it as hexo --version. When I did this, it dumped out some Validating config output with a bunch of dependencies and their version numbers. The version number specified for hexo was hexo: 6.3.0. I went to open the blog/package.json file again to update the version from 3.2.2 to 6.3.0. However, hexo had already updated the file for me.
Then I typed hexo server while still in /home/public/blog and then the hexo server started up. It errored out with some NaN is not a valid date! error, but the server was still running.
In a separate terminal connected to the same machine and inside the /home/public/blog directory I typed hexo new "Hello Hexo". This worked. Then I typed hexo generate to generate the static files. This also worked.
Everything seems to be working now. Not sure what the problem was earlier. Would still like to know how to set the local prefix to a specific path though, if possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73834468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Work with and change the layout of an csv file in pandas I read a csv data with pandas and now I would like to change the layout of my dataset. My dataset from excel looks like this:
I run the code with df = pd.read_csv(Location2)
This is what I get:
I would like to have a separated column for time and Watt and their values.
I looked at the documentation but I couldn't find something to make it work.
A: Use read_excel
df = pd.read_excel(Location2)
A: It seems as if you'd need to set up the correct delimiter that separates the two fields. Try adding delimiter=";" to the parameters
A: I think you need parameter sep in read_csv, because default separator is ,:
df = pd.read_csv(Location2, sep=';')
Sample:
import pandas as pd
from pandas.compat import StringIO
temp=u"""time;Watt
0;00:00:00;50
1;01:00:00;45
2;02:00:00;40
3;00:03:00;35"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), sep=";")
print (df)
time Watt
0 00:00:00 50
1 01:00:00 45
2 02:00:00 40
3 00:03:00 35
Then is possible convert time column to_timedelta:
df['time'] = pd.to_timedelta(df['time'])
print (df)
time Watt
0 00:00:00 50
1 01:00:00 45
2 02:00:00 40
3 00:03:00 35
print (df.dtypes)
time timedelta64[ns]
Watt int64
dtype: object
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43756927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits