text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: JMeter - throughput I'd like to test 5 HTTP requests in a ThreadGroup. I need to define a different throughput rate for each, but cannot put them in separate groups, because I'd like to variate the number of threads for that particular group.
How can I achieve this?
A: I believe that Constant Throughput Timer is what you're looking for.
In regards to "separate groups" - you can set thread number as a property for, the same for all groups, and set this property during JMeter execution via jmeter.properties file or -J command line argument like:
Set "Number of Threads" in Thread Group to ${__P(virtual.users,)}
and launch JMeter as:
jmeter -Jvirtual.users=50 ... ... ...
Hope this all helps.
A: Little bit late but you can use in that way
cmd.exe /c jmeter.bat --nongui -JforcePerfmonFile=true --runremote
--testfile "performance.jmx"
--jmeterproperty "perf.properties"
in file perf.properties set:
virtual.users=50
and it will used 50 for your players.
Hope this all helps
A: Throughput Controller should be also a choice.
Thread Group
*
*Throughput Controller2: 98%
*Throughput Controller2: 2%
*
*Http Request1
*Http Request2
When Throughput Controller set percent 2%,
Here are run rate: Http Request1: 2% ,Http Request2: 2%.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21332158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to connect to Facebook Graph API from Python using Requests if I do not need user access token? I am trying to find the easiest way how to use Facebook Graph API using my favorite Requests library. The problem is, all examples I found are about getting user access token, about redirects and user interaction.
All I need is only application access token. I do not handle any non-public data, so I need no user interaction and as my final app is supposed to be command-line script, no redirects are desired.
I found something similar here, but it seems to be everything but elegant. Moreover, I would prefer something using Requests or Requests-OAuth2. Or maybe there is library for that? I found Requests-Facebook and Facepy (both Requests based), but again, all examples are with redirection, etc. Facepy does not handle authorization at all, it just accepts your token and it is up to you to get it somehow.
Could someone, please, provide a short, sane, working example how to get just the application access token?
A: Following https://developers.facebook.com/docs/technical-guides/opengraph/publishing-with-app-token/:
import requests
r = requests.get('https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=123&client_secret=XXX')
access_token = r.text.split('=')[1]
print access_token
(using the correct values for client_id and client_secret) gives me something that looks like an access token.
A: If you just need a quick/small request, you can manually cut and paste the access token from here into you code: https://developers.facebook.com/tools/explorer
Note: Unlike Richard Barnett's answer, you'll need to regenerate the code manually from the graph api explorer every time you use it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14611240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I add content before in extended page? (KID templates) I've got master.kid (simplified):
<html>
<head py:match="item.tag == 'head'">
<title>My Site</title>
</head>
<body py:match="item.tag == 'body'">
<h1>My Site</h1>
<div py:replace="item[:]"></div>
<p id="footer">Copyright Blixt 2010</p>
</body>
</html>
And mypage.kid:
<html>
<head></head>
<body>
<p>Hello World!</p>
</body>
</html>
Now I want it to be possible to add more content before the </body> tag in the resulting HTML, specific to mypage.kid.
Basically the result should be something this:
<html>
<head>
<title>My Site</title>
</head>
<body>
<h1>My Site</h1>
<p>Hello World!</p>
<p id="footer">Copyright Blixt 2010</p>
<script type="text/javascript">alert('Hello World!');</script>
</body>
</html>
The <script> tag should be specified in mypage.kid. It's okay if I have to modify master.kid to optionally support additional content before the </body> tag, but what the content is has to be specified in mypage.kid.
At first I figured adding an element before the </body> tag in master.kid with py:match="item.tag == 'bodyend'" would work. The problem is that it uses the position of the element in mypage.kid, and not the position of the element doing py:match. So if I put the <bodyend> tag before </body> in mypage.kid, it is imported before <p id="footer">, and if I put it below </body> it will stay there.
How do I set up master.kid and mypage.kid to support adding content immediately before the </body> tag?
A: The best solution I've found is the following:
master.kid:
<html>
<head py:match="item.tag == 'head'">
<title>My Site</title>
</head>
<body py:match="item.tag == 'body'">
<h1>My Site</h1>
<div py:replace="item[:]"></div>
<p id="footer">Copyright Blixt 2010</p>
<div py:if="defined('body_end')" py:replace="body_end()"></div>
</body>
</html>
mypage.kid:
<html>
<head></head>
<body>
<p>Hello World!</p>
<div py:def="body_end()" py:strip="True">
<script type="text/javascript">alert('Hello World!');</script>
</div>
</body>
</html>
The master.kid page checks for a variable defined as body_end, and if there is such a variable, it will call it, replacing the contents of the element before </body> (otherwise it will output nothing).
Any page that needs to output content before </body> will define the body_end function using py:def="body_end()". The py:strip="True" is there to remove the wrapping <div>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1999300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google Sheets Script "Exceeded maximum execution time" I'm having issues trying to deal with the "Exceeded maximum execution time" error I get when running my script in Google sheets. I've found a few solutions on here that I couldn't get working with my script. Any help would be greatly appreciated, here is the script I am trying to modify:
function getGeocodingRegion() {
return PropertiesService.getDocumentProperties().getProperty('GEOCODING_REGION') || 'au';
}
function addressToPosition() {
// Select a cell with an address and two blank spaces after it
var sheet = SpreadsheetApp.getActiveSheet();
var cells = sheet.getActiveRange();
var addressColumn = 1;
var addressRow;
var latColumn = addressColumn + 1;
var lngColumn = addressColumn + 2;
var API_KEY = "xxx";
var options = {
muteHttpExceptions: true,
contentType: "application/json",
};
for (addressRow = 1; addressRow <= cells.getNumRows(); ++addressRow) {
var address = cells.getCell(addressRow, addressColumn).getValue();
var serviceUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + API_KEY;
// Logger.log(address);
// Logger.log(serviceUrl);
var response = UrlFetchApp.fetch(serviceUrl, options);
if (response.getResponseCode() == 200) {
var location = JSON.parse(response.getContentText());
// Logger.log(response.getContentText());
if (location["status"] == "OK") {
//return coordinates;
var lat = location["results"][0]["geometry"]["location"]["lat"];
var lng = location["results"][0]["geometry"]["location"]["lng"];
cells.getCell(addressRow, latColumn).setValue(lat);
cells.getCell(addressRow, lngColumn).setValue(lng);
}
}
}
};
function positionToAddress() {
var sheet = SpreadsheetApp.getActiveSheet();
var cells = sheet.getActiveRange();
// Must have selected 3 columns (Address, Lat, Lng).
// Must have selected at least 1 row.
if (cells.getNumColumns() != 3) {
Logger.log("Must select at least 3 columns: Address, Lat, Lng columns.");
return;
}
var addressColumn = 1;
var addressRow;
var latColumn = addressColumn + 1;
var lngColumn = addressColumn + 2;
//Maps.setAuthentication("acqa-test1", "AIzaSyBzNCaW2AQCCfpfJzkYZiQR8NHbHnRGDRg");
var geocoder = Maps.newGeocoder().setRegion(getGeocodingRegion());
var location;
for (addressRow = 1; addressRow <= cells.getNumRows(); ++addressRow) {
var lat = cells.getCell(addressRow, latColumn).getValue();
var lng = cells.getCell(addressRow, lngColumn).getValue();
// Geocode the lat, lng pair to an address.
location = geocoder.reverseGeocode(lat, lng);
// Only change cells if geocoder seems to have gotten a
// valid response.
Logger.log(location.status);
if (location.status == 'OK') {
var address = location["results"][0]["formatted_address"];
cells.getCell(addressRow, addressColumn).setValue(address);
}
}
};
function generateMenu() {
var entries = [{
name: "Geocode Selected Cells (Address to Lat, Long)",
functionName: "addressToPosition"
}, {
name: "Geocode Selected Cells (Address from Lat, Long)",
functionName: "positionToAddress"
}];
return entries;
}
function updateMenu() {
SpreadsheetApp.getActiveSpreadsheet().updateMenu('Geocode', generateMenu())
};
/**
* Adds a custom menu to the active spreadsheet, containing a single menu item
* for invoking the readRows() function specified above.
* The onOpen() function, when defined, is automatically invoked whenever the
* spreadsheet is opened.
*
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
*/
function onOpen() {
SpreadsheetApp.getActiveSpreadsheet().addMenu('Geocode', generateMenu());
};
Or, any other script you may know of that does geocode in Google sheets and already properly handles max execution time that would be OK too, I'm not tied to this specific script, just getting the outcome I need!
A: This error's cause is due to script running more than 6 minutes.
A possible solution is to limit the time-consuming part of your script (which is the for loop) to only 5 minutes. Then create a trigger and continue the loop into another instance if it still isn't done.
Script:
function addressToPosition() {
// Select a cell with an address and two blank spaces after it
var sheet = SpreadsheetApp.getActiveSheet();
...
var options = {
muteHttpExceptions: true,
contentType: "application/json",
};
// if lastRow is set, get value, else 0
var continueRow = ScriptProperties.getProperty("lastRow") || 0;
var startTime = Date.now();
var resume = true;
for (addressRow = ++continueRow; addressRow <= cells.getNumRows(); ++addressRow) {
var address = cells.getCell(addressRow, addressColumn).getValue();
...
// if 5 minutes is done
if ((Date.now() - startTime) >= 300000) {
// save what's the last row you processed then exit loop
ScriptProperties.setProperty("lastRow", addressRow)
break;
}
// if you reached last row, assign flag as false to prevent triggering the next run
else if (addressRow == cells.getNumRows())
resume = false;
}
// if addressRow is less than getNumRows()
if (resume) {
// after execution of loop, prepare the trigger for the same function
var next = ScriptApp.newTrigger("addressToPosition").timeBased();
// run script after 1 second to continue where you left off (on another instance)
next.after(1000).create();
}
}
Do the same thing with your other functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69121700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Count items of json string in SQL script (compatibility version 100, no openjson) My Json string has couple of items and I can use json_value to get specific items and parse it. But need to know the length of items to iterate.
[
{"name":"Ram", "email":"[email protected]"},
{"name":"David", "email":"[email protected]"},
{"name":"Bob", "email":"[email protected]"}
]
For example JSON_VALUE(@myJsonString, N'$[1].email') returns [email protected] but I need to know the length to increment.
Am I doomed to use openjson?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63271121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alfresco connector error I'm trying to do a connector to get a file. I receive the path of the file by args like :
var filePath = args["file"]
If I print this, I get the path correctly. But in the connector I have:
var connector = remote.connect("alfresco");
result = connector.get(args["file"])
and if I made this, this not recognise the path, the status is Error 500. I print the path and I paste like:
result = connector.get("/slingshot/node/content/workspace/SpacesStore/f32afa20-4c73-4e6c-84e4-1c12d5964a95/txt.txt")
... But obvious, I want by args because I want for all the files.
What is my error? This is so strange for me.
A: For future users that which may have the same problem, my problem was that args send the path with "" like "http://something" and if we put get("/slingshot/node/content/workspace/SpacesStore/f32afa20-4c73-4e6c-84e4-1c12d5964a95/txt.txt") don't have "". So, we can put the args on the string and make string.substring(1,string.length-1) to delete "".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33526370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: BitmapFactory.decodeResource() returns null for shape defined in xml drawable I looked through multiple similar questions, although I haven't found a proper answer to my issue.
I have a drawable, defined in shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@color/bg_color" />
</shape>
I want to convert it to Bitmap object in order to perform some operations, but BitmapFactory.decodeResource() returns null.
This is how I'm doing it:
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.shape);
What am I doing wrong? Is BitmapFactory.decodeResource() applicable for xml defined drawables?
A: Android KTX now has an extension function for converting drawable to bitmap
val bitmap = ContextCompat.getDrawable(context, R.drawable.ic_user_location_pin)?.toBitmap()
if (bitmap != null) {
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
}
A: public static Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Integer width, Integer height) {
Drawable d = getResources().getDrawable(drawableId);
if (d instanceof BitmapDrawable) {
return ((BitmapDrawable) d).getBitmap();
}
if (d instanceof GradientDrawable) {
GradientDrawable g = (GradientDrawable) d;
int w = d.getIntrinsicWidth() > 0 ? d.getIntrinsicWidth() : width;
int h = d.getIntrinsicHeight() > 0 ? d.getIntrinsicHeight() : height;
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
g.setBounds(0, 0, w, h);
g.setStroke(1, Color.BLACK);
g.setFilterBitmap(true);
g.draw(canvas);
return bitmap;
}
Bitmap bit = BitmapFactory.decodeResource(getResources(), drawableId);
return bit.copy(Bitmap.Config.ARGB_8888, true);
}
//------------------------
Bitmap b = convertDrawableResToBitmap(R.drawable.myDraw , 50, 50);
A: Since you want to load a Drawable, not a Bitmap, use this:
Drawable d = getResources().getDrawable(R.drawable.your_drawable, your_app_theme);
To turn it into a Bitmap:
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
Taken from: How to convert a Drawable to a Bitmap?
A: it is a drawable, not a bitmap. You should use getDrawable instead
A: You may have put .xml into directory:.../drawable-24, and try to put it into .../drawable instead.
it works for me, hope this can help someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24389043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "55"
} |
Q: Optimize a query with a three-way JOIN I have the following query what is the suggests to make it better and how to avoid null values.
SELECT stream.id AS status_id,
members.username,
members.membership_type,
members.first_name,
members.last_name,
stream.member_id,
stream.url_preview,
stream.media,
stream.images,
stream.poll_id,
stream.status_type,
stream.created_at,
stream.activity_text,
stream.original_id,
stream.shared_from
FROM stream, follow, members
WHERE follow.follower_id = 239
AND stream.member_id = members.id
AND (stream.member_id=follow.follower_id OR stream.member_id=follow.member_id)
AND stream.type = 2
AND stream.status_type NOT IN (4, 5, 7, 8, 9, 10, 11)
GROUP BY stream.id
ORDER BY stream.id DESC
LIMIT ' . $offset . ', 10;
+----+-------------+---------+--------+-----------------------+-------------+---------+-------------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+--------+-----------------------+-------------+---------+-------------------------+------+-------------+
| 1 | SIMPLE | stream | index | member_id | PRIMARY | 4 | NULL | 1 | Using where |
| 1 | SIMPLE | members | eq_ref | PRIMARY | PRIMARY | 4 | portal.stream.member_id | 1 | |
| 1 | SIMPLE | follow | ref | follower_id,member_id | follower_id | 4 | const | 14 | Using where |
+----+-------------+---------+--------+-----------------------+-------------+---------+-------------------------+------+-------------+
A: Yes its quite obvious that you are using old style of joining, still if you need to avoid NULL value to show on data then you can use IFNULL() function for avoiding NULL.
Example :-
select ifnull(members.username,'this is null part') as username from table_name;
This query will print the null part ,if the username is null either it will print the username only.
You can apply to your all column when you are fetching the column data in your query.
Hope it will help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22568189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Record (get) mouse click position while key is pressed and stop recording when same key is released in python I am creating a script where if user press f7 it will start recording mouse clicks and when he releases the button it should stop and this happens unless user closes the program.
The script is printing "None" inspite of pressing f7 and instead of showing click position and "f7", it is showing None.
In on_press function when we print the value, it is showing "f7" but when clicking the mouse button in on_click function, it is showing "None"
Here is the code
from pynput import mouse, keyboard
from pynput.keyboard import Key, Listener
import pickle
x_pos = []
y_pos = []
both_pos = []
pressed_key = None
def on_press(key):
if (key==keyboard.Key.f7):
pressed_key = "f7"
else:
pressed_key = None
def on_release(key):
pass
def on_click(x, y, button, pressed):
if pressed:
#print ("{0} {1}".format(x,y))
print(pressed_key)
if pressed_key == "f7":
x_pos.append("{0}".format(x,y))
y_pos.append("{1}".format(x,y))
#print("test" + x_pos + y_pos)
print (x_pos + y_pos)
#both_pos = x_pos, y_pos
else:
pass
print (x_pos + y_pos)
mouse_listener = mouse.Listener(on_click=on_click)
mouse_listener.start()
with keyboard.Listener(on_press = on_press, on_release = on_release) as listener:
try:
#listener.start()
listener.join()
except MyException as e:
print('Done'.format(e.args[0]))
A: Found the issue. Because in on_press i was not using global pressed_key so it was creating local variable.
Here is the working code.
from pynput import mouse, keyboard
from pynput.keyboard import Key, Listener
import pickle
x_pos = []
y_pos = []
both_pos = []
pressed_key = None
def on_press(key):
global pressed_key
if (key==keyboard.Key.f7):
pressed_key = "f7"
print(pressed_key)
else:
pressed_key = None
def on_release(key):
global pressed_key
pressed_key = None
def on_click(x, y, button, pressed):
if pressed:
#print ("{0} {1}".format(x,y))
print(pressed_key)
if pressed_key == "f7":
x_pos.append("{0}".format(x,y))
y_pos.append("{1}".format(x,y))
#print("test" + x_pos + y_pos)
print (x_pos + y_pos)
#both_pos = x_pos, y_pos
else:
pass
print (x_pos + y_pos)
mouse_listener = mouse.Listener(on_click=on_click)
mouse_listener.start()
with keyboard.Listener(on_press = on_press, on_release = on_release) as listener:
try:
#listener.start()
listener.join()
except MyException as e:
print('Done'.format(e.args[0]))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51705708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Unittest Inheritance I have 2 classes, A and B.
class A (unittest.TestCase):
#methods here
class B (A):
#methods here
when i try and call self.assertEqual(1,1) in a method of class B, I get the error mentioned here:
Why do I get an AttributeError with Python3.4's `unittest` library?
Yet if I call it in A, everything is fine.
Does unittest not follow regular inheritance? Is there only a very specific way you can use it?
A: I have tried your example as such:
import unittest
class A(unittest.TestCase):
def test_a(self):
self.assertEqual(1, 1)
class B(A):
def test_b(self):
self.assertEqual(2, 3)
if __name__ == '__main__':
unittest.main()
and it worked, this is test result:
test_a (__main__.A) ... ok
test_a (__main__.B) ... ok
test_b (__main__.B) ... FAIL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45314519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding a ViewGroup to a ViewGroup I would like to be able to programmatically add a viewgroup to another viewgroup. Both have been defined in xml as follows, along with my onCreate method:
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/firstll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="first text" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="second text" />
secondlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/secondll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="first text" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="second text" />
onCreate:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getBaseContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null);
LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.secondlayout, null);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(tv);
setContentView(ll);
}
A: You are trying to find a view before you set the content view when you do findViewById(R.layout.secondlayout). Also, secondlayout isn't the id of a view, it's the name and id of the layout file.
Try doing
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null);
LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.secondlayout, null);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(tv);
setContentView(ll);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8435294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ng-repeat in Angular.js not working as expected I have an object of JavaScript that I push it into an array, the code like below:
//Firebase Retrieve Data
var ref = firebase.database().ref().child("pelanggan");
ref.on("child_added", function(snapshot) {
var key = snapshot.key;
console.log("SALES ID : " + key);
var pelangganArr = new Array();
var ref2 = firebase.database().ref().child("pelanggan").child(key);
ref2.on('child_added', function(data) {
var pelanggan = new Object();
pelanggan.alamat = data.val().alamat;
pelanggan.email = data.val().email;
pelanggan.identitas = data.val().identitas;
pelanggan.layanan = data.val().layanan;
pelanggan.lo = data.val().lo;
pelanggan.lt = data.val().lt;
pelanggan.nama = data.val().nama;
pelanggan.noHp = data.val().noHp;
pelanggan.salesId = key;
pelangganArr.push(pelanggan);
console.log(pelanggan.salesId+" : "+pelanggan.nama+","+pelanggan.identitas+","+pelanggan.alamat+","+pelanggan.email);
And I use ng-repeat to display it in html, on the console I got:
Sales Controller loaded..
sales.js:120 sales01 : Endang,85764321,Bintaro,[email protected]
sales.js:120 sales01 : Gugi Pratama,1234567894,Jl. Mampang Prapatan,[email protected]
sales.js:120 sales01 : Endang,85764321,Bintaro,[email protected]
sales.js:120 sales01 : Gugi Pratama,1234567894,Jl. Mampang Prapatan,[email protected]
sales.js:120 sales01 : Endang,85764321,Bintaro,[email protected]
sales.js:120 sales01 : Gugi Pratama,1234567894,Jl. Mampang Prapatan,[email protected]
sales.js:120 sales02 : imam farisi,123456789,Jl. Pejaten Raya No.1, Pasar Minggu,[email protected]
sales.js:120 sales02 : Budi,1234567891,Jl. Ragunan Raya No. 1, Jakarta Selatan,[email protected]
sales.js:120 sales02 : Riza Putriyani,1234567892,Jl. Kemang Raya No. 1, Jakarta Selatan,[email protected]
sales.js:120 sales02 : imam farisi,123456789,Jl. Pejaten Raya No.1, Pasar Minggu,[email protected]
sales.js:120 sales02 : Budi,1234567891,Jl. Ragunan Raya No. 1, Jakarta Selatan,[email protected]
sales.js:120 sales02 : Riza Putriyani,1234567892,Jl. Kemang Raya No. 1, Jakarta Selatan,[email protected]
sales.js:120 sales02 : imam farisi,123456789,Jl. Pejaten Raya No.1, Pasar Minggu,[email protected]
sales.js:120 sales02 : Budi,1234567891,Jl. Ragunan Raya No. 1, Jakarta Selatan,[email protected]
sales.js:120 sales02 : Riza Putriyani,1234567892,Jl. Kemang Raya No. 1, Jakarta Selatan,[email protected]
But my view is blank, I wrote the script like:
<tbody ng-controller="SalesCtrl as t">
<tr ng-repeat="pelanggan in pelangganArr">
<td>{{pelanggan.alamat}}</td>
<td>{{pelanggan.email}}</td>
<td>{{pelanggan.lo}}</td>
<td>{{pelanggan.lt}}</td>
<td>{{pelanggan.nama}}</td>
<td>{{pelanggan.noHp}}</td>
<td></td>
<td><a class="btn btn-success" ng-click="showEditSalesForm(sales)">Edit</a></td>
<td><a class="btn btn-danger" ng-click="removeSales(sales)">Delete</a></td>
</tr>
</tbody>
to render it.
I am new in Angular.js.
A: Try
<tr ng-repeat="pelanggan in t.pelangganArr">
A: In your controller declare pelangganArr as $scope.pelangganArr.
Only scope variables are recognised by angular in the DOM and provide 2 way binding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42397464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I create a document with inputs from cells of a spreadsheet? Please refer the link/pic for more details? How can I create a document with inputs from cells of a spreadsheet? Please refer the link/pic for more details.
enter image description here
A: This might help you to get started:
function makeDoc(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('myDoc');
var vA=sh.getDataRange().getValues();
var name=vA[0][0];
var doc=DocumentApp.create(name);
var body=doc.getBody();
for(var i=1;i<vA.length;i++){
body.appendParagraph(vA[i][0]);
}
var root=DriveApp.getRootFolder();
var files=root.getFilesByName(name);
while(files.hasNext()){
var child=files.next();
}
var newFolder=DriveApp.getFolderById('finalFolderId');
newFolder.addFile(child)
root.removeFile(child);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48611265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: jquery ui tabs change content after .tabs() initialization OBJECTIVE:
How can I change content of ui tabs after it has been initialized.
See code below.Possible something after $tabs.find(content-1) etc
*
*Actually My tabs have content based on json requests which then will
be parsed and displayed as per requriement (graphs,tables etc).
*I can not use
*tab1 method described
in ui docs for ajax content because I need all tabs to have data
separately and load simultaneously. Ajax method keeps replacing one
tab data with other tab data which is not my requirement.
So ideally,
*
*tabs should init with "loading .." message.
*Then Afetr i have detected its init event , i should make say 3 different ajaxcalls , process data and whichever is completed, "loading .." message should be replace with its content.
My JSFIDDLE
HTML:
<div id="tabs">
<ul>
<li><a href="#tabs-1">tab1</a>
</li>
<li><a href="#tabs-2">tab2</a>
</li>
<li><a href="#tabs-3">tab3</a>
</li>
</ul>
<div id="tabs-1">
<p>loading...</p>
</div>
<div id="tabs-2">
<p>loading...</p>
</div>
<div id="tabs-3">
<p>loading...</p>
</div>
</div>
JS
$tabs = $('#tabs').tabs({
cache: false,
});
//
$tabs.do something here
$tab. detect evet if tabs have initialized ..
then send ajax requests and append to tabs content area ..
A: Working DEMO
Try this
I guess this is what you need
$(document).ready(function () {
$tabs = $('#tabs').tabs({
cache: false,
});
if ($('#tabs').hasClass('ui-tabs')) { // check if tabs initilized
$('.tab').each(function () {
var tab = $(this);
$.ajax({
url: '/echo/html/',
success: function (data) {
tab.html("success"); // for demo
}
});
});
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19021554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to integrate normal distribution with numpy and scipy? trying to integrate a normal distribution
import numpy as np
import scipy
this does not work, throws a type error:
def f_np(x):
return np.random.normal(size=x)
integrate.quad(f_manual, -np.inf, np.inf)
mtrand.pyx in numpy.random.mtrand.RandomState.normal()
_common.pyx in numpy.random._common.cont()
TypeError: 'float' object cannot be interpreted as an integer
but it works if I manually enter the pdf:
def f_manual(x):
return 1/(1 * np.sqrt(2 * np.pi)) * np.exp(-(x - 0)**2 / (2 * 1**2) )
integrate.quad(f_manual, -np.inf, np.inf)
(0.9999999999999997, 1.017819145094224e-08)
any idea why?
A: Several things going on here.
np.random.normal draws samples from the normal distribution. The size parameter specifies the number of samples you want. If you specify 10 you'll get an array with 10 samples. If you specify a tuple, like (4, 5) you'll get a 4x5 array. Also, np.inf is a float and np.random.normal is expecting an integer or a tuple of integers for the size parameter.
What you have in f_manual is a deterministic function (i.e. the PDF) which returns the value of the PDF at the value x.
These are two different things.
scipy has a function to return the PDF of a Gaussian: scipy.stats.norm.pdf
import scipy.stats
scipy.integrate.quad(scipy.stats.norm.pdf, -np.inf, np.inf)
# (0.9999999999999998, 1.0178191320905743e-08)
scipy also has a CDF function that returns the integral from -inf to x:
scipy.stats.norm.cdf(np.inf)
# 1.0
scipy.stats.norm.cdf(0)
# 0.5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66502401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Docker: ERROR: relation "users" does not exist at character 13 I am trying to dockerize my app made with Python and FastAPI. I successfully created the images and container.
I tried to dockerize my postgres database it was done successfully until I try to create a new user. It throws the following error:
ERROR: relation "users" does not exist at character 13
10 02:24:37.586 UTC [71] STATEMENT: INSERT INTO users (email, password) VALUES ('[email protected]', '$2b$12$VNya4IkKSGCuapswkJrh3u6POJVsdU2GSeIaV/ya4GprxNqEt5oim') RETURNING users.id
It shows the following error in my FastAPI app image:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context
self.dialect.do_execute(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.UndefinedTable: relation "users" does not exist
LINE 1: INSERT INTO users (email, password) VALUES ('sumitdadwal11@g...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 376, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/usr/local/lib/python3.9/site-packages/fastapi/applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "/usr/local/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/usr/local/lib/python3.9/site-packages/starlette/middleware/cors.py", line 84, in __call__
await self.app(scope, receive, send)
File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 226, in app
raw_response = await run_endpoint_function(
File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 161, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 39, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "/usr/local/lib/python3.9/site-packages/anyio/to_thread.py", line 28, in run_sync
return await get_asynclib().run_sync_in_worker_thread(func, *args, cancellable=cancellable,
File "/usr/local/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 818, in run_sync_in_worker_thread
return await future
File "/usr/local/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 754, in run
result = context.run(func, *args)
File "/usr/src/app/./app/routers/user.py", line 18, in create_user
db.commit()
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 1428, in commit
self._transaction.commit(_to_root=self.future)
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 829, in commit
self._prepare_impl()
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 808, in _prepare_impl
self.session.flush()
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3345, in flush
self._flush(objects)
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3485, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
compat.raise_(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3445, in _flush
flush_context.execute()
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/unitofwork.py", line 456, in execute
rec.execute(self)
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/unitofwork.py", line 630, in execute
util.preloaded.orm_persistence.save_obj(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/persistence.py", line 244, in save_obj
_emit_insert_statements(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/persistence.py", line 1221, in _emit_insert_statements
result = connection._execute_20(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1614, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection
return connection._execute_clauseelement(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1481, in _execute_clauseelement
ret = self._execute_context(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1845, in _execute_context
self._handle_dbapi_exception(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2026, in _handle_dbapi_exception
util.raise_(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context
self.dialect.do_execute(
File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users" does not exist
LINE 1: INSERT INTO users (email, password) VALUES ('sumitdadwal11@g...
^
[SQL: INSERT INTO users (email, password) VALUES (%(email)s, %(password)s) RETURNING users.id]
[parameters: {'email': '[email protected]', 'password': '$2b$12$5tcxP4b0hwVJpmHfyF10wuosYsdIxBkm1nhk1b1BZlLFZyCymodhK'}]
(Background on this error at: https://sqlalche.me/e/14/f405)
This is my docker-compose.yml file:
version: "3"
services:
api:
build: .
ports:
- 8000:8000
# env_file:
# ./.env
environment:
- DATABASE_HOSTNAME=postgres
- DATABASE_PORT=5432
- DATABASE_PASSWORD=password123
- DATABASE_NAME=fastapi
- DATABASE_USERNAME=postgres
- SECRET_KEY=secretkeysecretkeysecretkeysecretkey
- ALGORITHM=HS256
- ACCESS_TOKEN_EXPIRE_MINUTES=30
postgres:
image: postgres
environment:
- POSTGRES_PASSWORD=password123
- POSTGRES_DB=fastapi
volumes:
- postgres-db:/var/lib/postgresql/data
volumes:
postgres-db:
This is my Dockerfile:
FROM python:3.9.9
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
First I thought somethings wrong with my code but it is working fine when I am running it locally on my system.
Also, I am very new to docker.
I have tried different online solution but nothing worked out.
I think it getting connected to the wrong table named postgres but I cant find the reason behinf it.
UPDATE:
What I have noticed is that my postgress server has three databases:
-fastapi
-fastapi-project
*
*postgres
fastapi is the one i want to connect to but i think it is getting connected to the postgres one and I dont remember creating that database.
Also the postgres database has no tables so it makes sense that it cannot find the user table.
But the question is how do I change databases?
Please let me know if you need any additional information.
Thanks in advance!
A: I ran into the same problem following Sanjeev's tutorial. Given your settings, you are connecting to the right db, the issue is that it has no tables. This can be solved via Alembic.
In your docker-compose.yml, under api: add the line:
command: bash -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload"
That's it!
To check that the tables have been successfully created, open a terminal in your project folder and do the following:
*
*Run docker compose
docker-compose up -d
*Find the pg container name, in your case it should be something like fastapi-postgres-1, then start a bash session into your pg container
docker ps
docker exec -it fastapi-postgres-1 bash
*From here, access psql and find your db name, in your case it should be fastapi
su - postgres
psql
\l
*Access your db and check that the tables have been created
\c fastapi
\dt
If result is something like this, you're good to go.
List of relations
Schema | Name | Type | Owner
--------+-----------------+-------+----------
public | alembic_version | table | postgres
public | posts | table | postgres
public | users | table | postgres
public | votes | table | postgres
(4 rows)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70298161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use of common methods within other Vue components What is the proper way to use method isValidEmail within compA.vue and some other hypothetical compB.vue?
This approach doesn't work for me:
<template>
<div></div>
</template>
<script>
export default {
name: 'Validators',
methods: {
isValidEmail(someEmail) {
//Omitted
},
}
}
</script>
<template>
<div>{{isValidEmail('[email protected]')}}</div>
</template>
<script>
import Validators from 'validators.vue'
export default {
name: 'CompA',
components: {
'validators': Validators
},
}
</script>
A: You can simply use mixins: you define in the mixin the function isValidEmail and then you import the mixin in the components you need.
https://v2.vuejs.org/v2/guide/mixins.html - Vue v2
https://v3.vuejs.org/guide/mixins.html - Vue v3
For example, instead creating a component Validators.vue as you did in your example, you can create a mixin named Validators.js as per below:
export default {
methods: {
isValidEmail(someEmail) {
//Omitted
}
}
}
Then you can import the mixin in the components you need:
<template>
<div>{{isValidEmail('[email protected]')}}</div>
</template>
<script>
import MixinValidator from 'Validators.js'
export default {
name: 'CompA',
mixins: [ MixinValidator ],
}
</script>
In this way, the component CompA will inherit all the functions, data and computed property defined in the mixin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64512912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to write social media links to NFC cards? So I'm new to NFC technology and I bought NFC Card - MIFARE Classic 1K 13.56MHz and tried to write my Social Media using the NFC tools application on mobile. My end goal here is to share my Social Media with just 1 tap from my NFC card. But when I try to write, it errors. Any suggestions or applications I can use to do what I want it to do?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73755287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Statements after Switch being skipped I may be having a senior moment here (at 22 years old), but I can't figure out why C# is skipping a statement I have included after a switch. The code goes as follows:
switch (shape)
{
case ToolShape.BasicTool:
EditTool = (LastTool.ToolType == ToolShape.BasicTool)
? new BasicTool((BasicTool)LastTool)
: new BasicTool(ToolNumber, BasicToolType.TypeA,
"Tool " + ToolNumber, "", 1.0, 60.0, 0.0, 0.0, 0.0, 10.0);
break;
case ToolShape.AdvancedTool:
EditTool = (LastTool.ToolType == ToolShape.AdvancedTool)
? new AdvancedTool((AdvancedTool)LastTool)
: new AdvancedTool(AdvancedTool, "Tool " + ToolNumber, "", 1.0, 10.0, 2.0,
AdvancedTool.Light, AdvancedTool.Round);
break;
case ToolShape.SpecialTool:
EditTool = (LastTool.ToolType == ToolShape.SpecialTool)
? new SpecialTool((SpecialTool)LastTool)
: new SpecialTool(SpecialTool, "Tool " + ToolNumber, "",
1.0, 1.0, 90.0);
break;
}
// We never seem to reach anything below here ----------------
LoadToolToForm(EditTool);
It's never hitting that LoadToolToForm(EditTool) statement. Or a MessageBox.Show("...") I stuck in there, for debugging purposes. Removing the switch works as expected. Putting even a really small switch in there with a single case causes it to exit prematurely again, though.
Is this known behavior? Is there a situation in which breaking from a switch statement causes the function to exit (without ever invoking the return keyword).
A: If you are sure the code is never passing the switch statement, there is only one other possibility:
There is an exception being thrown in the switch statement, and it is being caught somewhere higher up so the program just continues.
One thing you could try to verify this suggestion would be wrapping your switch in a temporary try{}catch{} block and showing a MessageBox on Exception, or use lots of breakpoints.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12923656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: toolbar inflate from fragment not working at first drawer layout creation of the activity Introduction
I have an activity (let's call BaseActivity) that initializes the drawer layout in onPostCreate
public void initDrawerLayout(){
setSupportActionBar(getYellowToolbar());
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setScrimColor(getResources().getColor(R.color.blue_menu));
// Toggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
getYellowToolbar(), R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
EventBus.getDefault().post(new UiHelper());
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
findViewById(R.id.menu_back).setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
});
mExpandableListView = (ExpandableListView) findViewById(R.id.listmenu);
mExpandableListView.setOnGroupClickListener(this);
mExpandableMenuAdapter = getMenuAdapter();
mExpandableListView.setAdapter(mExpandableMenuAdapter);
mDrawerToggle.syncState();
}
Then I have a specific fragment working under an Activity which extends BaseActity.
This fragment adds to the top toolbar (yellowtoolbar) at onResume time an additional button inside R.menu.scanner_menu.
Toolbar toolbar = getYellowToolbar();
if (toolbar == null)
return;
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.scanner_menu);
/**
* Add click listener on scan
*/
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
.
.
return false;
}
});
Situation
BaseActivity onPostCreate init drawer layout
ChildrenActivity extends BaseActivity
Fragment inflates new button onResume
Problem
When I reach this fragment from another fragment belonging to the same activity the inflate of the additional button is successful and I can click it with no problem.
While if I starts the application (so the onPostCreate of the BaseActivity is called) having the fragment to be shown at first so both the initDrawerLayout from BaseActivity and the inflate of the fragment are called almost at the same time the inflate of the additional button is unsuccessful and I cannot see it.
Additional info
I have tried to add a generic button in the fragment and clicking on it inflates one more time the menu button in the top toolbar and it correctly works. I think the problem seems to be the toolbar rendering by the drawer layout initialization that is still not completed the moment the fragment inflates the new button, so the toolbar just skip the new button and goes on with the BaseActivity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46845140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: After run firefox go to full screen but not kiosk mode I would like to start Firefox automatically on startup, and then maximize the window. With the code below, I am currently able to start Firefox, however I cannot get past that.
#!/bin/bash
firefox &
while [ "$(wmctrl -l | grep \"Mozilla Firefox\" 2>&1 | wc -l)" -eq 0 ];
do
sleep 1;
done
wmctrl -r firefox -b toggle, fullscreen
The first portion starts running Firefox. After that there is a loop, which I'm writing to create and display the Firefox window. The last step is maximize Firefox to full screen.
I believe I have a problem with the while loop.
A: I suggest:
while [[ $(wmctrl -l | grep "Mozilla Firefox" 2>&1 | wc -l) -eq 0 ]]; do
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50182858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Woocommerce: Runtime error when I place order to process payment using bank API I'm using Armenian bank API with woocommerce as extra payment method. When I place order it gives me Runtime error. I'm attaching the image or the error I receive and the code I am using.
id = 'ameriabank'; // payment gateway plugin ID
$this->icon = ''; // URL of the icon that will be displayed on checkout page near your gateway name
$this->has_fields = true; // in case you need a custom credit card form
$this->method_title = 'Ameria Bank Gateway';
$this->method_description = 'Description of Ameria payment gateway';
$this->supports = array(
'products',
'subscriptions'
);
// Method with all the options fields
$this->init_form_fields();
// Load the settings.
$this->init_settings();
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->enabled = $this->get_option( 'enabled' );
//$this->testmode = 'yes' === $this->get_option( 'testmode' );
$this->ClientID = $this->get_option( 'ClientID' );
$this->Username = $this->get_option( 'Username' );
$this->Password = $this->get_option( 'Password' );
// This action hook saves the settings
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// We need custom JavaScript to obtain a token
//add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
// You can also register a webhook here
// add_action( 'woocommerce_api_{webhook name}', array( $this, 'webhook' ) );
}
/**
* Plugin options, we deal with it in Step 3 too
*/
public function init_form_fields(){
$this->form_fields = array(
'enabled' => array(
'title' => 'Enable/Disable',
'label' => 'Enable AmeriaBank Gateway',
'type' => 'checkbox',
'description' => '',
'default' => 'no'
),
'title' => array(
'title' => 'Title',
'type' => 'text',
'description' => 'This controls the title which the user sees during checkout.',
'default' => 'Credit Card',
'desc_tip' => true,
),
'description' => array(
'title' => 'Description',
'type' => 'textarea',
'description' => 'This controls the description which the user sees during checkout.',
'default' => 'Pay with your credit card via our super-cool payment gateway.',
),
'ClientID' => array(
'title' => 'Client ID',
'type' => 'text'
),
'Username' => array(
'title' => 'Username',
'type' => 'text'
),
'Password' => array(
'title' => 'Password',
'type' => 'text'
)
);
}
public function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
// Ameria bank params
$this->description = "[description]";
$this->orderID = $order_id;
$this->paymentAmount = $order->get_total();
$_SESSION['eli_cart_total'] = $this->paymentAmount;
$this->backURL = add_query_arg('key', $order->order_key, add_query_arg('order', $order_id, get_permalink(woocommerce_get_page_id('thanks'))));
$options = array(
'soap_version' => SOAP_1_1,
'exceptions' => true,
'trace' => 1,
'wdsl_local_copy' => true
);
$client = new SoapClient("https://testpayments.ameriabank.am/webservice/PaymentService.svc?wsdl", $options);
$args['paymentfields'] = array(
'ClientID' => $this->ClientID,
'Username' => $this->Username,
'Password' => $this->Password,
'Description' => $this->description,
'OrderID' => $this->orderID,
'PaymentAmount' => $this->paymentAmount,
'backURL' => $this->backURL
);
$webService = $client->GetPaymentID($args);
$_SESSION['pid'] = $webService->GetPaymentIDResult->PaymentID;
$this->liveurl = 'https://testpayments.ameriabank.am/forms/frm_paymentstype.aspx?clientid='.$this->ClientID.'&clienturl='.$this->backURL.'&lang=am&paymentid='.$webService->GetPaymentIDResult->PaymentID;
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->liveurl
);
}
/**
* Output for the order received page.
*
* @access public
* @return void
*/
function thankyou_page($order_id) {
global $woocommerce;
$options = array(
'soap_version' => SOAP_1_1,
'exceptions' => true,
'trace' => 1,
'wdsl_local_copy' => true
);
$client = new SoapClient("https://testpayments.ameriabank.am/webservice/PaymentService.svc?wsdl", $options);
$total = $_SESSION['eli_cart_total'];
$args['paymentfields'] = array(
'ClientID' => $this->ClientID,
'Username' => $this->Username,
'Password' => $this->Password,
'PaymentAmount' => $total,
'OrderID' => $order_id
);
$webService = $client->GetPaymentFields($args);
if($webService->GetPaymentFieldsResult->respcode == "00") {
$order = new WC_Order( $order_id );
$type = $webService->GetPaymentFieldsResult->paymenttype;
if( $type == "1" ) {
$client->Confirmation($args);
}
$order->update_status('on-hold', __( 'Awaiting credit card payment', 'woocommerce' ));
// Reduce stock levels
$order->reduce_order_stock();
// Remove cart
$woocommerce->cart->empty_cart();
} else {
//echo '';
}
}
}
}
Error Screenshot:
Let me know if someone can help me on this.
A: The problem was in this->backURL because it has / so the server feel like go to /another resource so you need to encode it using urlencode(this->backURL)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53481080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Doing the following operations in Azure ML Studio through REST calls Is there any possibility of doing the following operations in Azure ML Studio through REST calls?
1) Create and upload a new dataset.
2) Create a new Automated ML run selecting an already created dataset, configuring the experiment name, target column and training cluster and selecting the task type (e.g. Classification/Regression).
3) Deploy the run on a container and retrieve the container endpoint URL.
A: Please follow the APIs available at the https://learn.microsoft.com/en-us/rest/api/azureml/
for Azure ML studio through REST API calls, but other than dataset-related API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61094767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: find out which browse button clicked in a repeater and append progress bar under particular clicked browse button I have attached browse button in each row of repeater and on click browse button selected files display with progress bar but i am facing problem when I click any browse button progress bar always display in the first row of repeater. Actually i am unable to find out which button has clicked in a repeater.I have to append progress bar and file name of particular clicked browse button.My code is as follows:
<html>
<head runat="server">
<script src="jquery.min.js" type="text/javascript"></script>
<style>
.a{
display:none;
}
.input{
display:none;
margin-top: -17px;
margin-left: 176px;
width:34px;
}
.button {
background: #25A6E1;
background: -moz-linear-gradient(top,#25A6E1 0%,#188BC0 100%);
background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#25A6E1),color-stop(100%,#188BC0));
background: -webkit-linear-gradient(top,#25A6E1 0%,#188BC0 100%);
background: -o-linear-gradient(top,#25A6E1 0%,#188BC0 100%);
background: -ms-linear-gradient(top,#25A6E1 0%,#188BC0 100%);
background: linear-gradient(top,#25A6E1 0%,#188BC0 100%);
filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
padding:8px 13px;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:17px;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border:1px solid #1A87B9;
width:227px !important;
}
</style>
<script>
var selDiv = "";
var updateProcessInterval;
var updateTextBoxInterval;
document.addEventListener("DOMContentLoaded", init, false);
function init() {
// var classname = document.getElementsByClassName("files");
// alert(classname);
// document.querySelector('#files').addEventListener('change', handleFileSelect, false);
var f = document.querySelectorAll('.files');
// alert(f);
for (var i = 0; i < f.length; i++) {
//alert("jdj");
//alert(f.length);
f[i].addEventListener("change", handleFileSelect, false);
//alert(f[i]);
/* for (var i = 0; i < classname.length; i++) {
alert(classname.length);
classname[i].addEventListener('change', handleFileSelect, false);
}*/
// $('.files').on("change", function(){ handleFileSelect(); });
}
}
function handleFileSelect(e) {
if (!e.target.files) return;
var files = e.target.files;
// alert(files);
for (var i = 1; i < files.length; i++) {
var progress = document.createElement("progress");
progress.setAttribute('class', 'a');
progress.setAttribute('id', 'i');
progress.setAttribute('max', '100');
progress.setAttribute('value', '0');
var filename = document.createElement("div");
var text = document.createElement("input");
text.setAttribute('class', 'input');
text.setAttribute('value', '0%');
text.setAttribute('max', '100%');
filename.setAttribute('class', 'filename');
$('.prrogress-wp').append(filename);
$('.progress-wpr').append(progress);
$('.progress-wpr').append(text);
}
var elements = document.getElementsByClassName('a');
var filename = document.getElementsByClassName('filename');
var textname = document.getElementsByClassName('input');
for (var i = 0; i < files.length; i++) {
var f = files[i];
var p = elements[i];
var t = textname[i];
filename[i].innerHTML = f.name;
p.style.display = 'block';
t.style.display = 'block';
updateProcessInterval = setInterval(update_progress, 1500);
updateTextBoxInterval = setInterval(updatetextbox, 1500);
}
}
function update_progress() {
var elements = document.getElementsByClassName('a');
for (var i = 0; i < elements.length; i++) {
var p = elements[i];
var a = p.value;
a = a + 10; //alert(a)// infinite number of times sum
if (a > 100) { //if this part add then see
clearInterval(updateProcessInterval);
}
p.value = a; //alert(p.value);
}
}
function updatetextbox() {
var textt = document.getElementsByClassName('input');
//alert(textt.length); //any alert in this doc display right value but n no times
for (var i = 0; i < textt.length; i++) {
var tt = textt[i];
// alert(textt[i]);
var a = tt.value;
c = parseInt(a) + parseInt("10");
if (parseInt(c) > 100) {
clearInterval(updateTextBoxInterval);
return;
} else if (!(parseInt(c) < 0 || isNaN(c))) {
tt.value = c + "%";
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource2">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table id="gg">
<tr class="ff">
<td>
<input type="file" class="button files" id="files" name="files" onchange="handleFileSelect(this)" multiple><br/>
<div id="progress-wpr" class="progress-wpr">
<div class="filename"></div>
<progress class='a' max=100 value=0></progress>
<input type="text" value="0%" class="input" max="100" />
</div>
<input type="submit" value="Upload" class="button" style="margin-top:56px;width:77px !important" >
</td></tr></table>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
Please help me to find out clicked button in repeater so that i can append progress bar in it.Thanks in advance....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27372128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ip header help? Why in struct ip is defined like
#if __BYTE_ORDER == __LITTLE_ENDIAN
unsigned int ip_hl:4; /* header length */
unsigned int ip_v:4; /* version */
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
unsigned int ip_v:4; /* version */
unsigned int ip_hl:4; /* header length */
#endif
Little endian and big endianess only affects multibyte values. Why are we storing ip_hl before ip_v, shouldn't ip_hl be transmitted after ip_v?
A: Endianess also affects the way the compiler puts bit-field fields (the ":4" at the end means it's only 4 bits worth of the value) within bytes of the resulting structure. For big-endian, the bits populate from the most-significant. For little-endian, the bits populate from the least-significant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5559240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use a ListView.builder and wrap widgets dynamically I try to solve the following problem: I want to have a dynamically generated set of cards widgets which should be layed out horizontal and wrap the line when the card is getting too big:
I was thinking of a ListView.builder but this can either go horizontal or vertical. More, a gridview seems also not the best option as I have no fixed columns or rows. Is there any way in doing so or exists there maybe a widget I am not aware of currently?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65092620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DataStax Solr index rebuild. reload all data from cassandra table I created a table using cql, inserted 2 rows to that table and created solr index using datastax procedures. The index has no documents.
If I inserted another row to the table using cql, The index has 1 document not 3 documents.
I tried to delete the index data and rebuild the index using dsetool rebuildindexes command
dsetool -h localhost rebuild_indexes demo_db tbl_1 demo_db.tbl_1
but the index still has 1 documents instead of 3 documents.
Is there any way to rebuild the index to be loaded with all rows in the table?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29651898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS Sqlite NSDate value I have a Date column in my Sqlite database. When I put some NSDate value in it, and open the Sqlite file through graphical tools. I get some value like 530963469.705571. The corresponding date is around today or yesterday.
It's clearly not Unix epoch datestamp value. What exactly does this value mean?
I need to change this value in order to debug my app.
A: From the documentation
NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).
Since sqlite does not support NSDate directly, the date is persisted as the underlying value. 530963469.705571 represents the number of seconds between 00:00:00 UTC on 1 January 2001 and the time when you created the NSDate
You can use the NSDate initialiser init(timeIntervalSinceReferenceDate:) to create an NSDate from the time interval value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47008663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check that specific value exists in multidimension array I have session with multidimensions array and this session is update by every form send.
I would like to check if the product_id already exists in my multidimensional array, so as not to add it several times, but only to increase the number of pieces. I create something like a basket. So when somebody add the same product to cart in my session have to check, that this product exists and if exists update just quantity field in array.
I do everything in ajax
array(2) {
[0]=>
array(15) {
["quantity"]=> string(1) "1"
["final_price"]=> string(3) "0.5"
["do_wash"]=> string(2) "on"
["final_wash_price"]=> string(3) "0.2"
["do_bringing"]=> string(2) "on"
["final_bringing_price"]=> string(3) "0.4"
["deposit_price"]=> string(1) "5"
["product_name"]=> string(24) "Talerz płytki Ø 160 mm"
["product_id"]=> string(2) "12"
["product_price"]=> string(3) "0.5"
["product_person_to_bringing"]=> string(1) "1"
["product_wash_price"]=> string(3) "0.2"
["product_bringing_price"]=> string(3) "0.4"
["product_calculate_bringing"]=> string(0) ""
["action"]=> string(9) "send_form"
}
[1]=>
array(15) {
["quantity"]=> string(1) "1"
["final_price"]=> string(3) "0.5"
["do_wash"]=> string(2) "on"
["final_wash_price"]=> string(3) "0.2"
["do_bringing"]=> string(2) "on"
["final_bringing_price"]=> string(3) "0.4"
["deposit_price"]=> string(1) "5"
["product_name"]=> string(24) "Talerz płytki Ø 160 mm"
["product_id"]=> string(2) "12"
["product_price"]=> string(3) "0.5"
["product_person_to_bringing"]=> string(1) "1"
["product_wash_price"]=> string(3) "0.2"
["product_bringing_price"]=> string(3) "0.4"
["product_calculate_bringing"]=> string(0) ""
["action"]=> string(9) "send_form"
}
}
if (isset($_POST['action'])) {
if (!isset($_SESSION['products'])) {
$_SESSION['products'] = [];
}
if (!isset($_SESSION['product'])) {
$_SESSION['product'] = [];
}
$product_object = $_POST;
$_SESSION['product'] = [];
$_SESSION['product'][] = $product_object;
foreach ($_SESSION['product'] as $single_product_array) {
$_SESSION['products'][] = $single_product_array;
}
echo '<pre style="color:#fff;">';
var_dump( $_SESSION['products']);
echo '</pre>';
}
I try to use functions from: PHP multidimensional array search by value and from php.net
$key = array_search(40489, array_column($userdb, 'uid')); but not working for me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69348834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I redirect STDOUT to .json for logs in NodeJS I need to have my logs in .json format and currently I use express-js server and my logs looks the following:
Error: Cannot return null for non-nullable field Query.get_bar.
Error: Cannot return null for non-nullable field Query.get_bar.
Error: Cannot return null for non-nullable field Query.get_foo.
I figured out there're some logger frameworks (log4js, winstonjs) but I don't want to log manually (i.e., console.log(123)), I'm interested in redirecting my STDOUT, converting it to JSON and writing to some .log file.
What's the most simple solution for this task?
Update: there's a related issue on GitHub.
A: The process.stdout and process.stderr pipes are independent of whatever actual code you're running using Node, so if you want their output sent to files, then make your main entry point script capture stdout/stderr output and that's simply what it'll do for as long as Node.js runs that script.
You can add log writing yourself by tapping into process.stdout.on(`data`, data => ...) (and stderr equivalent), or you can pipe their output to a file, or (because why reinvent the wheel?) you can find a logging solution that does that for you, but then that's on you to find, asking others to recommend you one is off topic on Stackoverflow.
Also note that stdout/stderr have some sync/async quirks, so give https://nodejs.org/api/process.html#process_a_note_on_process_i_o a read because that has important information for you to be aware of.
A: The example from winston basically solved the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57314819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: VBA writes to first Excel cell only, not second I am using a form to process data and write it into a worksheet. The form is working but whenever I write to a cell, the first data is written and then the subroutine exits without error.
I have written some test code; "aaa" is written but "bbb" is not.
Private Sub CommandButton1_Click()
On Error GoTo ErrorHandler
ThisWorkbook.Sheets("DJ").Cells(10, 1) = "aaa"
ThisWorkbook.Sheets("DJ").Cells(10, 2) = "bbb"
Exit Sub ' Exit to avoid handler.
ErrorHandler: ' Error-handling routine.
Dim E As Integer
E = Err.Number
Resume Next
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70389905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Enable Bitcode is not setting to Yes after upgrading watchOS 1 to watchOS4 in Xcode 9.1 I got this mail from Apple when I tried to submit build after upgrading watchOS. Bitcode was not enabled in the whole app before.
Dear developer,
We have discovered one or more issues with your recent delivery for "event****". To process your delivery, the following issues must be corrected:
Invalid Executable - The executable 'ProjectName.app/Watch/ProjectName WatchKit App.app/PlugIns/ProjectName WatchKit Extension.appex/ProjectName WatchKit Extension' does not contain bitcode.
Though you are not required to fix the following issues, we wanted to make you aware of them:
WatchKit 1.0 - Your previous version used an extension for Apple Watch but your current version doesn’t. Users who haven’t updated their Apple Watch to watchOS 2 or later may lose access to their Apple Watch extension.
Once the required corrections have been made, you can then redeliver the corrected binary.
I have googled and followed this link which seems helpful to me but It didn't.
Bitcode WatchOS3 - how to generate
I have one doubt, In my project for iOS targets, bitcode settings are in build option under Build settings but for watchOS targets it comes in User defined settings under build settings.
When I tried to set its value to yes and go ahead to archive the build, at the time of exporting the IPA file it shows the contents of the target, in which it is always showing bitcode is not included. Why it is happening even after setting the yes value, I am totally confused.
I want to set the bitcode value to yes for only watchOS targets.
Thanks
A: As I have solved this issue by clearing a small confusion which can cause lot of stress to anyother like me.
Apple says : For iOS apps, bitcode is the default, but optional. For watchOS and tvOS apps, bitcode is required. If you provide bitcode, all apps and frameworks in the app bundle (all targets in the project) need to include bitcode.
So if your app does not having targets for WatchOS(in my case watchOS4 version) then it is ok to enable or disable bitcode settings as per your requirement. But in any case if you have watchOS targets in your app then you don't have any other option rather than enabling the bitcode for whole app targets and then only apple can accept your build for Appstore.
If you enable the bitcode for watchOS targets and disable the bitcode setting for other targets then the build can archive but the bitcode setting inside the build will always show "NOT INCLUDED" and apple rejects it.
And after enabling bitcode if you are using old third party libraries then you have to update each library to the version which support bitcode, it include pods as well. So beware of it because it is not easy task if your app is old and toooooo vast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47752045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get missing content length for a file from url? I am trying to write a simple download manager using python with concurrency. The aim is to use the Content-Length header from the response of a file url and splits the file into chunks then download those chunks concurrently. The idea works for all the urls which have Content-Length header but recently I came across some urls which doesn't serve a Content-Length header.
https://filesamples.com/samples/audio/mp3/sample3.mp3
HTTP/1.1 200 OK
Date: Sat, 08 Aug 2020 11:53:15 GMT
Content-Type: audio/mpeg
Transfer-Encoding: chunked
Connection: close
Set-Cookie: __cfduid=d2a4be3535695af67cb7a7efe5add19bf1596887595; expires=Mon, 07-Sep-20 11:53:15 GMT; path=/; domain=.filesamples.com; HttpOnly; SameSite=Lax
Cache-Control: public, max-age=86400
Display: staticcontent_sol, staticcontent_sol
Etag: W/"5def04f1-19d6dd-gzip"
Last-Modified: Fri, 31 Jul 2020 21:52:34 GMT
Response: 200
Vary: Accept-Encoding
Vary: User-Agent,Origin,Accept-Encoding
X-Ezoic-Cdn: Miss
X-Middleton-Display: staticcontent_sol, staticcontent_sol
X-Middleton-Response: 200
CF-Cache-Status: HIT
Age: 24
cf-request-id: 046f8413ab0000e047449da200000001
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 5bf90932ae53e047-SEA
How can I get the content-length of the file without downloading the whole file?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63315223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript For Final Expression does not allow complex statements. Why? Reasons aside, I've discovered the following:
var lines = ["Line 1", "Line 2", "Line 3"], i = 0, line;
for (line[i]; i < lines.length; line = lines[i++]) {
console.log(line); //Outputs "Line 1" three times
}
for (line[i]; i < lines.length; i++, line = lines[i]) {
console.log(line); //Outputs "Line 1", "Line 2", "Line 3"
}
The only difference is separating out the i++ in the final-expression statement into two statements separated by commas (who thought of that syntax, BTW?! Shouldn't multiple statements be separated by semi-colons and wrapped in {}, like we use everywhere else? I digress...) So what gives Javascript? Is line=lines[i++] too complicated for you while your wrapping around that loop?
And before anyone asks why I can't just put the line=lines[i] inside, at the top of the loop: Because the first example is just elegant. It keeps things separated.
So my question stands: Why, Javascript, why?
A: The code you posted doesn't run.
The beginning of each for loop
for (line[i];
makes no sense.
Maybe you meant
for (line = lines[i];
?
var lines = ["Line 1", "Line 2", "Line 3"], i = 0, line;
for (line = lines[i]; i < lines.length; line = lines[i++]) {
console.log(line); //Outputs "Line 1" three times
}
i = 0;
for (line = lines[i]; i < lines.length; i++, line = lines[i]) {
console.log(line); //Outputs "Line 1", "Line 2", "Line 3"
}
In that case case 1 prints
line 1
line 1
line 2
And case 2 prints
line 1
line 2
line 3
As for why, i++ means
temp = i;
i = i + 1;
return temp;
so in the first case if i = 0 this part
line = lines[i++]
will be this
line = lines[0], i = i + 1
since temp in the example of what i++ actually means is 0 at the point it's used.
whereas in the second case
i++, line = lines[i]
You're doing the postincrement before it's used
To be clear i++ this is called post incrementing. The value of the expression is the value before it was incremented.
If you actually mean increment instead of postincrement use ++i
As for elegant, that's an opinion. It's not clear what you're trying to do and there are certainly reasons to use loops based on indices but just in case here's a few other ways to iterate
var lines = ["Line 1", "Line 2", "Line 3"];
// use a function
lines.forEach(function(line) {
console.log(line);
});
// use a function with arrow syntax
lines.forEach(line => {
console.log(line);
});
// and of course if you really want to use indices why is
// this not elegant?
for (let i = 0, len = lines.length; i < len; ++i) {
const line = lines[i];
console.log(line);
}
It's not clear to me why you think you're solution is elegant. I'd look at your solution and think it's obfusticated. In other words it's hard to understand and hard to understand is not elegant.
A:
Javascript For Final Expression does not allow complex statements. Why?
You answered your own question. The final-expression is an expression, not a statement. That is the way the language was designed. It goes back to the comma operator in C forty years ago, if not further.
If you want to assign line inside the for, you can write your loop this way:
const lines = [1, 2, 3];
for (let i = 0, line; line = lines[i], i < lines.length; i++) {
console.log(line);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43555407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: optimizing part of code with array constructor The following simple example code gives correct results. However, I'd like to optimize it or make it more efficient. The constructor array, y, that I create in order to generate the position line spacing works, but it is very clumsy looking and inconvenient since the numbers in it are very specific. I want to make the numbers in the y array more general variables that depend on the earlier defined parameters in my code. Here is the code and then I'll be more clear:
PROGRAM TestRuns
IMPLICIT NONE
INTEGER :: i, j, k !matrix indices (i,j), spatial index k
INTEGER,PARAMETER :: n=5 !matrix size
REAL, PARAMETER :: a = -6, b =6 !end points of grid
REAL :: h !step size on position grid
REAL :: y(0:6) = (/(k, k=-6,6,2)/) ! generating spatial grid array
DOUBLE PRECISION :: M(n,n) !nxn matrix
h = (b-a)/(n+1)
DO i = 1,n
DO j = 1,n
IF (i .EQ. j) THEN
M(i,j) = y(i)**2
ELSE
M(i,j) = 0
END IF
END DO
END DO
END PROGRAM TestRuns
Instead of having
REAL :: y(0:6) = (/(k, k=-6,6,2)/) ! this line of code works but is not helpful in generalizing my code at all.
I really want to write something more general such as :
REAL :: y(0:n+1) = (/(k, k=a,b,h)/)
I always specify, a,b,n first in my code, so from these parameters I want to be able to then calculate h and the array y. I don't want to have to automatically put the values of array y in by hand as I'm doing now.
A: You'll have discovered that your compiler doesn't like the line
REAL :: y(0:n+1) = (/(k, k=a,b,h)/)
Change it to
REAL :: y(0:n+1) = [(k, k=INT(a),INT(b),2)]
that is, make the lower and upper bounds for k into integers. I doubt that you will ever be able to measure any increase in efficiency, but this change might appeal to your notions of nice-looking and convenient code.
You might also want to tweak the way you initialise M. I'd have written your two loops as
M = 0.0
DO i = 1,n
M(i,i) = y(i)**2
END DO
Overall, though, your question is a bit vague so I'm not sure how satisfactory this answer will be. If not enough, clarify your question some more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60365341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: API Reference for chrome.devtools.network for my daily work I have to look a lot at network requests made by the browser and for a long while I used firebug to do that.
Firebug had a really cool at pleasent and clean way to show XHR requests in the console. The Firebug DevTools do not offer that same clear GUI and it is a lot of scrolling. The chrome devtools are better but also do not offer the same sort of firebug convenience.
So I want to write a extension for that myself to perfectly suit my needs but so far I am a little bit confused about the API reference that I found.
https://developer.chrome.com/extensions/devtools_network#method-getHAR
Maybe I am bit spoiled from C++ API references but that can't be the whole documentation of that API?
According to that page the whole network API consists of three functions?
I mean where has to be more somewhere but I was not able to found it on the google page hopefully somebody can point the way or enlighten me about that.
For example I added a chrome.devtools.network.onRequestFinished.addListener
which gives me request object but I was only able to get the body of the request how do you get the header information?
On that same page is a link to: http://www.softwareishard.com/blog/har-12-spec/#request and I thought: "Ok maybe that is the full documentation but it is only a blog post and the request object has as far as I can tell no request.headers variable.
I hope somebody can point the way.
Regards
Ruvi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48251120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c# copy directory during publish I want to copy a folder that's contained in another project into the publish directory during website publish, is this possible?
The reason for this is that I have a project with the SQL schema files for creating the database structure, ASP.NET membership schema, alongside some code to run the files against the database. I don't really like having these SQL files in my web project, that just seemed dirty. So I figured I'd store them somewhere else in the solution. But when I deploy I do need them in the publish directory.
A: Why not place these scripts in App_data? It will be deployed along with the rest of the website, and cannot be accessed via client web browsers. That's what it is there for, to store data associated with your website that you don't want to have in the root for security purposes.
A: You can include an extra folder for deployment with all its contents editing the publish profile: http://www.asp.net/mvc/tutorials/deployment/visual-studio-web-deployment/deploying-extra-files
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6641812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Extending Angular CLI tasks I'm trying to extend the default Angular CLI tasks, but I'm running into some roadblocks. At this point, I'm trying to extend it to add two additional tasks:
*
*Add in additional linting to support stylelint for CSS linting
*Add support for doiuse to ensure all styles written support the browsers we need to support
I have tried a few things so far, however none of them seem to work. I've also taken a look at the material-2 angular-cli-build.js file, and have been able to get doiuse to work in a modified version of it, however it's still problematic and not properly catching errors when it finds invalid CSS.
Has anybody had any luck or have any tips they can suggest for extending the Angular CLI tasks?
A: As stated here, you can extend the build script as ember-cli.
You can also look at the ember-cli user guide for built in configurations that you can use without making any extension first
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37889045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Why does the entire page jump when an input is selected in Mobile Safari? I have a fixed form that is layered on top of the body using fixed positioning.
This full screen takeover approach works fine on Chrome and Safari desktop, but on mobile it is shifting the entire page in order to compensate for the keyboard appearing. Wondering if this is fixable without JS.
<!--CSS-->
.test-form {
background-color: #fff;
padding: 40px;
color: #333;
position: relative;
}
::-webkit-scrollbar {
display: none;
}
.test-form.open {
top: 0;
margin: 0;
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
z-index: 200;
border: 1px solid red;
background-color: #ddd;
overflow: hidden;
}
.test-form label {
display: block;
}
.test-form input {
display: block;
}
.test-form.open .test-form__content {
position: absolute;
top: 10px;
bottom: 10px;
left: 20px;
right: 20px;
padding: 20px;
border: 1px solid yellow;
width: auto;
height: auto;
background-color: #eee;
overflow-y: scroll;
}
<!--TEST FORM-->
<div class="test-form open">
<div class="test-form__content">
<div class="filler">
<p>
"I Want You Back"
Uh-huh huh huhhh
Let me tell ya now
Uh-huh
(Mmhhmmm)
When I had you to myself, I didn't want you around
Those pretty faces always made you stand out in a crowd
But someone picked you from the bunch, one glance was all it took
Now it's much too late for me to take a second look
Oh baby, I need one more chance, hah
I tell you that I love you
Baby, oh! Baby, oh! Baby, oh!
I want you back!
I want you back!
[Fade out]
</p>
</div>
<form>
<label>Input One</label>
<input type="text" name="one" placeholder="Input Here">
<br>
<label>Input Two</label>
<input type="text" name="two" placeholder="Input Here">
<br>
<label>Input Three</label>
<input type="text" name="three" placeholder="Input Here">
<br>
<label>Input Four</label>
<input type="text" name="four" placeholder="Input Here">
<br>
<label>Input Five</label>
<input type="text" name="five" placeholder="Input Here">
</form>
</div>
</div>
<h1>footer</h1>
</body>
I have seen the article on focus jumping and other issues with using fixed elements in iOS Safari, but I have not been able to come up with a solution.
JSFiddle below (preview the raw results iOS simulator and select different inputs, you will see the app jumping up and down):
https://jsfiddle.net/a01tnona/
View a screengrab:
http://cl.ly/1C0S153C0R0J
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34767594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to alert user with local notifications when the value in label is under threshold in Swift 4? I'm trying to alert the user with local notification when randomly generated integer value is more than the label's text value in Swift 4. I have looked for answers in Google even though I implemented them to my problem as required I couldn't solve it. Here is my code:
import UIKit
import Dispatch
import QuartzCore
import UserNotifications
class ViewController: UIViewController {
var alertButton: UIButton {
let button = UIButton(frame: CGRect(x: 100, y: 150, width: UIScreen.main.bounds.width / 2, height: 100))
button.setTitle("Show Alert", for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: #selector(showAlert), for: .touchUpInside)
return button
}
var valueLabel: UILabel {
let label = UILabel(frame: CGRect(x: 250, y: 300, width: 150, height: 150))
label.text = "Value"
label.textColor = UIColor.black
return label
}
var value: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(alertButton)
self.view.addSubview(valueLabel)
UNUserNotificationCenter.current().delegate = self
requestSettings()
//let link = CADisplayLink(target: self, selector: #selector(updateLabels))
//link.add(to: .main, forMode: .default)
Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.updateLabels), userInfo: nil, repeats: true)
}
private func requestAuthorization(completionHandler: @escaping (_ success: Bool) -> ()) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) { (success, error) in
if let error = error {
print("Auth request failed. \(error) \(error.localizedDescription)")
}
completionHandler(success)
}
}
private func requestSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .notDetermined:
self.requestAuthorization { (success) in
guard success else { return }
self.scheduleNotification()
}
case .denied:
print("App not allowed to display notification")
case .authorized:
self.scheduleNotification()
case .provisional:
self.scheduleNotification()
}
}
}
@objc func updateLabels() {
self.value = Int.random(in: 1...50)
print("\(self.value)")
DispatchQueue.main.async {
self.valueLabel.text = "\(self.value)"
}
}
@objc func showAlert() {
var val: String = ""
let alert = UIAlertController(title: "Threshold", message: nil, preferredStyle: .alert)
alert.addTextField(configurationHandler: { (textField) in
textField.placeholder = "Enter an integer value:"
})
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
val = (alert.textFields?.first!.text)!
if self.value > Int(val)! {
self.scheduleNotification()
}
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
private func scheduleNotification() {
let content = UNMutableNotificationContent()
content.title = "App"
content.subtitle = "WARNING!"
content.body = "Threshold value is passed"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "notification_id", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("\(error) \(error.localizedDescription)")
}
}
}
}
extension ViewController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert])
}
}
Any help is appreciated.
Update: I tried implementing local push notification. But my problem is that i can't push it to the user depending on the condition i mentioned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58517308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pandas correlation between two string column I am not sure if the title is correctly interprits what I want. let me explain.
please consider the mwe I am using
dataset = pd.read_csv("tmp.csv").astype('string')
print(dataset.head())
print(dataset.groupby('c2').size())
print(dataset.groupby('c1').size())
to read a csv file like:
name,c1,c2
foo,q1,p1
bar,q1,p2
qoo,q2,p1
soo,q3,p1
doo,q1,p1
too,q2,p2
Now, I want to find among all p1, how many of them belongs to q1, how many of them are in q2 and so on.
Like in above csv, out of 4 p1, 2 is from q1,1 is from q2 and 1 is from q3. I want to get that number and plot as a pie chart.
A: IIUC:
you need value_counts()+reset_index()
out=df.value_counts(subset=['c2','c1']).reset_index(name='count')
output of out:
c2 c1 count
0 p1 q1 2
1 p1 q2 1
2 p1 q3 1
3 p2 q1 1
4 p2 q2 1
If you need piechart(decorate it according to your need):
df.value_counts(subset=['c2','c1']).plot(kind='pie',autopct='%.2f%%')
output:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68741930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Run javascript first and on success run code behind In Asp page i have below controls. A input textbox ,Imagebutton and a label.
<input id="txtTotamt" runat="server" type="text" value="0" />
<asp:ImageButton ID="Validate" runat="server" OnClientClick="return validatecontrol();"/>
<asp:Label ID="lblerror" runat="server"></asp:Label>
And in javascript in page
<script language="javascript" type="text/javascript">
function validatecontrol()
{
var valid_amt = document.getElementById("txtTotamt").value;
if isNaN(valid_amt) == false {
if(valid_amt % 1 != 0) && (valid_amt>0){
return true;
}else{
document.getElementById("lblerror").innerHTML ="Error";
}
}else{
document.getElementById("lblerror").innerHTML ="Error";
}
}
</script>
In code behind
Protected Sub Validate_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Validate.Click
//my codes go here
End Sub
I want to validate the content of textbox in a JavaScript and I also have code behind for that button click.I want scrip to be executed first and if the text in input text not proper then code behind should not execute. But it does not work for me. I think the code behind in .net gets triggered before the JavaScript. How it can be solved? Is there any error in my javascript?
A: Your if statement is missing its brackets.
In javascript, all if statements are expected to be wrapped in standard brackets. Without these you will get a syntax error.
the standard is:
if ( /*your if comparison here e.g 1 == 1*/) {
} else {
}
Try changing:
if isNaN(valid_amt) == false {
to:
if (isNaN(valid_amt) == false) {
Same for:
if(valid_amt % 1 != 0) && (valid_amt>0){
to
if((valid_amt % 1 != 0) && (valid_amt>0)){
A: Try to replace these lines
if isNaN(valid_amt) == false {
with
if (!isNan(valid_amt) || valid_amt!=undefined) {
A: first you have to send to the isNan() function the value of the valid_amt:
if isNaN(valid_amt.value) == false
and also, in order to avoid calling the server function when the validation is invalid, add return false; to the else statement:
<script language="javascript" type="text/javascript">
function validatecontrol()
{
var valid_amt = document.getElementById("txtTotamt");
if isNaN(valid_amt.value) == false {
if(valid_amt % 1 != 0) && (valid_amt>0){
return true;
}else{
document.getElementById("lblerror").innerHTML ="Error";
return false;
}
}else{
document.getElementById("lblerror").innerHTML ="Error";
return false;
}
}
</script>
A: Please modify your script as:
<script type="text/javascript">
function validatecontrol()
{
var valid_amt = document.getElementById("txtTotamt");
if (isNaN(valid_amt) == false)
{
if((valid_amt % 1 != 0) && (valid_amt>0))
{
return true;
}
else
{
document.getElementById("lblerror").innerHTML ="Error";
return false;
}
}
else
{
document.getElementById("lblerror").innerHTML ="Error";
return false;
}
}
</script>
A: Two corrections in aspx code ..
*
*OnClientClick="Javascript:return validatecontrol();"
*OnClick="Validate_Click"
asp:ImageButton ID="Validate" runat="server" OnClientClick="Javascript:return validatecontrol();" OnClick="Validate_Click" />
& one correction in Javascript function
use return false; in else part of javascript function. If value is not appropriate then it will stop further processing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23601480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to open openssl.cnf, but it just worked I'm running Debian 8. I created a signing request and then decided I wanted to change the FQDN so I deleted everything in my /ssl folder.
I then tried to run the same command again and and received the error:
WARNING: can't open config file: /usr/lib/ssl/openssl.cnf
Unable to load config info from /usr/lib/ssl/openssl.cnf
I then reinstalled OpenSSL thinking that my fix it but it didn't.
Any suggestions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41888411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I check if solr is running or no using python? I am using pysolr library and I want to check if solr is running or no
and to switch between solr and other search engine.
I found similar question and I tried many suggestions and didn't work.
How to know whether solr server is running or not
How do i check cassandra and solr is up?
Python code to check if service is running or not.?
A: A clean way is using pysolr
import pysolr
# Create a client instance. The timeout and authentication options are not required.
solr = pysolr.Solr('http://localhost:8983/solr/')
# Do a health check.
ping = solr.ping()
resp = json.loads(ping)
if resp.get('status') == 'OK':
print('success')
A: if the code below error(connection refused), solr is not working.
gettingstarted is an example collective name in the link.
from urllib.request import *
connection = urlopen('http://localhost:8983/solr/gettingstarted/select?q=mebus&wt=python')
response = eval(connection.read())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61334504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Progress dialogue and toast failing on sending HTTP Post through MultipartEntity I am still relatively an amateur at android programming. I have a very annoying issue. When i click send in my class it doesn't show a progress dialogue and it also ignores my validations that I have for 2 edit text buttons that I have. My code might be very messy and unorganized. i apologize in advance.
What i need to do is show my progress dialogue running and on the end of the Handler get it to dismiss. Also I need my toast to show and the class to stop working.
public class share extends Activity {
ProgressDialog dialog;
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://api...");
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.send);
Button Deliver;
Deliver = (Button) findViewById (R.id.Send);
Deliver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final ProgressDialog dialog = ProgressDialog.show(share.this, "","Uploading...", true);
dialog.show();
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
EditText etxt_user = (EditText) findViewById(R.id.user_email);
EditText etxt_pass = (EditText) findViewById(R.id.friend_email);
if(file == null){
Toast display = Toast.makeText(share.this, "There are no videos to send", Toast.LENGTH_SHORT);
display.setGravity(Gravity.BOTTOM|Gravity.LEFT, 0, 0);
display.show();
startActivity(new Intent("android.main.SHARE"));
}
else{
Pattern pattern= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +"\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +")+"
);
Matcher matcher=pattern.matcher(etxt_user.getText().toString());// match the contents of the first edit text
Matcher matcher1=pattern.matcher(etxt_pass.getText().toString());
if (!matcher.matches()&&(etxt_user.getText().toString()==null))
{
Toast display1 = Toast.makeText(share.this, "Please enter correct email address", Toast.LENGTH_SHORT);
display1.show();
startActivity(new Intent("com..SHARE"));
}
else
{
//proceed with program
}
if (!matcher1.matches()&&!(etxt_pass.getText().toString()==null)){
Toast display2= Toast.makeText(share.this, "You entered wrong email Format in the second box", Toast.LENGTH_LONG);
display2.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
startActivity(new Intent("com.apapa.vrsixty.SHARE"));
}
else
{
//proceed
}
try{
MultipartEntity me = new MultipartEntity();
me.addPart("file", new FileBody(new File("/sdcard/videocapture_example.H264")));
me.addPart("userEmail", new StringBody(etxt_user.getText().toString()));
me.addPart("friendEmail", new StringBody(etxt_pass.getText().toString()));
httppost.setEntity(me);
HttpResponse responsePOST = client.execute(httppost);
HttpEntity resEntity = responsePOST.getEntity();
InputStream inputstream = resEntity.getContent();
BufferedReader buffered = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder stringbuilder = new StringBuilder();
String currentline = null;
while ((currentline = buffered.readLine()) != null) {
stringbuilder.append(currentline + "\n");
String result = stringbuilder.toString();
Log.v("HTTP UPLOAD REQUEST",result);
inputstream.close(); } }
catch (Exception e) {
e.printStackTrace();
}
}dialog.dismiss();
}
});
}
});
When I am done with this and I press send, it gives me a black screen with no progress dialogue and even if I have validations in place for my edit text or if there is no file to send, it just runs the program without stopping it and showing a toast. Thank you in advance guys
A: Well it looks like your httppost is sending it to "http://", which is not exactly a valid address, which is part of your problem.
Also: Is that code verbatim? There is no way it should run. at the very beginning you have this line
new HttpPost("http://"");
You have two quotes at the end, which effectively makes everything after the second quote a string until it runs into a closing quote.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6915858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Row Below - Making Three Spinners and Player Adds or Chooses Without Using the Same Name Good morning fellas. This is me again, David Dimalanta. I'm here for a question. I need to create a program that if all three players got different names, the confirmation will say on the toast "Process complete." But instead, even all were not having the same name.
Steps:
*
*Each player chooses a name from the spinner.
*The value is written onto the string.
*When button clicked, the process evaluates for similarity aliases (names).
*If similar, at least two, the toast message will say "Please specify a different username."
*If not, then it's complete.
And, my activity name is "Player_3_at_Spinner_Menu.java". Here's my code for the first part under this class:
//Spinners for Players
private Spinner spinner_1;
private Spinner spinner_2;
private Spinner spinner_3;
//Button to Start
private Button play_it;
//For Displaying Text
private String SUMMON_PICK_UP_1, SUMMON_PICK_UP_2, SUMMON_PICK_UP_3;
private String cplayer_1, cplayer_2, cplayer_3;
//Text Response from a Spinner
public final static String EXTRA_MESSAGE_1 = "com.example.databasetestvertwo.MESSAGE1";
public final static String EXTRA_MESSAGE_2 = "com.example.databasetestvertwo.MESSAGE2";
public final static String EXTRA_MESSAGE_3 = "com.example.databasetestvertwo.MESSAGE3";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.players_3);
//Searching for ID... (Button)
play_it = (Button) findViewById(R.id.START_GAME);
//Adding listener to the button(s).
play_it.setOnClickListener(new trigger_happy_start());
//Call from the Database_Handler.class to call the database.
Database_Handler db = new Database_Handler(getApplicationContext());
//Then, load the content and...
loadSpinnerData();
}
//Insert the value from the database into each of the spinners.
private void loadSpinnerData()
{
//Initialize the spinners.
spinner_1 = (Spinner) findViewById(R.id.player_1_spinner);
spinner_2 = (Spinner) findViewById(R.id.player_2_spinner);
spinner_3 = (Spinner) findViewById(R.id.player_3_spinner);
Database_Handler db = new Database_Handler(getApplicationContext());
List<String> lables = db.getAllLabels();
//Creating an adapter for the spinner...
ArrayAdapter<String> data_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lables);
data_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Inserts the spinners by a database.
spinner_1.setAdapter(data_adapter);
spinner_2.setAdapter(data_adapter);
spinner_3.setAdapter(data_adapter);
}
//Action applied if a user chose this item. (Player 1)
public class response_1 implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SUMMON_PICK_UP_1 = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "You selected: " + SUMMON_PICK_UP_1, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
//Do nothing. I guess...
}
}
//Action applied if a user chose this item. (Player 2)
public class response_2 implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent_2, View view, int position, long id)
{
SUMMON_PICK_UP_2 = parent_2.getItemAtPosition(position).toString();
Toast.makeText(parent_2.getContext(), "You selected: " + SUMMON_PICK_UP_2, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
}
//Action applied if a user chose this item. (Player 3)
public class response_3 implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent_3, View view, int position, long id)
{
SUMMON_PICK_UP_3 = parent_3.getItemAtPosition(position).toString();
Toast.makeText(parent_3.getContext(), "You selected: " + SUMMON_PICK_UP_2, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
}
And, here's the code for checking if all, or at least two, players got the same name, the process warns them not to use the same name under this activity also. Here's my code:
private class trigger_happy_start implements OnClickListener
{
public void onClick(View v)
{
//Checks if the names assigned on each spinner have a the same name.
if
(
SUMMON_PICK_UP_1 == SUMMON_PICK_UP_2 ||
SUMMON_PICK_UP_1 == SUMMON_PICK_UP_3 ||
SUMMON_PICK_UP_2 == SUMMON_PICK_UP_3
)
{
Toast.makeText(getApplicationContext(), "Please specify a different username.", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Process complete, idiot.", Toast.LENGTH_SHORT).show();
}
}
}
A: I don't see any problem with your application's logic.
However, you forgot to set Spinner's onItemSelected:
spinner1.setOnItemSelectedListener( new response_1());
spinner2.setOnItemSelectedListener( new response_2());
spinner3.setOnItemSelectedListener( new response_3());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11732668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rigid Body Collision Relative Velocity Calculation This is my code:
Vec2 fv = nv.scale(-((1D + aelas) * getLinearVelocity().sub(shape.getLinearVelocity()).dot(nv)));
aelas is a double, set to 1D(later on I can change to a function)
nv is the unit-normal-vector
My issue is that the collision only properly reacts with perfect elasticity when aelas is 0, but when it is 1, it treats it as if the elasticity is >2D(so, more energy goes out then comes in).
My thinking is that my system for relative velocity is incorrect, causing it to improperly react.
I have thoroughly debugged my code, and am fairly certain that it is my math. Anyone care to share some insight?
Vec2 Class:
package JavaProphet.Profis.Geometry;
/**
* Created by JavaProphet on 12/8/13 at 12:28 PM.
*/
public class Vec2 {
private final double x;
private final double y;
public static final Vec2 ZERO_VEC = new Vec2(0D, 0D);
/**
* Empty Vector.
*/
public Vec2() {
x = 0D;
y = 0D;
}
public String toString() {
return "<" + getX() + ", " + getY() + ">";
}
/**
* Uses basic trigonometry to create a Vec2 from a radian.
*
* @param rad The radian.
*/
public Vec2(double rad) {
x = Math.sin(rad);
y = Math.cos(rad);
}
/**
* Assigns a vector it's value.
*/
public Vec2(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Assigns a vector it's value from a double array of length 2.
*/
public Vec2(double v[]) {
this.x = v[0];
this.y = v[1];
}
/**
* Assigns a vector it's value from subtraction of position.
*
* @param x x1
* @param x2 x2
* @param y y1
* @param y2 y
*/
public Vec2(double x, double y, double x2, double y2) {
this.x = x2 - x;
this.y = y2 - y;
}
/**
* @return The x value from the vector.
*/
public double getX() {
return x;
}
/**
* @return The y value from the vector.
*/
public double getY() {
return y;
}
/**
* Adds two vectors.
*/
public Vec2 add(Vec2 vec) {
return new Vec2(getX() + vec.getX(), getY() + vec.getY());
}
/**
* Subtracts two vectors.
*/
public Vec2 sub(Vec2 vec) {
return new Vec2(getX() - vec.getX(), getY() - vec.getY());
}
/**
* Performs a dot product on two vectors.
*/
public double dot(Vec2 vec) {
return getX() * vec.getX() + getY() * vec.getY();
}
/**
* Scales magnitude of a vector by a scalar.
*
* @param sc The scalar.
*/
public Vec2 scale(double sc) {
return new Vec2(getX() * sc, getY() * sc);
}
/**
* Scales magnitude of a vector by two scalars.
*
* @param x The x scalar.
* @param y The y scalar.
*/
public Vec2 scale(double x, double y) {
return new Vec2(getX() * x, getY() * y);
}
public boolean equals(Vec2 vec) {
return vec.getX() == getX() && vec.getY() == getY();
}
public double relativeCosine(Vec2 vec) {
double d = dot(vec);
double rc = d / (getMagnitude() * vec.getMagnitude());
return rc;
}
public double relativeRadian(Vec2 vec) {
return Math.acos(relativeCosine(vec));
}
public double getRot() {
return Math.atan2(getY(), getX());
}
/**
* Rotates the vector around the origin.
*
* @param rad A radian to rotate by.
* @return The result.
*/
public Vec2 rot(double rad) {
double sin = Math.sin(rad);
double cos = Math.cos(rad);
double t1 = ((cos * getX()) - (sin * getY()));
double t2 = ((sin * getX()) + (cos * getY()));
return new Vec2(t1, t2);
}
/**
* Retrieves the slope for this vector.
*
* @param vec A vector in which is paired to make a line segment.
* @return A slope.
*/
public double slope(Vec2 vec) {
return (vec.getX() - getX()) / (vec.getY() - getY());
}
/**
* Scales magnitude of a vector to a tracable amount. (1 / x, 1 / y)
*/
public Vec2 tscale() {
return new Vec2(1D / getX(), 1D / getY());
}
/**
* Inverts a vector(-x, -y).
*/
public Vec2 invert() {
return new Vec2(-getX(), -getY());
}
private double mag = 0D; // magnitude cannot be 0, so if zero, calc mag.
/**
* Return the length, or magnitude of a vector, uses sqrt.
*/
public double getMagnitude() {
if(mag == 0D && (getX() != 0D || getY() != 0D)) {
mag = Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2));
}
return mag;
}
/**
* Converts a vector to a unit vector (x / length, y / length), uses sqrt.
*/
public Vec2 uscale() {
double length = getMagnitude();
return new Vec2(getX() / length, getY() / length);
}
/**
* Converts a vector to a unit vector (x / length, y / length), uses sqrt.
*/
public Vec2 hat() {
return uscale();
}
}
A: For rigid body physics, this code line is entirely correct IF fv is going to be added to the existing velocity of this, and the shape is an infinite mass boundary.
If your other code is trying to use fv as 'final velocity', it shouldn't have the constant 1 in it's calculation (and is simply wrong in oblique collisions anyway).
For extension to finite mass pair collisions the 1D constant turns into a signed weighting function, which I'll leave as an exercise for the reader.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21034289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: View not updating on variable change in Ionic 2 and Angular 2 I'm new to using Angular 2 so I may just not be understanding what's wrong. However, I have an *ngIf that is supposed to show a button if a variable is false and not show the button if the variable is true.
However once I've updated the variable to true, the button does not go away. Any help is greatly appreciated.
Code:
HTML
ion-slide>
<h1> Uber Button </h1>
<button ion-button color="dark" *ngIf="!uberSettings?.uberActivated" (click)="userSettings.connectUber()">Activate Uber</button>
</ion-slide>
COMPONENT:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HomePage } from '../home/home';
import { UserSettings} from '../../providers/user-settings'
@Component({
selector: 'page-setup',
templateUrl: 'set-up.html'
})
export class SetUpPage {
constructor(public navCtrl: NavController, private userSettings: UserSettings) {
}
goToHome(){
this.navCtrl.setRoot(HomePage);
}
}
SERVICE:
declare
var window: any;
@Injectable()
export class UserSettings {
authorizationCode: string;
uberData: any;
uberSettings: UberSettings;
result: any;
constructor(public http: Http, private platform: Platform, public storage: Storage) {
console.log('called uberSettings Constructor');
storage.ready().then(() => {
storage.get('uberSettings').then((val) => {
console.log('the val is' + val);
if (val == null) {
console.log('val equaled null');
this.uberSettings = {
buttonOn: false,
uberActivated: false,
token: null,
refreshToken: null,
long: null,
lat: null,
}
console.log(this.uberSettings);
storage.set('uberSettings', this.uberSettings);
// this.uberSettings.uberActivated = true;
// // this.uberSettings.token= val.token;
} else {
console.log("there was a value for Val");
this.uberSettings = val
console.log(this.uberSettings);
}
})
.catch(err => {
console.log('we dont have an uber token yet' + JSON.stringify(err));
});
});
}
public connectUber() {
this.platform.ready().then(() => {
this.uberLogin().then(success => {
this.authorizationCode = success;
console.log(this.authorizationCode);
this.token()
}, (error) => {
alert(error);
});
});
}
token() {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
// let body = 'client_id=3ibytPcye4w3_-0txknyO7ptD-MfFMkn&client_secret=2Kp8O54mGvlOoBm6IPX_0gKBmJ_mODSo7FqPbbA9&redirect_uri=http://localhost:8100/callback&grant_type=authorization_code&code=' + this.authorizationCode
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('client_id', <CLIENT ID>);
urlSearchParams.append('client_secret', <CLIENT SECRET>);
urlSearchParams.append('redirect_uri', 'http://localhost:8100/callback');
urlSearchParams.append('grant_type', 'authorization_code');
urlSearchParams.append('code', this.authorizationCode);
let body = urlSearchParams.toString()
return this.http.post(`https://login.uber.com/oauth/v2/token`, body, {
headers: headers
})
.map(response => response.json())
.subscribe(result => {
this.result = result
console.log(this.result);
this.uberSettings.token = this.result.access_token;
this.uberSettings.refreshToken = this.result.refresh_token;
this.uberSettings.uberActivated = true;
this.uberSettings.buttonOn = true;
console.log(this.uberSettings);
});
public uberLogin(): Promise < any > {
return new Promise(function(resolve, reject) {
var browserRef = window.cordova.InAppBrowser.open("https://login.uber.com/oauth/v2/authorize?client_id=3ibytPcye4w3_-0txknyO7ptD-MfFMkn&response_type=code", "_blank", "location=no,clearsessioncache=yes,clearcache=yes");
browserRef.addEventListener("loadstart", (event) => {
if ((event.url).indexOf("http://localhost:8100/callback") === 0) {
browserRef.removeEventListener("exit", (event) => {});
browserRef.close();
var responseParameters = ((event.url).split("code="));
var parsedResponse = responseParameters[1].split("#");
if (parsedResponse[0] !== undefined && parsedResponse[0] !== null) {
resolve(parsedResponse[0]);
} else {
reject("Problem authenticating with Uber");
}
}
});
browserRef.addEventListener("exit", function(event) {
reject("The Uber sign in flow was canceled");
});
});
}
}
So if you look at the service code I am updating this.uberSettings when token() is called and the console shows that this.uberSettings.uberActivated has been changed to true. However, I don't understand why the button still shows then. Any help would be greatly appreciated. Thank you!
A: Your ngIf is not referencing your service. I think you have a typo :)
*ngIf="!userSettings.uberSettings?.uberActivated"
instead of
*ngIf="!uberSettings?.uberActivated"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43905921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript libraries for typeahead / autocomplete in textarea, any recommendation? can anyone recommend a Javascript library to support typeahead in textarea?
*
*It should only perform autocomplete when trigger character like @ is
entered.
*Once match is found it should REMOVE the trigger character.
*Angular support is ideal, other frameworks are also considered
I found some typeahead examples on the web but none of them seem to match my criteria. Does anyone have any idea or does such library actually exist? Thanks!
A: I'll answer my own question mentio for angular does this job quite well
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36939814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sweet Alert confirm with Node JS and Express I have a Node JS/Express app using .EJS templates and I'm using the following code to popup standard 'Are You Sure' messages before editing or deleting a record. Both of these are working fine:
<a id="edit-form" href="/blog/<%-blog._id%>/edit" onclick="return confirm('Are you sure you wish to edit this blog post?');">
<div class="new-show-icons"><i class="far fa-edit"></i></div>
</a>
<form id="btn-form" action="/blog/<%- blog._id %>?_method=DELETE" method="POST" onclick="return confirm('Are you sure you wish to delete this blog post?');">
<div class="new-show-icons"><i class="far fa-trash-alt"></i></div>
</form>
Here is a the JS code I have so far for the popups, but I'm unsure 1) how to replace these to popup up in place of the standard html confirm message, and 2) how to specify what action should be taken if the user confirms or cancels (in case of edit, bring them to the edit page, and in case of delete, direct delete the record). Any help is appreciated. Thanks
function areYouSureEdit() {
swal({
title: "Are you sure you wish to edit this record?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
closeOnConfirm: false,
},
function(){
});
};
function areYouSureDelete() {
swal({
title: "Are you sure you wish to delete this record?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, delete it!',
closeOnConfirm: false,
},
function(){
swal("Deleted!", "Your imaginary file has been deleted!", "success");
});
};
However, I would like to make sure of 'Sweet Alert' confirm messages, which I am struggling with.
A: SweetAlert uses promises to keep track of how the user interacts with the alert.
If the user clicks the confirm button, the promise resolves to true. If the alert is dismissed (by clicking outside of it), the promise resolves to null. (ref)
So, as there guide
function areYouSureEdit() {
swal({
title: "Are you sure you wish to edit this record?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
closeOnConfirm: false,
}.then((value) => {
if(value){
//bring edit page
}else{
//write what you want to do
}
}) };
function areYouSureDelete() {
swal({
title: "Are you sure you wish to delete this record?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, delete it!',
closeOnConfirm: false,
}.then((value) => {
if(value){
//ajax call or other action to delete the blog
swal("Deleted!", "Your imaginary file has been deleted!", "success");
}else{
//write what you want to do
}
})); };
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60359335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I check whether remote directory exist or not on SFtp using nodejs? I need to check whether a remote directory exists or not on sFtp connection.
I am using the condition like,
if (!sftp.Exists(remotePath))
I am using the library ssh2-sftp-client but it doesn't allow me to use the Exist methods because it doesn't have that function.
Can anybody suggest me what should I do for checking for remote directory exist or not?
A: Use list
sftp.list(remotePath);
It will (asynchronously) trigger an error if the file doesn't exist
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52183264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to stop elements moving other elements when positioned absolutely? Using css, I'm trying to position my dropdown menu in mobile but there are some issues.
*
*I've rotated it 270 degrees and this has left a space after it on the on right which increases page width.
*I'd like to position it absolutely but doing so requires negative margin-left, or margin right, which moves the line separating head and body to the right.
So do I position it absolutely, stop the white space appearing to the left and stop it moving other elements?
I've tried to reduce its width, which has no effect, and the further left I move it, the further left the grey line separating head and body goes.
Here is my working CSS.
@media(max-width: 768px). {
.dropdown {
position: absolute;
transform: rotate(270deg);
right: 50%
margin-left: 110px;
}
}
HTML
<i class="fa fa-bars"></i>
</div>
<div class="module-group right">
<div class="module left">
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul id="menu" class="menu"><li id="menu-it
em-3530" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-3530 dropdown"><a title="Contact" href="https://4309.co.uk/contact/">Contact
<ul role="menu" class=" dropdown-menu">
<li id="menu-item-12515" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12515"><a title="DRAWING DEVELOPMENT" href="https://4309.co.uk/drawing-development/">DRAWING DEVELOPMENT</a></li>
<li id="menu-item-2997" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-2997"><a title="SKETCHES" href="https://4309.co.uk/sketches-life-drawing/">SKETCHES</a></li>
Here is a link to my personal site
Basically I'm also trying to make it device compatible for all mobile handsets(responsive)
There are some side issues too, which are that one of the menu items rides up the page in certain devices.
When the menu is opened, there is a the big white space, when closed the space disappears.
The menu also moves according to which page you're on, not sure how that happens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60676408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: login form needs to go to more form pages hi i have a login system that needs to go to multiple pages.
3 pages baroverzicht,keukenoverzicht,tafeloverzicht. if i login i go to tafeloverzicht with all users. i dont know how to fix it i just start coding
SQL server i have a table: Personeel
naam:----
password:----
afdelling: bar, keuken, bediening
bar needs to go to baroverzicht keuken needs to go to keukenoverzicht
bediening needs to go to tafeloverzicht
private void button1_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager
.ConnectionStrings["ReserveringenConnectionStringSQL"]
.ConnectionString;
SqlConnection conn = new SqlConnection(connString);
//----
//sql datbase connectie
//----
conn.Open();
SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord =" + textBox1.Text + "", conn);
tabel personeel(wachtwoord) op de vragen
SqlDataReader dr = cmd.ExecuteReader();
int count = 0;
while(dr.Read())
{
count += 1;
}
if (count ==1)
{
MessageBox.Show("OK");
this.Hide();
tafeloverzicht tafeloverzicht = new tafeloverzicht();
tafeloverzicht.Show();
}
else if (count > 0)
{
MessageBox.Show("");
}
else
{
MessageBox.Show("wachtwoord niet corect");
}
textBox1.Clear();
conn.Close();
}
}
}
A: Next to your question there are some other things to take into account:
a. Always use Parameters when creating Sql:
SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord = @Password", conn);
cmd.Parameters.Add("@Password", password)
b. Put your database methods in a separate class (Encapsulation, etc.) --> example: ReserverationsDataAccess
c. To answer your main question we'll need some more info (see comments).
A: i have made some changes to the code now.
SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord =" + textBox1.Text + "", conn);
SqlDataReader dr = cmd.ExecuteReader();
int count = 0;
while(dr.Read())
{
count += 1;
}
if (count ==1)
{
SqlCommand cmd1 = new SqlCommand("select afdeling from personeel where wachtwoord =" + textBox1.Text + "", conn);
SqlDataReader dr1 = cmd1.ExecuteReader();
MessageBox.Show("OK");
if (dr1.Rows[0][0].ToString() == "keuken")
{
this.Hide();
keukenoverzicht keukenoverzicht = new keukenoverzicht();
keukenoverzicht.Show();
}
else if (dr1.Rows[0][0].ToString() == "bar")
{
this.Hide();
baroverzicht baroverzicht = new baroverzicht();
baroverzicht.Show();
}
else
{
this.Hide();
tafeloverzicht tafeloverzicht = new tafeloverzicht();
tafeloverzicht.Show();
}
}
else
{
MessageBox.Show("wachtwoord niet corect");
}
textBox1.Clear();
conn.Close();
}
}
it have now 2 errors on dr1.rows
-a-
what needs to be changed to fix the error (rows)
-b-
cmd.Parameters.Add("@Password", password) is for ****** in the textbox ride?
error rows
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34493396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mootools setting up Event on for loop I have a problem concerning Mootools event-handling...
having a situation you have a loop and for each cycle creating an div and attaching an event on it. It always takes the value of the last cycle of the loop.
Like:
for(var i=0;i<10;i++) {
var el = new Element('div').inject($(document.root));
el.addEvent('click',function() {
alert(i);
});
}
All Elements will alert '10'. What I want is to have every new element counting +1.
Frist=0, second=1, ...
Hope someone understands what I mean.
Thx in advance!
A: use a closure to encapsulate the iterator at the time of adding into a local variable:
for(var i=0;i<10;i++) {
var el = new Element('div').inject($(document.root));
(function(i){
el.addEvent('click',function() {
alert(i);
});
}(i));
}
school of thought says you should not create functions in a loop.
other things you can do is pass the iterator to the constructor and keep it in storage:
var el = new Element('div').store('index', i).inject(document.body);
...
click: function(){
console.log(this.retrieve('index'));
}
you can also use a .each which automatically does an iterator for you:
var a = new Array(10);
a.forEach(function(item, index){
new Element('div', {
events: {
click: function(){
alert(index);
}
}
}).inject(document.body);
});
you could bind it to the callback also... many many patterns.
A: Found a workaround, not sure if it fits what you want.
Check fiddle here
JS/Mootools:
for(var i=0;i<10;i++) {
var el = new Element('div', {onclick: 'alert('+i+')',text:i}).inject(document.body);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17315196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Docker unable to copy .git folder When trying to generate a file called head with the current commit hash during a docker build (for internal .NET service versioning) it seems that docker is unable to pull the .git folder into the image at all.
Given the following DockerFile
FROM alpine/git AS version
WORKDIR /src
COPY .git/ ./.git/
RUN git rev-parse HEAD > head
This happens:
=> ERROR [version 2/4] COPY .git/ ./.git/ 0.0s
------
> [version 2/4] COPY .git/ ./.git/:
------
failed to compute cache key: "/.git" not found: not found
What is perhaps more interesting is that when using COPY . . it fails like so:
=> ERROR [version 4/4] RUN git rev-parse HEAD > head 1.7s
------
> [version 4/4] RUN git rev-parse HEAD > head:
#36 1.613 fatal: not a git repository (or any of the parent directories): .git
------
executor failed running [/bin/sh -c git rev-parse HEAD > head]: exit code: 128
The git folder is at the same root as the Dockerfile as ls -Force (windows powershell version of ls -a) the following result is returned (a few folders redacted for privacy):
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 11/4/2020 2:45 PM .ci
d--h-- 3/17/2021 3:06 PM .git
d----- 2/3/2021 6:12 PM .github
d----- 9/8/2020 7:22 PM .idea
d----- 1/20/2021 1:50 PM .run
d--h-- 9/29/2020 6:53 PM .vs
d----- 3/17/2021 10:55 AM build
d----- 11/4/2020 2:45 PM lib
d----- 9/7/2020 11:12 AM src
d----- 11/4/2020 2:45 PM tests
-a---- 3/15/2021 4:19 PM 340 .dockerignore
-a---- 2/3/2021 6:12 PM 186 .editorconfig
-a---- 2/3/2021 6:12 PM 580 .gitignore
-a---- 3/17/2021 4:07 PM 1611 Dockerfile
Unhiding the .git does not change this behavior.
https://stackoverflow.com/a/54150671/1890717 is a related answer that does not seem to be working here. At least on Windows 10
A: Check if .git is included in your .dockerignore file and if so, remove it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66680559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can we convert/rewrite sslprotocol TLSv1.0 coming from client to TLSv1.1 or TLSv1.2 and forward with sslprotocol as TLSv1.1 or TLSv1.2 using Apache I want to convert TLSv1.0 to TLSv1.1 or TLSv1.2, So that my outgoing request from my Proxy server is TLSv1.1/TLSv1.2. I can use Apache server.
Can someone Please Help !!
Any kind of Help is highly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28433706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Swift How to passing data over view controller using Segue? I want to do like this
passing Data from A to C
like: keying some string in A, and click Button to B, then click Button to C.
show string in C's Label
I find some passing Data like this
ex:
in aClass
let bController = segue.destinationVieController
bController.string = "xxx"
But it just A to B
What should I do to passing Data from A to C ?
Now, I use NSNotificationCetner to complete this work,but I want to learn how to use segue closure
If it's really easy, please tell me keyword
because I just search A to B...
thanks!
A: You are passing string from A->B using segue, so you have the string now in Controller B. Pass the same string from B-> C using segue like below
let cController = segue.destinationVieController
cController.string = string
where string is the variable in Controller B which you have assigned value while segueing from A->B
A: You can immediately perform the segue from b->c in prepare for segue
//VCA
override func prepareForSegue(segue : UISegue, sender: AnyObject?) {
if segue.identifier == "AtoB" {
//Cast destination VC as a your B VC
let bVC = segue.destinationViewController as! BVC
//Set b's .string property to the string property you're going to send to c
bVC.string = self.string
//perform the segue that goes from b to c
bVC.performSegueWithIdentifier("BtoC")
}
}
//VCB
override func prepareForSegue(segue : UISegue, sender: AnyObject?) {
if segue.identifier == "BtoC" {
//Cast destination VC as a your C VC
let cVC = segue.destinationViewController as! CVC
//Set c's .string property to the string property that you now go from
cVC.string = self.string
//Now you will have segue'd to C passing the string you got from a
}
}
Make sure that your segue.identifier's match what you set them in storyboard.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36860778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Render link in Grid cell with custom "click" handler I am rendering a custom link in ExtJS Grid via my own renderrer:
function renderLink( val ) {
return '<a href="javascript:void(0);">' + val + '</a>';
}
What is the easiest way to attach a "click" event listener to it?
Of course after all rows in grid are rendered I could iterate through every record from the grid store and on each of it:
Ext.get('....').on('click', ....);
But for me it sounds rather workaround than real solution... Is there any better way?
A: Try this:
function renderLink( val ){
return '<a href="javascript:void(0);" onclick="someMethod(); return false;">' + val + '</a>';
A: You can attach click event for example with dblclick listener:
listeners: {
dblclick : {
fn: function() {
var selectedRecord = Ext.getCmp('ObjectsGrid').getSelectionModel().getSelection()[0];
console.log(selectedRecord);
},
element: 'body'
}
}
All columns values can be seen by console.log(selectedRecord):
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5911060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: OMP Optimizing nested loop with if statement I have the following few lines of code that I am trying to run in parallel
void optimized(int data_len, unsigned int * input_array, unsigned int * output_array, unsigned int * filter_list, int filter_len) {
#pragma omp parallel for
for (int j = 0; j < filter_len; j++) {
for (int i = 0; i < data_len; i++) {
if (input_array[i] == filter_list[j]) {
output_array[i] = filter_list[j];
}
}
}
}
Just putting the pragma statement has really done wonders, but I am trying to further reduce the run time of this code. I have tried many things ranging from array padding to collapsing the loops to creating tasks, but the only thing that has seemed to work thus far is loop unrolling. Does anyone have any suggestions on what I could possibly due to further speed up this code?
A: You are doing pure memory accessing. That is limited by the memory bandwidth of the machine.
Multi-threading is not going to help you much. gcc -O2 already provide you SSE instruction optimization. So it may not help either to use intel instruction directly. You may try to check 4 int at once because SSE support 128 register (please see https://gcc.gnu.org/onlinedocs/gcc-4.4.5/gcc/X86-Built_002din-Functions.html and google for some example) Also to reduce the amount of data helps, by using short instead of int if you can.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22032707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using destructuring switch statement in es6 Is there a way to use the destructuring feature in switch ... case statement instead of using nested if else statements ??
For example I would expect something like this :
const tall = true;
const clean = true;
switch ([tall, clean]) {
case [true,true]:
console.log("Perfect");
break;
case [false,true]:
console.log("Ok");
break;
case [true,false]:
console.log("Not so good");
break;
default:
console.log("Terrible");
}
instead of using :
if (tall){
if (clean){
...
}else{
...
}
}else{
if (clean){
...
}else{
...
}
}
A: No, this has nothing to do with destructuring and No, you cannot use array literals in a switch statement since distinct objects never compare equal.
What you can do in your case is to map your two booleans to an integer score:
switch (clean * 2 + tall) {
case 3:
console.log("Perfect");
break;
case 2:
console.log("Ok");
break;
case 1:
console.log("Not so good");
break;
case 0:
console.log("Terrible");
}
or the equivalent array lookup:
console.log(["Terrible", "Not so good", "Ok", "Perfect"][clean * 2 + tall]);
You might even want to make the bitwise magic more obvious:
switch (tall << 1 | clean << 0) {
case true << 1 | true << 0:
console.log("Perfect");
break;
case false << 1 | true << 0:
console.log("Ok");
break;
case true << 1 | false << 0:
console.log("Not so good");
break;
case false << 1 | false << 0:
console.log("Terrible");
break;
}
You can also call a helper function score(a, b) { return a << 1 | b << 0 } in both the switch and the cases.
A: Indeed, you can only use literals in a switch statement and you can't use primitive objects as keys in an array, so you can't do a mapping like:
{[true,true]: 'Perfect'
...}
Too bad. I wonder if there are languages where you can have a list/array as dictionary key.
I still might be tempted to do something like this which I think is quite readable (though it might get rejected in a code review!):
function hashKey([tall, clean]) {
return `${tall}_${clean}`
}
let valMap = {
'true_true': 'Perfect',
'false_true': 'Ok',
'true_false': 'Not so good',
'false_false': 'Terrible'
}
console.log(valMap[hashKey([true, true ])])
A: Can do something like the following:
const tall = true;
const clean = false;
switch (true) {
case tall && clean:
console.log("Perfect");
break;
case !tall && clean:
console.log("Ok");
break;
case tall && !clean:
console.log("Not so good");
break;
default:
console.log("Terrible");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48129331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Case agnostic lexicographical ordering in redis sorted set I have a large list of strings (contains usernames, approx 350K records). I need to store it sorted by lexicographical ordering, and ought to be able to retrieve member existence* and member likeness** efficiently. Redis sorted sets look like the data type for the job.
However, I seem to be falling at the first hurdle. Specifically, one of my key requirements is to keep different letter cases together as long as they start with the same letter. E.g. both Bender and bender should end up being ordered side by side. However, redis' sorted sets are strict in following lexicographical ordering rules, thus all strings starting with uppercase are by default sorted before all strings starting with lower case (e.g. Z is ordered before a, but after A).
Is there any way I can workaround this and still use redis sorted sets to fulfil my requirements? FYI, I'm using redis version 2.8.4. Thanks in advance.
*member existence: given a username, check whether it already exists in the stored set
**member likeness: given a username, pull up N stored usernames that are most like the given username
A: You need to do some special encoding with the names. The following is an example.
Let's suppose the length of all names are less than 100 characters. For each name, do the following steps to encode it:
*
*record the indices of upper case letters with 2 digits: for BeNd, the indices are 00 and 02.
*convert upper case letters of the name into lower cases to get a lower case name: from BeNd to bend
*append the indices to the lower case name to get the encoded name: from bend to bend0002
*add the encoded name into the sorted set: zadd key 0 bend0002
In this way, BeNd and bend should be ordered side by side.
When you want to do the search, use the same encoding method to encode the given name, do the search, and decode the results. Since the encoded name records the indices of upper case letters, you can decode it easily.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42036241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to send few parameters via POST method? I want to send parameters as Key-Value via POST. With GET method it easy to make:
myDomain.com?a=3&b=2&c=1
But how to make same request via POST method (I dont want to send all data as String with some delimiter and then parse this String on server via Split() method)?
A: The traditional format is the same. It just appears in the HTTP request body instead of as part of the URI. Whatever library you use to parse the query string should handle x-www-form-urlencoded data just as easily.
POST / HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
a=3&b=2&c=1
A: You should use either form method = POST or ajax.
Jquery ajax is easier. Just google it. (if you want it that way).
P.s. You can't send post parameters via url.
A: The most common way to send POST data is from an html form:
<FORM action="http://somesite.com/somescript.php" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM>
Then process the $_POST vars similar to how you would with $_GET vars in PHP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8986377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Is it possible to restart spyder console and run script again, every n iterations? Currently I am trying to do 3000 iterations of some function using a for-loop (using Spyder). The function however, which I imported from a package, contains a bug. Because of the bug, the function gets slower with every iteration. When I restart the IPython console, the function is fast again but it again gets slower with every iteration.
So, this is what I want to do:
*
*Run (for example) 100 iterations
*Restart console
*Run the next 100 iterations
*Restart console
And so forth, until I've done 3000 iterations.
I know this sounds like a cumbersome process but I don't know how to do it differently since I don't have the skills (and time) to debug the complicated function I am using.
Thanks in advance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55595274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create executable with Python 3.5 on Windows? I'm starting with Python so I downloaded the 3.5 version on my Windows 7 (64), and developped a small app in Eclipse Luna (4.4.1) with PyDev and the Tkinter library. It has only 4 modules and a text file.
I'd like to know how I could export an executable version of my project, like when you do File>Export>Runnable Jar File with a Java project. Is there a way to do this in Eclipse for Python projects ?
I have already tried tools like py2exe or cx_Freeze, but they tell me they have to be used respectively with Python 2.7 and 3.4... Does there exists some piece of software that could do the same for Python 3.5 ?
Thank you very much for any piece of help you could bring.
A: PyInstaller (version 3.2) works for Python 3.5, according to their website.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37612339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to format postgres result in the same way that "TABLE name;" does? I am using Postgres in a nodejs program, and I want to have functions that print the output to the terminal.
When you run the command "TABLE table_name;" in the terminal, you get a nice looking table with space for all characters in all columns shown here
When I run this same query, and try to display it like this:
console.log(pool.query("TABLE table_name")
I get something that looks way worse. Is there some plugin I can get to make it look as good as the first image? Note: It would be displaying in the windows command prompt if that changes anything.
I tried doing my own with some character counting and inserting "\t|\t" into strings, however if the database gets quite large, running multiple times through the data would take too long.
A: console.table() worked perfectly for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70142252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fastest string searching algorithm for fixed text and a lot of substrings I am trying to find an algorithm to search for binary strings of fixed size (64 bit) in a large binary buffer (100 MB). The buffer is always the same and i have got lots and lots of strings to search for (2^500 maybe).
I have to find all the occurrences of any given string, not only the first one.
What algorithm can i choose from? Maybe one that benefits from the constant buffer in which i search.
Links to C source code for such algorithm is appreciated.
A: Assuming your string are 8-bit aligned, from 100MB buffer you'll get 100 millions different strings, which can be put into the hash table approximately 800MB in size with constant (O(1)) access time.
This will allow you to make the search as fast as possible, because once you have your 8 byte string, you immediately know where this string was seen in your buffer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51117873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: assembly code for a reference I have not deeply understood the reference type in c++. So I wrote a tiny piece of code:
int a = 10;
int& b = a;
cout << "a: " << a << endl;
cout << "b: " << b << endl;
cout << "&a: " << &a << endl;
cout << "&b: " << &b << endl;
the output is:
a: 10
b: 10
&a: 0x7ffebd76ac6c
&b: 0x7ffebd76ac6c
And I noticed, without surprise, that a's and b's addresses are the same.
Then I disassembled to find out how actually the reference is considered for the compiler. Here the code:
40096e: c7 45 dc 0a 00 00 00 mov DWORD PTR [rbp-0x24],0xa
400975: 48 8d 45 dc lea rax,[rbp-0x24]
400979: 48 89 45 e0 mov QWORD PTR [rbp-0x20],rax
If I'm correct, rbp-0x24 refers to the variable a, whereas rbp-0x20 refers to the variable b. But my doubt is: if after this three lines (and if I haven't done mistakes)
[rbp-0x20] = rbp-0x24
how could it be possible that both the variables' addresses are the same?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41449356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save ListView items I want to save my downloaded ListView items so that for example next time the app starts, it should not start my download dialog, instead my previous ListView items should turn up.
Some useful code snippets would be appreciated.
Thanks in advance and please tell me if I need to clarify!
A: It depends on the kind of data that is displayed in your ListView.
You can store the data into a SQLite database. This means designing an appropriate schema and implementing create/read/update/delete methods.
The process is too long to be explained here in detail; I invite you to read the Notepad tutorial on the official Android developer site.
A: Depending on the amount of data you are saving you can have many options.
I am assuming you are starting out so it is probably best to go with a straight forward solution utilizing the SQLiteDB instead of preferences or saving to a file.
This is a link to a complete solution for creating the views adapters and database objects.
You could just cut and paste, but read through it and it will be better for you in the long run
Complete ListView Database Tutorial
Android SQLite Basics
List View loaded from XML Resource File
A: In order to do this, you need to think of a strategy for saving data. The most common one is through a SQLite Android DB, nevertheless you might also use Internal Storage if your data is not that complex. Also saving data on Android has been a common topic (check this post)
A: Have a look at the Java Serialization API.
It has its drawbacks (concurrent access....), but maybe it's enough for you.
That's just a quick google hit for that topic.
http://java.sun.com/javase/technologies/core/basic/serializationFAQ.jsp
A: You can use SharedPreferences
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4021511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to loop through a list of dictionaries and write the values as individual columns in a CSV I have a list of dictionaries
d = [{'value':'foo_1', 'word_list':['blah1', 'blah2']}, ...., {'value': 'foo_n', 'word_list':['meh1', 'meh2']}]
I want to write this to a CSV file with all the 'value' keys in one column, and then each individual word from the "value"'s word_list as its own column. So I have the first row as
foo_1 blah_1 blah_2
and so on.
I don't know how many dictionaries I have, or how many words I have in "word_list".
How would I go about doing this in Python 3?
Thanks!
A: It would probably be easiest to flatten each row into a normal list before writing it to the file. Something like this:
with open(filename, 'w') as file:
writer = csv.writer(file)
for row in data:
out_row = [row['value']]
for word in row['word_list']:
out_row.append(word)
csv.writerow(out_row)
# Shorter alternative to the two loops:
# csv.writerow((row['value'], *row['word_list']) for row in data)
A: I figured out a solution, but it's kind of messy (wow, I can't write a bit of code without it being in the "proper format"...how annoying):
with open('filename', 'w') as f:
for key in d.keys():
f.write("%s,"%(key))
for word in d[key]:
f.write("%s,"%(word))
f.write("\n")
A: You can loop through the dictionaries one at a time, construct the list and then use the csv module to write the data as I have shown here
import csv
d = [{'value':'foo_1', 'word_list':['blah1', 'blah2']}, {'value': 'foo_n', 'word_list':['meh1', 'meh2']}]
with open('test_file.csv', 'w') as file:
writer = csv.writer(file)
for val_dict in d:
csv_row = [val_dict['value']] + val_dict['word_list']
writer.writerow(csv_row)
It should work for word lists of arbitrary length and as many dictionaries as you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57897002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need to Delete current password (if Prepopulated) in reset popup window using selenium After clicking reset password link I need to verify whether password (i.e testdemo)is prepopulating in current password text box, if so then I need to clear those values.
A: As far I understood your scenario, you are checking that your password is auto populated in password field and If so then you need to clear that
You can do this - First you need to check is there any value in password field if so then do clear
int passLength = driver.findElement(By.id("Password")).getAttribute("value").length();
if(passLength>0)
{
driver.findElement(By.id("Password")).clear();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41469610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android WebView- Scroll bar not visible after few scrolling inWebView In webView after a few scrolls, the webView default scrollbar gets disappears.
This is my webView code:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:fadeScrollbars="false"
android:focusable="false"
android:focusableInTouchMode="true"
android:scrollbarThumbVertical="@android:color/holo_blue_bright"
android:scrollbarTrackVertical="@android:color/darker_gray"
android:scrollbars="vertical"></WebView>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64423575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stage3D and AIR 3 How does one get a project setup in Flash Builder 4 with Adobe AIR 3 that uses Stage3D?
Whenever I add "-swf-version=13" to the compiler options, I get the following error:
Process terminated unexpectedly.
error while loading initial content
Launch command details: "/Applications/Adobe Flash Builder 4/sdks/4.5.1.21328/bin/adl" -runtime "/Applications/Adobe Flash Builder 4/sdks/4.5.1.21328/runtimes/air/mac" "/Users/joverton/Documents/Prototyping and Testing/Virtual Library AIR/bin-debug/Main-app.xml" "/Users/joverton/Documents/Prototyping and Testing/Virtual Library AIR/bin-debug"
I have gpu mode enabled in my App.xml file, and am using the newest Flex SDK (4.6).
Similar question was asked here:
AIR 3.0 and Stage3D
but the solution is no longer valid! The link in the accepted answer just annoyingly redirects to the home page, and you can't even get to it by looking at Google's cached version of the page.
Also here:
http://www.dreaminginflash.com/2011/10/12/adobe-flex-adobe-air-3-alternativa-3d-real-3d-engine/
does not work for me.
A: You can not use "gpu" mode and Stage3D. You need to specify "direct". Hope this works. Confusing, I know :) If not, try making a regular flash player project first, and run with all debug flags on. AIR is usually more complicated with all the SDKs and stuff.
A: Got it! The solution turned out to be building from the command line, rather than using Flash Builder (4, can't speak for 4.5/6). Here is the sequence of commands:
I. axmlc compile the application (Main.as) file, with all the correct options:
$FLEX_4.6_SDK/bin/amxmlc -static-link-runtime-shared-libraries=true
-library-path+='$ALTERNATIVA/Alternativa3D.swc' -debug=true -swf-version=13 -load-config $FLEX_4.6_SDK/frameworks/air-config.xml -- Main.as
(where $FLEX_4.6_SDK and $ALTERNATIVA are the locations of the Flex SDK and Alternativa3D SWC, naturally)
II. adl run the application
$FLEX_4.6_SDK/bin/adl Main-app.xml
which for convenience I setup in my .bash_profile like so:
alias run_virtual_library="cd '/Users/joverton/Documents/Prototyping and Testing/Virtual Library/src/' && /Applications/Adobe\ Flash\ Builder\ 4/sdks/4.6/bin/amxmlc -static-link-runtime-shared-libraries=true -library-path+='/Users/joverton/Documents/Libraries & Tools/Alternativa3D/Alternativa3D_8.17.0/Alternativa3D.swc' -debug=true -swf-version=13 -load-config /Applications/Adobe\ Flash\ Builder\ 4/sdks/4.6/frameworks/air-config.xml -- Main.as && '/Applications/Adobe Flash Builder 4/sdks/4.6/bin/adl' Main-app.xml &"
Note that in my AIR application descriptor file I set the renderMode to "gpu", but "direct" will also work. Also, in the amxmlc command you needn't set the debug compiler option to true; I only do for the sake of testing.
EDIT: Additional note is that - because I was building from the command line rather than from Flash Builder - I had to explicitly set the value of in my AIR Descriptor file (in this case to "Main.swf"), else I received "content not found" errors when trying to run the application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8969128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to access non container App data/Logs from an Azure-IoT-Edge Container App in gateway/Server? In Azure-IoT-Edge, How to Access non container App data/Logs from an Azure-IoT-Edge Container App in gateway/Server and Push data to Azure IoT Hub cloud?
A: At the end of the day it's the docker container running on a machine and in docker container you can run services that listen to the data that is posted on those services. Some solutions can be:-
*
*A http server running on your edge module container and producers posting data to the RESTful api exposed by the container. Once data received, push it to IoT Hub using routes in edgeHub.
*You can also run a consumer on docker container that listens to a message broker and passes that data to IoT hub using edgeHub routes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63883276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Powershell - Read, Alter Line, Write new line over old in Text Document I am reading in line by line of a text file. If I see a specific string, I locate the first and last of a specific character, use two substrings to create a smaller string, then replace the line in the text file.
The difficult part: I have the line of text stored in a variable, but cannot figure out how to write this new line over the old line in the text document.
Excuse the crude code - I have been testing things and only started playing with PowerShell a few hours ago.
foreach($line in [System.IO.File]::ReadLines("C:\BatchPractice\test.txt"))
{
Write-Output $line
if ($line.Contains("dsa")) {
Write-Output "TRUEEEEE"
}
$positionF = $line.IndexOf("\")+1
$positionL = $line.LastIndexOf("\")+1
$lengthT = $line.Length
Write-Output ($positionF)
Write-Output $positionL
Write-Output $lengthT
if($line.Contains("\")){
Write-Output "Start"
$combine = $line.Substring(0,$positionF-1) + $line.Substring($postionL,($lengthT-$positionL))
Write-Output $combine
$line1 = $line.Substring(0,$positionF-1)
$line2 = $line.Substring($positionL,($lengthT-$positionL))
$combined = $line1 + $line2
Write-Output $combined
Write-Output "Close"
}
}```
A: You can save the file as arrays in Get-Content and Set-Content:
$file=(Get-Content "C:\BatchPractice\test.txt")
Then you can edit it like arrays:
$file[LINE_NUMBER]="New line"
Where LINE_NUMBER is the line number starting from 0.
And then overwrite to file:
$file|Set-Content "C:\BatchPractice\test.txt"
You can implement this in code. Create a variable $i=0 and increment it at the end of loop. Here $i will be the line number at each iteration.
HTH
A: Based on your code it seems you want to take any line that contains 'dsa' and remove the contents after the first backslash up until the last backslash. If that's the case I'd recommend simplifying your code with regex. First I made a sample file since none was provided.
$tempfile = New-TemporaryFile
@'
abc\def\ghi\jkl
abc\dsa\ghi\jkl
zyx\vut\dsa\srq
zyx\vut\srq\pon
'@ | Set-Content $tempfile -Encoding UTF8
Now we will read in all lines (unless this is a massive file)
$text = Get-Content $tempfile -Encoding UTF8
Next we'll make a regex object with the pattern we want to replace. The double backslash is to escape the backslash since it has meaning to regex.
$regex = [regex]'(?<=.+\\).+\\'
Now we will loop over every line, if it has dsa in it we will run the replace against it, otherwise we will output the line.
$text | ForEach-Object {
if($_.contains('dsa'))
{
$regex.Replace($_,'')
}
else
{
$_
}
} -OutVariable newtext
You'll see the output on the screen but it's also capture in $newtext variable. I recommend ensuring it is the output you are after prior to writing.
abc\def\ghi\jkl
abc\jkl
zyx\srq
zyx\vut\srq\pon
Once confirmed, simply write it back to the file.
$newtext | Set-Content $tempfile -Encoding UTF8
You can obviously combine the steps as well.
$text | ForEach-Object {
if($_.contains('dsa'))
{
$regex.Replace($_,'')
}
else
{
$_
}
} | Set-Content $tempfile -Encoding UTF8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64111431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Label the internal memory file At Run Time I have an application that
*
*takes data from the user and
*creates a file in the internal memory based on the name entered by the user
*and saves the user data.
But when the file is saved by that name, the fileInputStream does not respond to that name.
what should I do ?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_food);
bundle = getIntent().getExtras();
Toolbar toolbar=(Toolbar)findViewById(R.id.food_lood_toolbar);
setSupportActionBar(toolbar);
file=bundle.getString("diname");
getSupportActionBar().setTitle(file);
String q=”123”;
if (bundle.getString("activity").equals(q)) {
String e1=editText1.getText().toString() +"/";
fileOutputStream=openFileOutput(file,Context.MODE_PRIVATE);
fileOutputStream.write(e1.getBytes());
}
String t="321";
if (bundle.getString("activity").equals(t)){
try {
fileInputStream= openFileInput(file);
int x;
StringBuffer y = new StringBuffer();
while((x=fileInputStream.read())!=-1){
y.append((char)x);
}
String c=y.toString();
txt=c.split("/");
editText1.setText(txt[0]);
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(),"file not found",Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getBaseContext(),"io",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44484856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: i can't insert photo in database I have a big problem in insertion of photo (blob) into database with php. I can't execute query. It returns false. This is my code
public function addPhoto()
{
$ret = false;
$img_blob = '';
$img_titre ='';
$description = "hhhhh";
$selogon = '';
$ret= is_uploaded_file($_FILES['fic']['tmp_name']);
if (!$ret) {
echo "Problème de transfert";
return false;
} else {
$img_titre = $_FILES['fic']['name'];
$img_blob = file_get_contents ($_FILES['fic']['tmp_name']);
$conn = connection();
$sql = "INSERT INTO image (titre,selogon,description,img_blob)
VALUES ( '$img_titre','$selogon','$description','".addslashes ($img_blob)."')" ;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "string";
}
$conn->close();
}
A: PDO solution
Assuming you're using PDO(not specified by you), if you want to save it as blob then following steps should be done
try
{
$fp = fopen($_FILES['fic']['tmp_name'], 'rb'); // read the file as binary
$stmt = $conn->prepare("INSERT INTO image (titre, selogon, description, img_blob) VALUES (?, ?, ?, ?)"); // prepare statement
// bind params
$stmt->bindParam(1, $img_titre);
$stmt->bindParam(2, $selogon);
$stmt->bindParam(3, $description);
// this is important I will explain it below after the code
$stmt->bindParam(4, $fp, PDO::PARAM_LOB);
$stmt->execute();
// if you want to check if it was inserted use affected rows from PDO
}
catch(PDOException $e)
{
'Error : ' .$e->getMessage();
}
The most important thing is bind the file pointer ($fp) to PDO param called LOB which stands for Large Object
PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.
http://php.net/manual/en/pdo.lobs.php
After that you can use power of PHP streams and save it as binary safe stream. Reading the from streams make more sense but if I were you I'd really think if you want to save pictures directly in db, this doesn't seem to be a good idea.
MYSQLI solution:
If you don't use PDO but for example mysqli then streams are good idea as well but the solution is different.
The best option is to check SHOW VARIABLES LIKE 'max_allowed_packet'; this will print what is max allowed package size, if your image is bigger the blob will be corrupted.
To make it work you'll need to send data in smaller chunks using fread() + loop + feof() and mysqli function send_long_data
Example from php.net site: you can adjust it to your needs quite similar as I did above, the difference is that params are bound in different way.
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen($_FILES['fic']['tmp_name'], "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
A: I have been solve the problem :
solution : in augmentation of size of photo in type (blob --> longblob ) .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49161789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: XPiNC in Notes sidebar without use of Composite App? I seem to remember at Lotusphere 2011 discussion that there would be a way to deploy an XPiNC page to a sidebar widget without using a composite app. Is this possible with 8.5.3 clients? I need to be able to deploy the XPage via the widget catalog, and I cannot have a composite app tab appearing in the client. (I could use a composite app if the only UI would be in the sidebar panel). Any ideas?
A: Yes it is possible to put an XPage in the sidebar without Composite Applications. What you need to do here is to go to File -> Preferences ->Widget Catalog and check the "Show widgets toolbar and My Widgets Panel". Now Open the XPage you want to create as a widget in XPiNC. In the toolbar, click on the "Configure a widget from the current context". Choose "Display as Panel" , click next and then the finish button. Your XPage should now display in the sidebar. Another way is to just click the "Display as Panel" button in the MyWidgets toolbar, this will also put your XPage in the sidebar. If you go to the MyWidgets sidebar Panel, you will be able to see your XPage Widget there and it is possible to export it as a widget to send to other users. Or use the widget catalog and deploy the widget to your users via a policy setting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13624986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to install scoped private npm package from Artifactory in Github Actions This question includes a specific use-case:
*
*I have a private scoped package: @myscope/mypackage
*It hosted in Artifactory NPM registry: https://company.jfrog.io/artifactory/api/npm/my-npm-registry/
*I need to use my credentials to consume it.
*I want to consume it in Github Actions.
How can I do that?
A: .npmrc
First, you need to configure your access in a local .npmrc file. You can put this file in your source root folder.
always-auth = true
# First, set a different registry URL for your scope
@myscope:registry=https://company.jfrog.io/artifactory/api/npm/my-npm-registry/
# Then, for this scope, you need to set the token
//company.jfrog.io/artifactory/api/npm/my-npm-registry/:_auth = {{your token - see below}}
Token
You need to get the NPM Token from Artifactory (note it isn't your API Key.
*
*Get your Artifactory API Key from your Artifactory profile: https://company.jfrog.io/ui/admin/artifactory/user_profile
*Run the next command on your Linux terminal: curl -u {{ ARTIFACTORY_USERNAME }}:{{ ARTIFACTORY_API_KEY }} https://company.jfrog.io/artifactory/api/npm/auth/
*
*Powershell:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f {{ ARTIFACTORY_USERNAME }},{{ ARTIFACTORY_API_KEY }})))
Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} https://company.jfrog.io/artifactory/api/npm/auth/
*You should receive this:
_auth = {{ YOUR_NPM_TOKEN }}
always-auth = true
*So now you can take this Token and put it in the .npmrc file above.
Github Actions
How to do all this in Github Actions?
*
*First, save your Jfrog username and API Key in Github Secrets: JFROG_USER & JFROG_PAT.
*And you can add the next step to your workflow, after checkout and before yarn/npm install:
- name: npm token
run: |
echo "@myscope:registry=https://company.jfrog.io/artifactory/api/npm/my-npm-registry/" > .npmrc
echo "//company.jfrog.io/artifactory/api/npm/my-npm-registry/:$(curl -u ${{ secrets.JFROG_USER }}:${{ secrets.JFROG_PAT }} https://company.jfrog.io/artifactory/api/npm/auth/)" >> .npmrc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70759862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: how to push multiple objects into one object serially I have 2 or multiple objects in a single variable and i want to push these objects into one object.
let a = {"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}
{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}
I want the output to be:
{
"0": {
"device_type": "iphone",
"filter_data": {
"title": {
"value": "Lorem Ipsum..",
"data": {}
},
"message": {
"value": "Lorem Ipsum is simply dummy text of the printing...",
"data": {}
},
"dismiss_button": {
"value": "Ok",
"data": {}
},
"action_url": {
"value": "",
"data": {
"type": "custom"
}
}
}
},
"1": {
"device_type": "iphone",
"filter_data": {
"message": {
"value": "Push Message goes here.",
"data": {}
}
}
}
}
How can I do this?
A: You could replace }{ with a },{, parse it and take Object.assign for getting an object with indices as properties from an array.
const
data = '{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}';
result = Object.assign({}, JSON.parse(`[${data.replace(/\}\{/g, '},{')}]`));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }
A: If they're in an array, it's fairly simple - just use reduce:
const data = [{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}},{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}];
const res = data.reduce((a, c, i) => (a[i] = c, a), {});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
A: You can use Array.protoype.match to separate each object then Array.protoype.reduce to get expected oject.
let a = '{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}';
let objects = a.match(/({"device_type".*?}}}})/g).map(e => JSON.parse(e));
console.log('Array of objects',objects)
const out = {...[objects]};
console.log('\ndesired output',out)
Also, it seems to be useless to convert the array into an object when the keys are just the indexes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56660932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring Cloud Data Flow Aggregator processor won't start I want to deploy a test stream using the app starter aggregator processor.
Just using the default settings, the processor aggregator doesn't start, I have no log, readiness and liveness probes fail.
My SCDF is deployed on a minikube and using bitnami chart version 2.11.3.
What would be a minimum configuration for the aggregator processor to start properly?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68325826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to call all Google font CSS under specific font face Can I call all the CSS of google font API under specific font-face?
I have here "Quattrocento Sans" that has 8 different font-style, the link below only call the CSS which font-style is only normal,
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans' rel='stylesheet' type='text/css'>
This second link call 400italic style:
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:400italic' rel='stylesheet' type='text/css'>
However I like to call all the CSS which contains all 8 different styles with single link only.
So I'm thinking Something like this: Using ( * ) all
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:*' rel='stylesheet' type='text/css'>
Is there any idea how to call all the CSS for this?
A: Don't Include Separate links:
*
*Instead again Go to the google font
*Open Quattrocento Sans font
*Add Whatever weight and style you need for that font
*And, add this code to your website
Link will be like following:
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic' rel='stylesheet' type='text/css'>
A: Use this as an example:
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,800italic|Roboto:400,500,900|Oswald:400,300|Lato:400,100' rel='stylesheet' type='text/css'>
That way you can gather them all in one specific link.
A: try this example:
standart:
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic,700,700italic&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
@import:
`@import url(http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic,700,700italic&subset=latin,latin-ext);`
javascript:
<script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Quattrocento+Sans:400,400italic,700,700italic:latin,latin-ext' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})(); </script>
use: font-family: 'Quattrocento Sans', sans-serif;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24880644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Checking file checksum in Python I have to write in Python that performs the following tasks:
1- Download the Movielens datasets from the url ‘http://files.grouplens.org/datasets/movielens/ml-
25m.zip’
2- Download the Movielens checksum from the url ‘http://files.grouplens.org/datasets/movielens/ml-
25m.zip.md5’
3- Check whether the checksum of the archive corresponds to the downloaded one
4- In case of positive check, print the names of the files contained by the downloaded archive
This is what I wrote up to now:
from zipfile import ZipFile
from urllib import request
import hashlib
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
url_datasets = 'http://files.grouplens.org/datasets/movielens/ml-25m.zip'
datasets = 'datasets.zip'
url_checksum = 'http://files.grouplens.org/datasets/movielens/ml-25m.zip.md5'
request.urlretrieve( url_datasets, datasets)
request.urlretrieve (url_checksum, checksum)
checksum = 'datasets.zip.md5'
with ZipFile(datasets, 'r') as zipObj:
listOfiles = zipObj.namelist()
for elem in listOfiles:
print(elem)
So what I'm missing is a way to compare the checksum I computed with the one I downloaded and maybe I can create a function "printFiles" that checks the checksum and in the positive case prints the list of files.
Is there something else I can improve?
A: Your code isn't actually making any of the requests.
from zipfile import ZipFile
import hashlib
import requests
def md5(fname):
hash_md5 = hashlib.md5()
hash_md5.update( open(fname,'rb').read() )
return hash_md5.hexdigest()
url_datasets = 'http://files.grouplens.org/datasets/movielens/ml-25m.zip'
datasets = 'datasets.zip'
url_checksum = 'http://files.grouplens.org/datasets/movielens/ml-25m.zip.md5'
checksum = 'datasets.zip.md5'
ds = requests.get( url_datasets, allow_redirects=True)
cs = requests.get( url_checksum, allow_redirects=True)
open( datasets, 'wb').write( ds.content )
ds_md5 = md5(datasets)
cs_md5 = cs.content.decode('utf-8').split()[0]
print( ds_md5 )
print( cs_md5 )
if ds_md5 == cs_md5:
print( "MATCH" )
with ZipFile(datasets, 'r') as zipObj:
listOfiles = zipObj.namelist()
for elem in listOfiles:
print(elem)
else:
print( "Checksum fail" )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66925001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does GIT merges based on datetime? I would like to understand how GIT merge happens.
Master & Feature
A--B--C --G--H--I
--D--E--F
Here is the changes made and date when it was changed.
G(Master) - Aug - 8th
H(Master) - Aug - 10th
I(Master) - Aug - 15th
D(Feature) - Aug - 9th
E(Feature) - Aug - 11th
F(Feature) - Aug - 12th
So, now If I merge master branch into feature how does the history appear? Does it merge based on the date change and display like this?
Feature branch
A--B--C--G--D--H--E--F
A: The way git does a merge is that it creates if you will, a patch of the diff between your current branch and the branch you are trying to merge. It then simply applies that patch as a whole to your branch with the commit -
Merge "Source Branch" into "Target Branch"
This is basically the only new commit that you are having. If you want to revert --D--E--F then you don't revert them individually, but revert this big merge commit.
As for the time stamp, yes git will now also give you a merge of the commits themselves in both the branches that you can revert by yourself.
So imagine it something like this,
Branch 1: A - B - C - - G - H - I
Branch 2: D - E - F
Merging these together in Branch 1 will give you -
Branch 1: A - B - C - D - E - F - G - H - I - J (Here, J = D + E + F)
On the other hand, a rebase would give you :
Branch 1: A - B - C - G - H - I - J - D* - E* - F* (Here, D* = D's changes)
A: If you are on branch master, and execute git merge feature, your history will be changed from this :
A--B--C---G--H--I (master)
\
\-D--E--F (feature)
to this :
A--B--C---G--H--I---J (master)
\ /
\-D--E--F-/ (feature)
git will compare the two diffs C vs I and C vs F, and try to build a new commit which combines the changes in these two diffs.
git mays ask you to manually solve conflicts if some changes on I overlap some changes in F.
git will not modify any of the existing commits, so that, on a shared repo, the other developpers' copy of the repo is not messed up.
git merge does not take into account the date of the commit(s) ; it just looks at the succession of commits (the fact that G comes after C in the graph, for example).
There is another command, git rebase, which will change the structure of the existing commits, and may force other developpers to do extra work if they want to keep their local copy in sync with the remote server.
git rebase is a useful command, but it is generally advised to use it only locally, before you share some modification (e.g. : only use it on modifications which have not yet been git pushed).
A: If you merge master branch to feature, it will make a new commit with its log like "Merge branch master to into feature".
you won't get history like A-B-C-G-D-H-E-F
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32303470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to move DataTable to another DataSet? How can I move the DataTable object from one dataset to another and avoid duplicating data in memory? Something, like this:
var ds1 = new DataSet();
var ds2 = new DataSet();
IDataAdapter da = myDataAdapterFactory.New();
da.Fill(ds1);
Console.WriteLine(ds1.Tables.Count);//1
Console.WriteLine(ds2.Tables.Count);//0
ds1.MoveDataTableTo(ds2, ds1.Tables[0]);
Console.WriteLine(ds1.Tables.Count);//0
Console.WriteLine(ds2.Tables.Count);//1
I cannot spend memory, and it is the reason why I dont'use DataTable.Copy() or DataSet.Merge() or other ways to duplicate rows in memory.
A: You can take the datatable you need to move, Remove it from the first dataset and Add it to the other
var dt = ds1.Tables[0];
ds1.Tables.Remove(dt);
ds2.Tables.Add(dt);
A: Use this function
public DataTable CopyDataTable(DataTable dtSource)
{
// cloned to get the structure of source
DataTable dtDestination = dtSource.Clone();
for (int i = 0; i < dtSource.Rows.Count; i++)
{
dtDestination.ImportRow(dtSource.Rows[i]);
}
return dtDestination;
}
Suppose you want to copy first table of sourceSet to destinationSet.
Call it like
DataTable destinationTable = CopyDataTable(ds1.Tables[0]);
DataSet destinationSet = new DataSet();
ds2.Tables.Add(destinationTable);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51925610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Accessing SQL array element from Libreoffice Basic I have a postgresql database that contains program data. In Libreoffice Calc, I have Basic macros that interact with the postgresql database and uses Calc as the user client. One of the postgresql tables has an array and I can't index into that array directly from Basic.
Here is the table setup, as shown in pgAdmin:
sq_num integer,
year_start integer,
id serial NOT NULL,
"roleArray" text[]
Say I want to SELECT roleArray[50]. My every attempt to do this out of Basic results in the entire array being passed. I can certainly split the array myself and get the element I'm after, but I was using SQL arrays to help automate this stuff.
My Basic code uses a Libreoffice Base file for the connection to the postgresql database. Going to the Base file, I cannot create a query that will select an individual element and not return the entire array UNLESS I select the button "Run SQL command directly" and run this query:
SELECT "roleArray"['50'] FROM myTableThatHasArrays
Then I get element 50 from every record as intended.
I believe there is a bug report that describes this, where the Base command parser can't handle indexing an array. My question is what is the best method to overcome this?
The best scenario is to be able to index an element in the SQL array directly from Basic.
A: It sounds like you used XRow.getString, which (sensibly enough) retrieves the array as a single large string. Instead, use XRow.getArray and then XArray.getArray. Here is a working example:
sSQL = "SELECT id, ""roleArray""[2] FROM mytablethathasarrays;"
oResult = oStatement.executeQuery(sSQL)
s = ""
Do While oResult.next()
sql_array = oResult.getArray(2)
basic_array = sql_array.getArray(Null)
s = s & oResult.getInt(1) & " " & basic_array(1) & CHR$(10)
Loop
MsgBox s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37310745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to get value hidden in C# when it is set by jquery after postback i am nwe to jquery.how i get value of hidden field after post back in csharp. when ever post back occures value dissapear.
this is my hidden field.
<asp:HiddenField ID="Hid_BasicSalary" runat="server" />
this is jquery code where is assign data to it after succsesful execution of ajax web service.
var BasicSalary = $('Hid_BasicSalary');
BasicSalary.val(data["BasicSalary"]);
this is c sharp code when i click on button postback occurs afte this node data.
protected void Btn_PIncrementSave_Click(object sender, EventArgs e)
{
try
{
TxBx_IncrementAmount.Text = Hid_BasicSalary.Value.ToString();
}
catch (Exception ex)
{
Utility.Msg_Error(this.Master, ex.Message);
}
}
please help me
A: In jQuery we use the selector for select any elements, and we have to put . for the class and # to the id selector so please put # or . before your element.
In your case, $('#Hid_BasicSalary'); or $('.Hid_BasicSalary'); is your answer.
A: i was missing # with $.
var BasicSalary = $('Hid_BasicSalary');
i write this instead of this
var BasicSalary = $('#Hid_BasicSalary');
A: Try this
var BasicSalary = $('#Hid_BasicSalary');
A: Use This code is page load to get new value from hidden
Request.Form["hdnvalue"];
A: you missed the "#" and i think that you should use the hidden control's clientid.
var BasicSalary = $('#<%=Hid_BasicSalary.ClientID%>');
A: try this to get value of server control from javascript/jquery
var BasicSalary = document.getElementById('<%=Hid_BasicSalary.ClientID%>').value
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16394179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: grep --output-only onto single line I'm currently running a grep that is very close to what I want:
$grep ! myinput_file/* | grep -Po '\d+\.\d+|\d+'
I like that this command only returns the matching contents of the line, but want the output to be on a line by line basis. E.g. when I run the command currently I get:
7.969
80
2
152.03886767
7.969
80
4
152.10112473
7.969
80
6
152.10200398
7.969
80
8
152.10203172
Where I would rather get output of the form:
7.969 80 2 152.03886767
7.969 80 4 152.10112473
7.969 80 6 152.10200398
7.969 80 8 152.10203172
I could write a script or use vim on the output, but I suspect there is a more elegant solution...
PS the source file looks like:
$grep ! encutkpoint_calculations/* | grep -P '\d+\.\d+|\d+'
encutkpoint_calculations/MgO.scf.a=7.969.ecut=80.k=2.out:! total energy = -152.03886767 Ry
encutkpoint_calculations/MgO.scf.a=7.969.ecut=80.k=4.out:! total energy = -152.10112473 Ry
encutkpoint_calculations/MgO.scf.a=7.969.ecut=80.k=6.out:! total energy = -152.10200398 Ry
encutkpoint_calculations/MgO.scf.a=7.969.ecut=80.k=8.out:! total energy = -152.10203172 Ry
A: Since data is being extracted from file names as well, I'll leave the first use of grep as is
$ # this won't depend on knowing how many matches are found per line
$ # this would also work if there are different number of matches per line
$ grep '!' encutkpoint_calculations/* | perl -lne 'print join " ", /\d+(?:\.\d+)?/g'
7.969 80 2 152.03886767
7.969 80 4 152.10112473
7.969 80 6 152.10200398
7.969 80 8 152.10203172
Alternate is to post process the data, if number of matches is constant per line
grep '!' encutkpoint_calculations/* | grep -oP '\d+(\.\d+)?' | pr -4ats' '
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49750701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Changing width of UISlider programmatically? I am creating a UISlider programmatically. When initializing it, I use initWithFrame and pass in CGRect and it doesn't have any effect. I thought maybe I can change it after I initialize but still nothing...I can change it via I.B. so there's got to be a way to change it's width.
A: You definitely can specify the width of the slider by using initWithFrame or changing the bounds of it. There has to be something else going on here that's preventing it from working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6807344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add jstree to angular 2 application using typescript with @types/jstree Hi I believe it's some kind of a newbee question, but I'm new to ng2 so please bear with me...
I've done:
npm i jstree --save
After I created using angular-cli application.
Then I installed:
npm i @types/jstree --save-dev
And that's on setup, then I tried to use it and no luck.
Please can someone show me how to use that 3rd party library with typescript
A: Here are the steps I took to get it to work.
I started with a new cli application.
npm install --save jquery jstree
npm install --save-dev @types/jquery @types/jstree
I then updated the angular.json file, if you are using an older version of angular-cli, makes changes to the angular-cli.json file. I added "../node_modules/jstree/dist/themes/default-dark/style.min.css" to the styles property array.
I also added two items into the scripts property array:
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/jstree/dist/jstree.min.js"
I then updated src/app/app.component.html to
<div id="foo">
<ul>
<li>Root node 1
<ul>
<li>Child node 1</li>
<li><a href="#">Child node 2</a></li>
</ul>
</li>
</ul>
</div>
I also update src/app/app.component.ts to
import { Component, OnInit } from '@angular/core';
declare var $: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit(): void {
$('#foo').jstree();
}
}
Hope this helps!
A: @IamStalker, it seems that i know what the problem is. But can you present more code to show how you want to use it?
As jstree depends on jQuery, you have to import it too.
You may have to use scripts config.
Here is the reference: https://github.com/angular/angular-cli/wiki/stories-global-scripts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44987260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to map table name to EF Entity? I have been using EF Code First for 1 month. My project needs to work with many tables (over 100 tables of data) and they will be changed many times in the future. It hard to control and take time to add the migration.
So is there any solution to skip the add-migration step, just create the table in the database and create a mapping to the Entity?
Example:
In database I have a table like this:
CREATE TABLE dbo.MyTable
(
Id INT,
Name VARCHAR(255),
Description VARCHAR(1000)
);
I want to map it to the following entity:
public class MyEntity
{
public Id int {get; set;}
public Name string {get; set;}
public Description string {get; set;}
}
My expected solution is something like this:
CreateMap("dbo.MyTable", MyEntity)
A: Use the attribute System.ComponentModel.DataAnnotations.Schema.Table
[Table("MyTable")]
public class MyEntity
{
public Id int {get; set;}
public Name string {get; set;}
public Description string {get; set;}
}
If you don't actually want to run the migrations, I suggest create them anyway and comment out the relevant code before you run them. That way you will be well set up for the occassion when you do actually want to run them.
A: You can define the entity maps by overriding the method called OnModelCreating in your DbContext:
Then you can add some maps similar to:
modelBuilder.Entity<Order>(m => {
m.ToTable("MyTable", "dbo");
})
Info: https://learn.microsoft.com/en-us/ef/core/modeling/relational/tables
EDIT: I don't like adding annotation directly to my entity as I prefer to centralize it in one place. Easier to manage. After all I guess it's a question of preferences :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46848336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Oracle connection test We are developing java based web application, which runs on Ubuntu 12.04. At the start of installation, we prompt for Oracle server's Host, Port, user, password & SID details and then passed them to installer to build jdbc:oracle:thin url. Eventually, our installer connects to Oracle and creates some tables.
Now I am trying to write a script(shell or python) to quickly verify user entered Oracle settings are correct or not by simply connecting to Oracle and disconnecting before passing those to our installer. I tried to use echo "exit" | sqlplus -L user/password@//host:port/SID | grep Connected > /dev/null but sqlplus easy connect is only taking service-name not SID.
Is there any easy way to test Oracle connectivity. I need to write it in script, which needs to run automatically as a part of installation steps.
Thanks for all the help.
A: Read https://asktom.oracle.com/pls/asktom/f?p=100:11:0::NO::P11_QUESTION_ID:45033135081903
Oracle listener is expected to listen to your request for connection.
Here is the copy of Tom's answer
[tkyte@desktop tkyte]$ sh -vx test.sh
sqlplus
'scott/tiger@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost.localdomain)(PORT=152
1)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ora9ir2.kyte.com)))'
Use your host, port and service_name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23231505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I implement this L1 norm Robust PCA equation in a more efficient way? I recently learned in class the Principle Component Analysis method aims to approximate a matrix X to a multiplication of two matrices Z*W. If X is a n x d matrix, Z is a n x k matrix and W is a k x d matrix. In that case, the objective function the PCA tries to minimize is this. (w^j means the j_th column of W, z_i means the i_th row of Z)
In this case it is easy to calculate the gradient of f, with respect to W and Z.
However, instead of using the L2 norm as above, I have to use the L1 norm, like the following equation, and use gradient descent to find the ideal Z and W.
In order to differentiate it, I approximated the absolute function as follows (epsilon is a very small value).
However, when I tried to calculate the gradient matrix with respect to W of this objective function, I derived an equation as follows.
I tried to make the gradient matrix elementwise, but it takes too long if the size of X is big.
g = np.zeros((k, d))
for i in range(k):
for j in range(d):
for k2 in range(n):
temp = np.dot(W[:,j], Z[k2,:])-X[k2, j]
g[i, j] += (temp * Z[k2, i])/np.sqrt(temp*temp + 0.0001)
g = g.transpose()
Is there any way I can make this code faster? I feel like there is a way to make the equation way more simple, but with the square root inside I am completely lost. Any help would be appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55255401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Spark job submission error on EMR: java.net.URISyntaxException: Expected scheme-specific part at index 3: s3 I submit Spark jobs to EMR via Managed Airflow service of AWS (MWAA). The jobs were running fine with the MWAA version 1.10.12. Recently, AWS released a newer version of MWAA i.e. 2.0.2. I created a new environment with this version and tried submitting the same job to EMR. But it failed with the following error :
Exception in thread "main" java.lang.IllegalArgumentException: java.net.URISyntaxException: Expected scheme-specific part at index 3: s3:
at org.apache.hadoop.fs.Path.initialize(Path.java:263)
at org.apache.hadoop.fs.Path.<init>(Path.java:221)
at org.apache.hadoop.fs.Path.<init>(Path.java:129)
at org.apache.hadoop.fs.Globber.doGlob(Globber.java:229)
at org.apache.hadoop.fs.Globber.glob(Globber.java:149)
at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:2096)
at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:2078)
at org.apache.spark.deploy.DependencyUtils$.resolveGlobPath(DependencyUtils.scala:192)
at org.apache.spark.deploy.DependencyUtils$.$anonfun$resolveGlobPaths$2(DependencyUtils.scala:147)
at org.apache.spark.deploy.DependencyUtils$.$anonfun$resolveGlobPaths$2$adapted(DependencyUtils.scala:145)
at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
at scala.collection.IndexedSeqOptimized.foreach(IndexedSeqOptimized.scala:36)
at scala.collection.IndexedSeqOptimized.foreach$(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:38)
at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)
at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242)
at scala.collection.AbstractTraversable.flatMap(Traversable.scala:108)
at org.apache.spark.deploy.DependencyUtils$.resolveGlobPaths(DependencyUtils.scala:145)
at org.apache.spark.deploy.SparkSubmit.$anonfun$prepareSubmitEnvironment$5(SparkSubmit.scala:364)
at scala.Option.map(Option.scala:230)
at org.apache.spark.deploy.SparkSubmit.prepareSubmitEnvironment(SparkSubmit.scala:364)
at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:902)
at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180)
at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203)
at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90)
at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1038)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1047)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.net.URISyntaxException: Expected scheme-specific part at index 3: s3:
at java.net.URI$Parser.fail(URI.java:2847)
at java.net.URI$Parser.failExpecting(URI.java:2853)
at java.net.URI$Parser.parse(URI.java:3056)
at java.net.URI.<init>(URI.java:746)
at org.apache.hadoop.fs.Path.initialize(Path.java:260)
... 27 more
Command exiting with ret '1'
The spark-submit command looks like this:
spark-submit --deploy-mode cluster
--master yarn
--queue low
--jars s3://bucket-name/jars/mysql-connector-java-8.0.20.jar,s3://bucket-name/jars/postgresql-42.1.1.jar,s3://bucket-name/jars/delta-core_2.12-1.0.0.jar
--py-files s3://bucket-name/dependencies/spark.py, s3://bucket-name/dependencies/helper_functions.py
--files s3://bucket-name/configs/spark_config.json
s3://bucket-name/jobs/data_processor.py [command-line-args]
The job submission failed in under 10 seconds. Hence, the YARN application ID did not get created.
What I tried to resolve the error:
*
*I added amazon related package to requirements.txt:
apache-airflow[mysql]==2.0.2
pycryptodome==3.9.9
apache-airflow-providers-amazon==1.3.0
*I changed the import statements from:
from airflow.contrib.operators.emr_add_steps_operator import EmrAddStepsOperator
from airflow.contrib.operators.emr_create_job_flow_operator import EmrCreateJobFlowOperator
from airflow.contrib.operators.emr_terminate_job_flow_operator import EmrTerminateJobFlowOperator
from airflow.contrib.sensors.emr_step_sensor import EmrStepSensor
from airflow.hooks.S3_hook import S3Hook
from airflow.operators.python_operator import PythonOperator
from airflow.operators.bash_operator import BashOperator
from airflow.models import Variable
to
from airflow.providers.amazon.aws.operators.emr_create_job_flow import EmrCreateJobFlowOperator
from airflow.providers.amazon.aws.operators.emr_add_steps import EmrAddStepsOperator
from airflow.providers.amazon.aws.operators.emr_terminate_job_flow import EmrTerminateJobFlowOperator
from airflow.providers.amazon.aws.sensors.emr_step import EmrStepSensor
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.operators.python import PythonOperator
from airflow.operators.bash import BashOperator
from airflow import DAG
from airflow.models import Variable
*Changed the URI scheme to s3n and s3a
I checked the official documentation and blogs on MWAA as well as Airflow 2.0.2 and made the above changes. But nothing has worked so far. I seek help in resolving this error at the earliest. Thanks in advance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70314712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to iterate column in CSV output on this beautifulsoup Python script? I have a beautifulsoup Python script that looks for href links in a component on a website and outputs those links line-by-line to a CSV file. I'm planning on running the script every day via a cron job, and I'd like to add a second column in the CSV labeled "Number of times seen". So when the script runs, if it finds a link already in the list, it would just add to the number in that column. For example, if it's the second time it's seen a particular link, it would be "N+1" or just 2 in that column. But if it's the first time the Python script saw that link, it would just add the link to the bottom fo the list. I'm not sure how to attack this as I'm pretty new to Python.
I've developed the Python script to scrape the links from the component on all of the pages in a XML sitemap. However, I'm not sure how to iterate on the "Number of times seen" column in the CSV output as the cron job runs the script every day. I don't want the file to be overwritten, I only want the "Number of times seen" column to iterate, or if it's the first time the link was seen, for the link to be put at the bottom of the list.
Here's the Python script that I have so far:
sitemap_url = 'https://www.lowes.com/sitemap/navigation0.xml'
import requests
from bs4 import BeautifulSoup
import csv
from tqdm import tqdm
import time
# def get_urls(url):
page = requests.get(sitemap_url)
soup = BeautifulSoup(page.content, 'html.parser')
links = [element.text for element in soup.findAll('loc')]
# return links
print('Found {:,} URLs in the sitemap! Now beginning crawl of each URL...'\
.format(len(links)))
csv_file = open('cms_scrape.csv', 'w')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['hrefs', 'Number of times seen:'])
for i in tqdm(links):
#print("beginning of crawler code")
r = requests.get(i)
data = r.text
soup = BeautifulSoup(data, 'lxml')
all_a = soup.select('.carousel-small.seo-category-widget a')
for a in all_a:
hrefs = a['href']
print(hrefs)
csv_writer.writerow([hrefs, 1])
csv_file.close()
Current state: Currently, every time the script runs, the "Number of times seen:" column in the CSV output is overwritten.
Desired state: I want the "Number of times seen:" column to iterate whenever the script finds a link it's seen in a previous crawl, or if it's the first time that link has been seen, I want it to say "1" in this column in the CSV.
Thanks a ton for your help!!
A: So, this isn't actually a questing about bs4, but more about how to handle data structures in python.
Your script lacks the part that loads the data you already know. One way to go about this would be the build a dict that has all your hrefs as keys and then the count as value.
So given a csv with rows like this...
href,seen_count
https://google.com/1234,4
https://google.com/3241,2
... you first need to build the dict
csv_list = list(open("cms_scrape.csv", "r", encoding="utf-8"))
# we skip the first line, since it hold your header and not data
csv_list = csv_list[1:]
# now we convert this to a dict
hrefs_dict = {}
for line in csv_list:
url, count = line.split(",")
# remove linebreak from count and convert to int
count = int(count.strip())
hrefs_dict[url] = count
That yields a dict like this:
{
"https://google.com/1234": 4,
"https://google.com/3241": 2
}
Now you can check if all hrefs you come across exist as a key in this dict. If yes - increase the count by one. If no, insert the href in the dict and se the count to 1.
To apply this to your code I'd suggest you scrape the data first and write to file once all scraping is completed. Like so:
for i in tqdm(links):
#print("beginning of crawler code")
r = requests.get(i)
data = r.text
soup = BeautifulSoup(data, 'lxml')
all_a = soup.select('.carousel-small.seo-category-widget a')
for a in all_a:
href = a['href']
print(href)
# if href is a key in hrefs_dict increase the value by one
if href in hrefs_dict:
hrefs_dict[href] += 1
# else insert it into the hrefs_dict and set the count to 1
else:
hrefs_dict[href] = 1
Now when the scraping is done, go through every line in the dict and write it to your file. It's generally recommended that you use context managers when you write to files (to avoid blocking if you accidentally forget to close the file). So the "with" takes care of both the opening and closing of the file:
with open('cms_scrape.csv', 'w') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['hrefs', 'Number of times seen:'])
# loop through the hrefs_dict
for href, count in hrefs_dict.items():
csv_writer.writerow([href, count])
So if you don't actually have to use a csv-file for this I'd suggest using JSON or Pickle. That way you can read and store the dict without needing to convert back and forth to csv.
I hope this solves your problems...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57827702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In search for a replacement for w3c.dom.Node Is there a library for Java that replaces the org.w3c.dom.Node with some better Node implementation?
I's so sick of the bad implementation of the whole default HTML parsing in Java.
A: For HTML parsing, I'd suggest jsoup:
jsoup is a Java library for working with real-world HTML. It provides
a very convenient API for extracting and manipulating data, using the
best of DOM, CSS, and jquery-like methods.
jsoup implements the WHATWG HTML5 specification, and parses HTML to
the same DOM as modern browsers do.
A: After some searching I found Jericho.
I use XPath with the help of this article and Jaxen
I'm just not sure if this is the best way...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8477070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how can I completely disable the horizontal scrolling system enter image description herewhen I one line too long, my full editor get horizontally large & scrollbar comes (like 1st image)
enter image description here
I want long lines will break in multiple short lines
(like 2nd image)
A: You have to turn on the WORD-WRAP Feature in Visual Studio Code.
There are 2 ways to do this:
*
*By using the View menu (View* → Toggle Word Wrap)
*By using the Keyboard Shortcut
Windows/Linux: ALT + Z
Mac: ⌥ + Z
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72749243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Styling last menu item on multilevel menu I'm trying to stylize the last menu choice on a menu that has dropdowns in it.
This is kind of what it looks like. The > means it's a drop down.
Home AAA> BBB> CCC DDD Contact Donate
I'm trying to make JUST the Donate choice have a red background with white letters, so I've put this in:
#main-nav li:last-child a {
color:#ffffff;
background-color:rgb(178, 45, 58);
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
padding: 5px;
}
But that is making the last item in each of the dropdowns red too!
How can I make just the last item of the main menu be stylized?
Thanks!
A: You need to target the immediate children of the navigation list. Use this selector:
#main-nav > ul > li:last-child > a
A: I'm going to post this, but please accept Chris' answer as his is right, except he did not have the correct Id name for the navigation.
#navigation > ul > li:last-child > a{
color:Red;
}
Here is a JSFiddle demonstrating that the 'Donate' is the only thing being turned red.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32785270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to simplify the JS code in this R shiny code? The below code I found at How to display a scaled up image in an popup window on mouse hover or on click event on an image displayed in a rhandsontable cell in RShiny? (but wrapped in Shiny) almost gets at what I'm trying to do with widgets in rhandsontable. But I don't know enough JS to modify it to do what I want.
I'd like to create a column with a question mark in each row of the table, and hovering over the question mark causes explanatory text to appear in a bubble. Sort of like what happens when running the below code, but the below code is more complex because it renders a miniature image in each column row, and hovering over the miniature images causes the image to bubble out large. I'd like to replace the miniature images with question marks, and when hovering over the question mark explanatory text pops up in a bubble, different text for each row. As shown in the below image:
Any recommendations for how to achieve this?
Code:
library(magrittr)
library(htmlwidgets)
library(rhandsontable)
library(shiny)
DF = data.frame(
comments = c(
"I would rate it ★★★★☆",
"This is the book about JavaScript"
),
cover = c(
"http://ecx.images-amazon.com/images/I/51bRhyVTVGL._SL500_.jpg",
"http://ecx.images-amazon.com/images/I/51gdVAEfPUL._SL500_.jpg"
),
stringsAsFactors = FALSE
)
ui <- fluidPage(br(),rHandsontableOutput('my_table'))
server <- function(input, output, session) {
output$my_table <- renderRHandsontable({
rhandsontable::rhandsontable(DF, allowedTags = "<em><b><strong><a><big>",
callback = htmlwidgets::JS(
"$(document).ready(function() {
$('body').prepend('<div class=\"zoomDiv\"><img src=\"\" class=\"zoomImg\"></div>');
// onClick function for all plots (img's)
$('img:not(.zoomImg)').click(function() {
$('.zoomImg').attr('src', $(this).attr('src')).css({width: '100%'});
$('.zoomDiv').css({opacity: '1', width: 'auto', border: '1px solid white', borderRadius: '5px', position: 'fixed', top: '50%', left: '50%', marginRight: '-50%', transform: 'translate(-50%, -50%)', boxShadow: '0px 0px 50px #888888', zIndex: '50', overflow: 'auto', maxHeight: '100%'});
});
// onClick function for zoomImg
$('img.zoomImg').click(function() {
$('.zoomDiv').css({opacity: '0', width: '0%'});
});
});"
),
width = 800, height = 450, rowHeaders = FALSE) %>%
hot_cols(colWidths = c(200, 80)) %>%
hot_col(1, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
hot_col(2, renderer = "
function(instance, td, row, col, prop, value, cellProperties) {
var escaped = Handsontable.helper.stringify(value),
img;
if (escaped.indexOf('http') === 0) {
img = document.createElement('IMG');
img.src = value; img.style.width = 'auto'; img.style.height = '80px';
Handsontable.dom.addEvent(img, 'mousedown', function (e){
e.preventDefault(); // prevent selection quirk
});
Handsontable.dom.empty(td);
td.appendChild(img);
}
else {
// render as text
Handsontable.renderers.TextRenderer.apply(this, arguments);
}
return td;
}")
})
}
shinyApp(ui, server)
A: Here's an option that doesn't totally do what you're asking, but should get you close if you add some css:
library(magrittr)
library(htmlwidgets)
library(rhandsontable)
library(shiny)
DF = data.frame(
comments = c(
"I would rate it ★★★★☆",
"This is the book about JavaScript"
),
cover = c(
"https://as1.ftcdn.net/v2/jpg/03/35/13/14/1000_F_335131435_DrHIQjlOKlu3GCXtpFkIG1v0cGgM9vJC.jpg",
"https://as1.ftcdn.net/v2/jpg/03/35/13/14/1000_F_335131435_DrHIQjlOKlu3GCXtpFkIG1v0cGgM9vJC.jpg"
),
text = c(
"descriptive text about img 1",
"descriptive text about img 2"
),
stringsAsFactors = FALSE
)
ui <- fluidPage(br(),rHandsontableOutput('my_table'))
server <- function(input, output, session) {
output$my_table <- renderRHandsontable({
rhandsontable::rhandsontable(DF, allowedTags = "<em><b><strong><a><big>",
width = 800, height = 450, rowHeaders = FALSE) %>%
hot_cols(colWidths = c(200, 80)) %>%
hot_col(1, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
hot_col(2, renderer = "
function(instance, td, row, col, prop, value, cellProperties) {
var escaped = Handsontable.helper.stringify(value),
img;
if (escaped.indexOf('http') === 0) {
img = document.createElement('IMG');
img.src = value; img.style.width = 'auto'; img.style.height = '80px';
Handsontable.dom.addEvent(img, 'mousedown', function (e){
var exists = document.getElementById('test')
if (exists === null){
var textBlock = instance.params.data[[row]][[2]];
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.innerHTML = '<center><b>close</b></center>';
cancel.onclick = function(e) {
popup.parentNode.removeChild(popup)
}
var message = document.createElement('span');
message.innerHTML = '<center>' + textBlock + '</center>';
popup.appendChild(message);
popup.appendChild(cancel);
document.body.appendChild(popup);
}
});
Handsontable.dom.empty(td);
td.appendChild(img);
}
else {
// render as text
Handsontable.renderers.TextRenderer.apply(this, arguments);
}
return td;
}") %>%
hot_cols(colWidths = ifelse(names(DF) != "text", 150, 0.1))
})
}
shinyApp(ui, server)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74101509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to have SQL server validate object references in Stored Procs? The following code executes fine in SQL Server
create proc IamBrokenAndDontKnowIt as
select * from tablewhichdoesnotexist
Of course if I try to run it, it fails with
Invalid object name 'tablewhichdoesnotexist'.
Is there any way to compile or verify that Stored Proc are valid?
A: You can use
SET FMTONLY ON
EXEC dbo.My_Proc
SET FMTONLY OFF
You'll need to capture the error(s) somehow, but it shouldn't take much to put together a quick utility application that takes advantage of this for finding invalid stored procedures.
I haven't used this extensively, so I don't know if there are any side-effects to look out for.
A: You used to get a warning message when you tried to create a stored procedure like that. It would say:
Cannot add rows to sysdepends for the current stored procedure because it depends on the missing object 'dbo.nonexistenttable'. The stored procedure will still be created.
For some reason I'm not getting it now, I'm not sure if it's been changed or if there's just some setting that turns the warning on or off. Regardless, this should give you a hint as to what's happening here.
SQL Server does track dependencies, but only dependencies which actually exist. Unfortunately, none of the dependency tricks like sp_depends or sp_MSdependencies will work here, because you're looking for missing dependencies.
Even if we could hypothetically come up with a way to check for these missing dependencies, it would still be trivial to concoct something to defeat the check:
CREATE PROCEDURE usp_Broken
AS
DECLARE @sql nvarchar(4000)
SET @sql = N'SELECT * FROM NonExistentTable'
EXEC sp_executesql @sql
You could also try parsing for expressions like "FROM xxx", but it's easy to defeat that too:
CREATE PROCEDURE usp_Broken2
AS
SELECT *
FROM
NonExistentTable
There really isn't any reliable way to examine a stored procedure and check for missing dependencies without actually running it.
You can use SET FMTONLY ON as Tom H mentions, but be aware that this changes the way that the procedure is "run". It won't catch some things. For example, there's nothing stopping you from writing a procedure like this:
CREATE PROCEDURE usp_Broken3
AS
DECLARE @TableName sysname
SELECT @TableName = Name
FROM SomeTable
WHERE ID = 1
DECLARE @sql nvarchar(4000)
SET @sql = N'SELECT * FROM ' + @TableName
EXEC sp_executesql @sql
Let's assume you have a real table named SomeTable and a real row with ID = 1, but with a Name that doesn't refer to any table. You won't get any errors from this if you wrap it inside a SET FMTONLY ON/OFF block.
That may be a contrived problem, but FMTONLY ON does other weird things like executing every branch of an IF/THEN/ELSE block, which can cause other unexpected errors, so you have to be very specific with your error-handling.
The only truly reliable way to test a procedure is to actually run it, like so:
BEGIN TRAN
BEGIN TRY
EXEC usp_Broken
END TRY
BEGIN CATCH
PRINT 'Error'
END CATCH
ROLLBACK
This script will run the procedure in a transaction, take some action on error (in the CATCH), and immediately roll back the transaction. Of course, even this may have some side-effects, like changing the IDENTITY seed if it inserts into a table (successfully). Just something to be aware of.
To be honest, I wouldn't touch this problem with a 50-foot pole.
A: No (but read on, see last line)
It's by design: Deferred Name Resolution
Erland Sommarskog raised an MS Connect for SET STRICT_CHECKS ON
The connect request has a workaround (not tried myself):
Use check execution plan. The only
weakness is that you may need
permissions to see the execution plan
first
A: You could run sp_depends (see http://msdn.microsoft.com/en-us/library/ms189487.aspx) and use that information to query the information schema (http://msdn.microsoft.com/en-us/library/ms186778.aspx) to see if all objects exist. From what I read here (http://msdn.microsoft.com/en-us/library/aa214346(SQL.80).aspx) you only need to check referenced tables, which is doable.
A: You could check information_schema.tables to check whether a table exist or not and then execute the code
here is quickly slung function to check
create function fnTableExist(@TableName varchar(64)) returns int as
begin
return (select count(*) from information_schema.tables where table_name=@tableName and Table_type='Base_Table')
end
go
if dbo.fnTableExist('eObjects') = 0
print 'Table exist'
else
print 'no suchTable'
like wise you can check for existance of Stored procs / functions in
.INFORMATION_SCHEMA.ROUTINES.Routine_name for th name of the Stored proc/function
A: In SQL 2005 or higher, you can test a stored procedure using transactions and try/catch:
BEGIN TRANSACTION
BEGIN TRY
EXEC (@storedproc)
ROLLBACK TRANSACTION
END TRY
BEGIN CATCH
WHILE @@TRANCOUNT > 0
ROLLBACK
END CATCH
The algorithm to test all stored procedures in a database is a bit more complicated, as you need to workaround SSMS restrictions if you have many SPs which return many result sets. See my blog for complete solution.
A: I've just discovered that VS2010 with database projects will do syntax and name reference checking. Seems like the best option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2015078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Cannot create "Analysis Services Multidimentional and Datamining" project in Visual Studio 2019 In Visual Studio 2019, I cannot create "Analysis Services Multidimensional and Datamining project" even "Microsoft Analysis Services Projects" extension v2.9.10 is installed and I am able to create "Analysis Services Tabular" project.
Any idea why?
A: I had the same problem.
In extension tab go to -Manage Extensions- -Installed- -Turn off Analysis services extension-
Reopen Visual studio, turn Analysis services extension on.
Reopen Visual studio.
It worked for me :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62385144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits