text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: How to use a promised function in a react app I'm trying to implement Bullet train API in a React web app. According to their node client documentation, I have setup the following function:
export const isFeatureEnabled = async (nameOfTheFeature) => {
return new Promise((resolve) => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
});
bulletTrain.hasFeature(nameOfTheFeature)
.then((featureFlag) => {
if (featureFlag[nameOfTheFeature].enabled) {
resolve(true);
}
})
.catch(err => resolve(false));
});
}
This is called in regular components like this:
render() {
return (<div>{await isFeatureEnabled('feature1') && <p>feature1 is enabled</p>}</div>)
};
which throws this:
Parsing error: Can not use keyword 'await' outside an async function
If we add the async keyword, with a proper return statement:
async render() {
return (<div>{await isFeatureEnabled('feature1') && <p>feature1 is enabled</p>}</div>)
};
Then it throws:
Your render method should have return statement
So what is the correct way to use this promised function inside a react app?
A: call function isFeatureEnabled inside an async function during mount (before/after your wish)
example -
export const isFeatureEnabled = async (nameOfTheFeature) => {
return new Promise((resolve) => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
});
bulletTrain.hasFeature(nameOfTheFeature)
.then((featureFlag) => {
if (featureFlag[nameOfTheFeature].enabled) {
resolve(true);
}
})
.catch(err => resolve(false));
});
}
...
componentDidMount() {
this.checEnabled();
}
...
const checkEnabled = async () => {
const flag = await isFeatureEnabled('feature1');
this.setState({f1enabled: flag});
}
...
render() {
return (<div>{this.state.f1enabled ? <p>feature1 is enabled</p> : null}</div>)
}
If isFeatureEnabled is in the same file keep it outside class component or else keep it in another file and export the function.
A: I would suggest you not to use await keyword in render instead use componentDidMount and constructor for this and use state object to check:
constructor(props){
super(props);
this.state = { isFeatEnabled: false };
}
componentDidMount(){
this.setState({isFeatEnabled:isFeatureEnabled('feature1')})
}
Now in the render:
render() {
return (<div>{this.state.isFeatEnabled && <p>feature1 is enabled</p>}</div>)
};
And remove the async from the method.
A: You can't use promise at there, the proper way:
import React, { useEffect, useState } from 'react'
import bulletTrain from '../somewhere'
import BULLET_TRAIN_ENV_ID from '../somewhere'
export default function featureComponent({ featureName }) {
const [featureEnabled, setFeatureEnabled] = useState(false)
useEffect(() => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
})
bulletTrain
.hasFeature(featureName)
.then(featureFlag => {
if (featureFlag[featureName].enabled) {
setFeatureEnabled(true)
}
})
.catch(err => setFeatureEnabled(false))
}, [featureName])
return <div>{featureEnabled && <p>{featureName} is enabled</p>}</div>
}
Append isFeatureEnabled function re-use answer below:
import React, { useEffect, useState } from 'react'
import isFeatureEnabled from '../somewhere'
export default function featureComponent({ featureName }) {
const [featureEnabled, setFeatureEnabled] = useState(false)
useEffect(() => {
const checkAndSetEnabled = async () => {
const enabled = await isFeatureEnabled(featureName)
setFeatureEnabled(enabled)
}
checkAndSetEnabled()
}, [featureName])
return <div>{featureEnabled && <p>{featureName} is enabled</p>}</div>
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60447275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dynamic arrays and lists So, I'm trying to create a kind of text editor for creating question lists. I'm unsure how to achieve that.
What I came up with until now is to create a JPanel which represents an A4 piece of paper. Then, I'd like to create maybe another JPanel which would contain several textboxes in which question/answers would be typed in. The problem is that I'd like to be able to add/remove questions from anywhere within my "document". Doing it with arrays would be tedious and I'd survive that, but the main issue would be fixed array size.
My question is, is there any way to create some kind of dynamic list and what would be a way to go in my case? It's also important to be able to pinpoint a certain "question" JPanel by simply invoking any of its textboxes (because clicking a textbox and pressing a combination of keys would add another question after the invoked one, at least that's the plan).
Anyone?
A: Take a look at ArryList. There are also many other collection classes in the util package that are also worth looking at. However, if you do not need a List and would like to be able to retrieve your Object by a known key a HashMap would be a better choice. For instance you should be able to use a JPanel or a TextField as the key.
A: Try using the collections, from java.util.collection package.
1. If every question you create has a unique identifier attached to it, then try to use Map, where let an Integer be your unique identifier and String may be the question
Map<Integer, String> map = HashMap<Integer, String>();
2. If you are storing the question is in sequence, List may also suffice.
List<String> list = ArrayList<String>();
A: Do you mean ArrayList?
You could also use a Map to have a key and then the JPanel as an instance?
It sounds like an ArrayList is better and then you generate a new JPanel biased on the Object/String in the ArrayList when it is clicked on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11970602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Comment out a whole hyperlink block with sed in an HTML file I'd like to remove certain hyperlinks which all contain "legacy/" in the URL in many HTML files. However, some of them are in one line
<a href=".../legacy/..."> ... </a>\n
while others are not. How can I use sed to replace them all at one time?
So far I've tried
sed -ri 's/(.+legacy\/[[:print:]]+<\/a>.*$)/<!--\1-->/g' wave-on-a-string.html
which only replaces hyperlink in one line. I then realized that sed read one line at a time only. However, I couldn't find out how to matches multi (uncertain number of) lines hyperlink block.
The HTML files have some contents like this:
<a class="other-sim-page" href="legacy/wave-on-a-string.html" dir="ltr">
<table>
<tr>
<td>
<img style="display: block;" src="../../images/icons/sim-badges/flash-badge.png" alt="Flash Logo" width="44" height="44">
</td>
<td>
<span class="other-sim-link">原始模擬教學與翻譯</span>
</td>
</tr>
</table>
</a>
...
<p>瀏覽<a href="legacy/wave-on-a-string.html#for-teachers-header">更多活動</a>。</p>
...
<a href="legacy/radiating-charge.html" class="simulation-link">
<img class="simulation-list-thumbnail" src="../../sims/radiating-charge/radiating-charge-128.png" id="simulation-display-thumbnail-radiating-charge" alt="Screenshot of the simulation 電荷輻射" width="128" height="84"/><br/>
<strong><span class="simulation-list-title">電荷輻射</span></strong><br/>
<span class="sim-display-badge sim-badge-flash"></span>
</a>
...
and it only matches and replaces the second hyperlink since it is in one line.
I'd like to replace all the hyperlink blocks (<a href="..."> ... </a>) also if they stretch over several lines.
A: With GNU sed for -z and using all 3 blocks of input you provided together in one file as input:
$ sed -z '
s:@:@A:g; s:}:@B:g; s:</a>:}:g;
s:<a[^<>]* href="legacy/[^}]*}:<!--&-->:g;
s:}:</a>:g; s:@B:}:g; s:@A:@:g
' file
<!--<a class="other-sim-page" href="legacy/wave-on-a-string.html" dir="ltr">
<table>
<tr>
<td>
<img style="display: block;" src="../../images/icons/sim-badges/flash-badge.png" alt="Flash Logo" width="44" height="44">
</td>
<td>
<span class="other-sim-link">原始模擬教學與翻譯</span>
</td>
</tr>
</table>
</a>-->
...
<p>瀏覽<!--<a href="legacy/wave-on-a-string.html#for-teachers-header">更多活動</a>-->。</p>
...
<!--<a href="legacy/radiating-charge.html" class="simulation-link">
<img class="simulation-list-thumbnail" src="../../sims/radiating-charge/radiating-charge-128.png" id="simulation-display-thumbnail-radiating-charge" alt="Screenshot of the simulation 電荷輻射" width="128" height="84"/><br/>
<strong><span class="simulation-list-title">電荷輻射</span></strong><br/>
<span class="sim-display-badge sim-badge-flash"></span>
</a>-->
The first line turns } into a character than can't be present in the input afterwards by converting all }s to @Bs and then turns all </a>s into } so that char can be negated in a bracket expression as [^}] in the regexp for the string you want to replace, the second line does the actual replacement you want, and the third line restores all }s to </a>s and then @Bs to }s.
Manipulating the input to create a char that can't exist in the input is a fairly common sed idiom to work around not being able to negate strings in regexps. See https://stackoverflow.com/a/35708616/1745001 for another example with additional explanation.
This will of course fail if you have strings in your input that resemble the strings you're trying to match but in reality it's probably good enough for your specific input - you'll just have to think about what it does and check it's output to verify.
A: You are not using the proper tool for this task.
sed is a great tool to perform find and replace using regex, however regex (based on DFA) are unable to parse nested structures like JSON or XML trees (as there is no limit to the depth of the nesting). I would therefore recommend using a XML/HTML parser.
For example you can use XSLT:
Input:
$ cat webpage.html
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<a href="https://www.w3schools.com">Visit W3Schools</a>
<p>My second paragraph.</p>
<a href="legacy/radiating-charge.html" class="simulation-link">
<img class="simulation-list-thumbnail" src="../../sims/radiating-charge/radiating-charge-128.png" id="simulation-display-thumbnail-radiating-charge" alt="Screenshot of the simulation 電荷輻射" width="128" height="84"/><br/>
<strong><span class="simulation-list-title">電荷輻射</span></strong><br/>
<span class="sim-display-badge sim-badge-flash"></span>
</a>
</body>
</html>
Stylesheet:
$ cat remove_legacy.xslt
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8" omit-xml-declaration="yes"/>
<!-- copy the whole structure recursively -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- when you meet a tag a that contains href -->
<xsl:template match="//a[contains(@href,'legacy')]">
<!-- add comment starting tag -->
<xsl:text disable-output-escaping="yes">
<!--
</xsl:text>
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
<!-- add comment ending tag -->
<xsl:text disable-output-escaping="yes">
-->
</xsl:text>
</xsl:template>
</xsl:stylesheet>
Output:
$ xsltproc --html remove_legacy.xslt webpage.html
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<a href="https://www.w3schools.com">Visit W3Schools</a>
<p>My second paragraph.</p>
<!--
<a href="legacy/radiating-charge.html" class="simulation-link">
<img class="simulation-list-thumbnail" src="../../sims/radiating-charge/radiating-charge-128.png" id="simulation-display-thumbnail-radiating-charge" alt="Screenshot of the simulation 電荷輻射" width="128" height="84"><br>
<strong><span class="simulation-list-title">電荷輻射</span></strong><br>
<span class="sim-display-badge sim-badge-flash"></span>
</a>
-->
</body>
</html>
As you can see the href that does not contain legacy is not commented.
A: try gnu sed
sed -E '/<a\s+.*href=.*legacy\/.*<\/a>/d; /<a\s+.*href=.*legacy\//,/<\/a>/d' wave-on-a-string.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55572926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: INNER JOIN vs CROSS JOIN vs CROSS APPLY One of the joys of SQL is that there are often multiple ways to do the same thing, so which is "best"?
In this case, I am inserting records from an 'Import' table and giving them all a default security level of 'Viewer' (could have different Key IDs in different databases). I can do this in at least three different ways (and probably even a few more): CROSS JOIN, CROSS APPLY, and INNER JOIN. Any suggestions as to which would be best for either performance or design purposes? I'm leaning towards the Cross Apply.
This question might have already been answered, but I can't find it, and lately I keep running into this need in my development, so I might as well learn the best way.
Here are the 3 example statements. Which is the best way to JOIN the SecRole table?
INSERT INTO LocStaff (LocationID, StaffID, SecRoleID)
SELECT i.LocationID, s.StaffID, sr.SecRoleID
FROM IntStaff i
JOIN Staff s ON i.EmployeeID = s.StaffNumber
CROSS JOIN SecRole sr
WHERE sr.Name = 'Viewer'
INSERT INTO LocStaff (LocationID, StaffID, SecRoleID)
SELECT i.LocationID, s.StaffID, sr.SecRoleID
FROM IntStaff i
JOIN Staff s ON i.EmployeeID = s.StaffNumber
JOIN SecRole sr ON sr.Name = 'Viewer'
INSERT INTO LocStaff (LocationID, StaffID, SecRoleID)
SELECT i.LocationID, s.StaffID, sr.SecRoleID
FROM IntStaff i
JOIN Staff s ON i.EmployeeID = s.StaffNumber
CROSS APPLY (SELECT TOP 1 SecRoleID FROM SecRole WHERE Name = 'Viewer') sr
A: The first two are equivalent. Whether you use an inner join or cross join is really a matter of preference in this case. I think I would typically use the cross join, because there is no real join condition between the tables.
Note: You should never use cross join when the intention is a "real" inner join that has matching conditions between the tables.
The cross apply is not doing the same thing. It is only choosing one row. If your intention is to get at most one matching row, then use cross apply. If the intention is to get exactly one matching row, then use outer apply.
A: We use Cross join (or just the keyword Join) only when we don't have any column in common among the tables (not the best structure design!) or we need all the possible cases. I don't know your table structure but I'm assuming table SecRole has no foreign or common key to Staff and InsStaff. In this case I would use a Right join (outer joins) here to get all the result from the first inner join between Staff and InsStaff and then put them next to SecRole desired records.
Here is the concept of a Right join
http://www.dofactory.com/sql/right-outer-join
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42587081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Getting an error while trying to print a string in Groovy I try to print the following in Groovy web console
def str1=''C:\mkjk\sys''
println str1
I get the following error:
Impossible to parse JSON response: SyntaxError: Unexpected token '
A: It should be:
def str1 = 'C:\\mkjk\\sys' // single quotes
or
def str1 = "C:\\mkjk\\sys" // double quotes
or
def str1 = """C:\\mkjk\\sys""" // three double quotes (multiline string)
or
def str = '''C:\\mkjk\\sys''' // three single quotes (multiline string)
or
def str1 = /C:\mkjk\sys/ // forward slashes (slashy string)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26627645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How can I create a dictionary of frames of an image in Python? I have a .tif image which has 4 dimensions - x, y, z, and no. of channels. There are 15 frames in total. I want to slice each frame and save it as its own image, and be able to perform operations on the slices.
I have I have previously saved each slice as its own .tif file in a directory, however I will soon be working with an image that has 640 frames, so 640 .tif files is a lot. Is there a way to save each new frame to a dictionary perhaps, labelling each frame as slice0, slice1 etc?
Here is the code I have used for saving each slice as a separate .tif file (it works):
for i in range(no_frames):
im.seek(i)
im.save('page_%s.tif' % (i,))
Here is something along the lines I wish to do with the dictionary:
slices = {}
for i in range(movie.n_frames):
slices["page_{0}".format(i)] = movie.seek(i)
Thanks !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71716129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the gcc alternate of "relro" and "now" flags in "mingw-gcc"? What is the gcc alternate of gcc flag "relro" in "mingw-gcc" ?
A: MinGW is actually GCC, so the flags are the same. But some flags depend on platform-specifics.
Relocation Read-Only (RELRO) is specifically for ELF binaries, which are not supported on Windows.
Instead Windows uses the PE/PE+ format (which is based on the COFF format.
There is support for -Wl,--dynamicbase and ASLR (address space layout randomization) that you could take a look at to see if it helps you accomplish your goal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73106203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drools KieContainer does not fire rules with custom classloader I am trying to add a non-existing method to a Java bean, compile it and use the newly added method in Drools rules. Via a custom class loader.
I am using CompilerUtils to bind newly modified class to the custom ClassLoader as follows:
ClassLoader loader = new ClassLoader(){};
String className = "com.example.Transaction";
String path = "file:D:/workspace/Transaction.class.tmp"; // a tmp file that contains source for Java bean
try {
URL transactionUrl = new URL(path);
URLConnection connection = transactionUrl.openConnection();
InputStream input = connection.getInputStream();
String transactionClass = new String(StreamUtils.copyToByteArray(input), StandardCharsets.UTF_8);
System.out.println(transactionClass);
String javaCode = "\npublic int test() {\n" +
" return 3;\n" +
" }\n" +
"}";
String updatedClassString = transactionClass.substring(0, transactionClass.length() - 1).concat(javaCode);
Class<?> classB = CompilerUtils.CACHED_COMPILER.loadFromJava(loader, className, updatedClassString); // This is where the loader is made aware of the newly compiled class
return loader;
} catch (IOException | ClassNotFoundException exception) {
e.printStackTrace();
}
return null;
And this is where I give access to drools my classloader
final KieServices kServices = KieServices.Factory.get();
final KieFileSystem kFileSystem = kServices.newKieFileSystem();
final KieModuleModel kModuleModel = KieRulePopulator.kieModuleModel();
if (kModuleModel != null) kFileSystem.writeKModuleXML(kModuleModel.toXML());
kServices
.newKieBuilder(kFileSystem, classLoader)
.buildAll();
}
KieContainer container = kServices.newKieContainer(kServices
.getRepository()
.getDefaultReleaseId(), classLoader);
This is how I fire rules
final KieBaseConfiguration configuration = KieServices.Factory.get().newKieBaseConfiguration();
final KieSession kSession = container
.getKieContainer()
.newKieBase(configuration)
.newKieSession();
Transaction someTransaction = new Transaction();
kSession.insert(transaction);
kSession.fireAllRules();
And this is my rule
rule "Rule_31F6DE769554404B89D4E3B7B5979CA1"
dialect "java"
no-loop true
when
tr : Transaction( test == 3 )
then
System.out.println("deneme");
end
A: I have load Transaction class from containers classloader and it worked.
final KieSession kSession = container
.getKieContainer()
.newKieBase(configuration)
.newKieSession();
Class<?> classA = container.getKieContainer().getClassLoader().loadClass("com.example.Transaction");
Object transaction = classA.getDeclaredConstructor().newInstance();
kSession.insert(transaction);
kSession.fireAllRules();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72390675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Modifying values of array during Iteration using JSTL c:forEach I am trying iterate over an array in a JSP using c:forEach. What I want is to convert each array element to lowercase, remove all the white spaces and concatenate '-wrapper' at the end of it. I want to use this value as the id of an div.
For example, if an element in array is 'Mobile Devices', I want the final value to be 'mobiledevices-wrapper'.
I'm not aware if there are such function like replace() and toLower() in JSTL. How can I modify the below code. Please help.
<c:forEach items="${userChargingTypeAccessArray}" var="chargingType">
<div id="${chargingType.value}"></div>
</c:forEach>
A: You can use fn:replace() and fn:toLowerCase().
<c:forEach items="${userChargingTypeAccessArray}" var="chargingType">
<div id="${fn:toLowerCase(fn:replace(chargingType.value,' ',''))}-wrapper"></div>
</c:forEach>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45613529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Caroufredsel responsive visible items I am building a caroufredsel for a responsive website (with only 3 states: 960px, 720px and 320px).
It's working great when you load the page in one of these states. It shows the correct number of items (3, 2 and 1 respectively).
But, when you resize the window, the number of visible items doesn't change. I was thinking about a $(window).resize() call, but I can't find how you can adjust the Caroufredsel settings after it is initialized.
$('#caroufredsel').carouFredSel({
infinite: true,
auto: false,
pagination: false,
prev: {
button: '#prev',
key: 'left'
},
swipe: {
onTouch: true,
onMouse: true
},
next: {
button: '#next',
key: 'right'
},
items: {
visible: 'variable'
}
});
A: What you need to do in your resize-callback is the following:
var $carouselContainer = $('#caroufredsel');
var resizeCallback = function() {
var showThatManyItems = 3; // determine the number of items to be shown depending on viewport size
$carouselContainer.trigger('configuration', [
'items', {
visible : showThatManyItems
}
], true);
}
A: If I'm not mistaken, don't you need "responsive:true," as one of the parameters?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19996394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Missing function header C++ i am getting this error when i want to build my cpp file.
Severity Code Description Project File Line Suppression State
Error C2447 '{': missing function header (old-style formal list?) Win32Project1 d:\persoonlijk\documenten\2e leerjaar\c++\win32project1\win32project1\leerlinggegevens_hfst3.cpp 2
Here is the code i am using:
/*Hoofdstuk 3, Leerlinggegevens*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
int lnr;
string lnm;
string oplnm;
string klasm;
//DECRALEREN
cout << "Voer je leerlingnummer in: \n";
cin >> lnr;
cout << "Vul je naam in: \n";
cin >> lnm;
cout << "Vul je opleiding in: \n";
cin >> oplnm;
cout << "Vul je klas in: \n";
cin >> klasm;
cout << "Jouw ingevulde leerleerlinggegevens bestaan uit: \n" << "Leerling " << lnr << " met leerlingnummer " << lnm << "staat ingeschreven bij opleiding " << oplnm << " \n" << "Leerlingnummer " << lnr << " zit in klas " << klasm << endl;
system("PAUSE");
}
Thanks for your time!
A: Your code works fine in Windows environment it seems.
In case you are running on Linux environment, but I am not quite sure whether system("PAUSE");works over there or not. Even, this seems to me as non - portable code.
I would recommend you to use cin.get() or getchar() instead, to make it portable. If you want to more why I am saying so, you can go through this link: http://www.gidnetwork.com/b-61.html
A: The source code you posted compiles just fine with both Microsoft Visual C++ 2015 and gcc (tried on ideone.com).
The only way to get the C2447 compile error you are getting, with Visual C++, is to add a semi-colon (;) right after main():
int main();
{
(but Visual Studio 2015 editor highlights the error, even before compiling the code).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42158637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement this feature in javascript ? Make uncertain , divorce, the wife say! In the Javascript, could I define a class, the class itself can also when a function call, similar to the index, such as:
function A()
{
}
var a=new A();
var v=a(); //Use ordinary/like Javascript function use
A: This is a abuse of the constructor function syntax (it will work without the new)
function A(message)
{
return function(){alert("Make " + message);}
}
var a = new A("uncertain, divorce the wife say");
var v = a(); //Use ordinary/like Javascript function use
A: No,This instance "a" has no object "A" prototype
a instanceof A===false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2702919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement unit tests in NativeScript using TestBed and Jasmine? I'm setting up a NativeScript-Angular project, and would like to implement unit tests using Jasmine-Karma in order to test my components using css selectors. How can I setup a simple unit test (beyond the sample test provided on the official repository) for a simple component?
This is for a new project using NativeScript CLI 6.0 with Android API level 28.
I have tried using the regular Angular TestBed which is claimed to be supported on this blog post:
https://www.nativescript.org/blog/announcing-the-nativescript-4.1-release
I have also tried following their working tests on the official nativescript-angular repository: https://github.com/NativeScript/nativescript-angular/tree/master/tests
Either way I seem to be doing something wrong when I try to do my own implementation because I get the following errors:
Uncaught Error: Zone already loaded
TypeError: Cannot read property 'injector' of null
TypeError: Cannot read property 'getComponentFromError' of null
TypeError: Cannot read property 'currentPage' of undefined
Has anyone managed to get TestBed unit tests working in NativeScript with Jasmine-Karma?
test-main.ts
import "nativescript-angular/zone-js/testing.jasmine";
import { nsTestBedInit } from "nativescript-angular/testing";
nsTestBedInit();
example.ts
import { ItemsComponent } from '~/app/item/items.component';
import { By } from '@angular/platform-browser';
import { nsTestBedBeforeEach, nsTestBedAfterEach, nsTestBedRender } from 'nativescript-angular/testing';
describe('item-detail-component', () => {
beforeEach(nsTestBedBeforeEach(
[ItemsComponent]
));
afterEach(nsTestBedAfterEach());
it(`should contain items`, () => {
return nsTestBedRender(ItemsComponent).then((fixture) => {
fixture.detectChanges();
const list = fixture.debugElement.query(By.css('.list-group'));
expect(list).toBeDefined();
});
})
});
I am expecting to be able to run the test without getting any errors.
I have included two repos for each test implementation.
Steps to reproduce:
1. Download repo
2. yarn install
3. tns test android
https://github.com/gsavchenko/nativescript-ns-testbed
update
for anyone else wondering how to further test their front-end using end to end tests it seems like appium is the go to https://docs.nativescript.org/plugins/ui-tests
A: To use TestBed you have to alter your karma.conf.js to:
// list of files / patterns to load in the browser
files: [
'src/tests/setup.ts',
'src/tests/**/*.spec.ts'
],
The file src/tests/setup.ts should look like this for jasmine:
import "nativescript-angular/zone-js/testing.jasmine";
import {nsTestBedInit} from "nativescript-angular/testing";
nsTestBedInit();
or if using mocha:
import "nativescript-angular/zone-js/testing.mocha";
import {nsTestBedInit} from "nativescript-angular/testing";
nsTestBedInit();
You'll find a sample here: https://github.com/hypery2k/tns_testbed_sample
A: I was facing the same issue like you. I finally found a way to make Unit Test in Nativescript-Angular works.
To fix my issue I add beforeAll(() => nsTestBedInit()); and afterAll(() => { });
Also change from TestBed to nsTestBed...
I just follow the idea on https://github.com/NativeScript/nativescript-angular/blob/master/tests/app/tests/detached-loader-tests.ts
Also add into tsconfig.tns.json file this line:
"include": ["src/tests/*.spec.ts"],
My issue now is split all test into multiple file. Like appComponent in a test file
and homeCompenent in a second test file. When the app grow the unit test also grow, we need organize our code.
Here my code (file name: src/tests/test.spec.ts):
import "reflect-metadata";
import { AppComponent } from "../app/app.component";
import { nsTestBedBeforeEach, nsTestBedAfterEach, nsTestBedRender, nsTestBedInit } from "nativescript-angular/testing";
import { HomeComponent } from "@src/app/home/home.component";
describe("AppComponent", () => {
beforeAll(() => nsTestBedInit());
afterAll(() => { });
beforeEach(nsTestBedBeforeEach([AppComponent, HomeComponent]));
afterEach(nsTestBedAfterEach());
it("should be: app works!", () => {
return nsTestBedRender(AppComponent).then((fixture) => {
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.title).toBe("app works!");
});
});
describe("HomeComponent", () => {
it("should contain: Home works!", () => {
return nsTestBedRender(HomeComponent).then((fixture) => {
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.title).toBe("Home works!");
});
});
});
});
And here the result:
JS: NSUTR: downloading http://192.168.10.169:9876/context.json
JS: NSUTR: eval script /base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?be3ff9a5e2d6d748de5b900ac3c6d9603e2942a7
JS: NSUTR: eval script /base/node_modules/karma-jasmine/lib/boot.js?945a38bf4e45ad2770eb94868231905a04a0bd3e
JS: NSUTR: eval script /base/node_modules/karma-jasmine/lib/adapter.js?3098011cfe00faa2a869a8cffce13f3befc1a035
JS: NSUTR: eval script /base/src/tests/test.spec.bundle.js?6e0098824123f3edc2bb093fa874b3fdf268841e
JS: NSUTR: beginning test run
NativeScript / 28 (9; Android SDK built for x86): Executed 1 of 2 SUCCESS (0 secs / 0.545 secs)
NativeScript / 28 (9; Android SDK built for x86): Executed 2 of 2 SUCCESS (0.829 secs / 0.735 secs)
TOTAL: 2 SUCCESS
JS: NSUTR: completeAck
NativeScript / 28 (9; Android SDK built for x86) ERROR
DisconnectedClient disconnected from CONNECTED state (transport error)
NativeScript / 28 (9; Android SDK built for x86): Executed 2 of 2 SUCCESS (0.829 secs / 0.735 secs)
A: Your issue is happening because of these lines.
beforeAll(() => nsTestBedInit());
afterAll(() => { });
Each test file tries to initialize test bed. Make sure that you initialize it in your entry component.
Please refer entry file test-main.ts specified in karma.config.js
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57186925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: PHP newer version fails decoding json "version like" string (ex: "0.7.4"->"0.7") Executing this code in PHP I expect the string "0.7.4" remaining as "0.7.4" https://3v4l.org/gX4vM
$value = "0.7.4";
if(!empty($value))
{
$jsonValue = json_decode($value);
if(!empty($jsonValue)) $value = $jsonValue;
}
print_r( $value,false);
And this is true for almost every PHP version but in my AWS with PHP 5.6.9, and in this php sandbox (5.6.4 ?), I'm getting 0.7 http://ideone.com/2uuoHw
In my code $value can be a deserializable string or a simple string ("['a','b']", "{'a':'10'}", "abc", "2500", etc.) and I expect the json to decode it properly. But I have no idea how to avoid this strange issue.
Any idea?
Thanks
A: 0.7.4 is not valid JSON.
This is valid JSON {"data": "0.7.4"}
Learn more about JSON here json.org
JSON to Object:
$json = '{"data": "0.7.4"}';
$obj = json_decode($json);
var_dump($obj);
JSON to Array:
$json = '{"data": "0.7.4"}';
$array = json_decode($json, true);
var_dump($array);
A: Two things:
*
*Don't check if the result is empty(), check if the result is NULL. json_decode returns NULL if the input could not be decoded.
*The input string 0.7.4 is invalid JSON. Period. It worked at one point in PHP, but it was a mistake that it worked at all. You should not depend on this behavior as it is incorrect.
The modified version of your code should probably look like:
$value = "0.7.4";
if( !empty($value) )
{
$jsonValue = json_decode($value);
if ( $jsonValue !== NULL ) {
// Pick a value to return
$value = $jsonValue->something;
} else {
// Do nothing, leave $value as is
}
}
var_dump($value);
A: As stated, 0.7.4 is not valid JSON (according to the JSON spec), but PHP's json_decode can decode scalar values, too.
PHP implements a superset of JSON as specified in the original » RFC 4627 - it will also encode and decode scalar types and NULL. RFC 4627 only supports these values when they are nested inside an array or an object.
From: http://php.net/json_decode
If you had $value ='"0.7.4"'; (7 characters), then json_decode() would decode this to the string 0.7.4. But since your value is 0.7.4 (5 characters, since it's missing the double quotes), it can't be decoded.
Your example at https://3v4l.org/gX4vM is failing to decode $value and just printing out its original value (see: https://3v4l.org/e3um2).
EDIT: For some weird reason, the example at http://ideone.com/2uuoHw is decoding 0.7.4 as the float 0.7. That shouldn't happen. You should only get 0.7 if you stated with $value = "0.7": (see: https://3v4l.org/H2W5M).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33371780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Customize WooCommerce single product sharing icons In WooCommerce single product page, there is sharing icons by default (Facebook, Twitter, GooglePlus, and Telegram). I want to change this icons and use other social medias, for example WhatsApp,... I searched every code pages of the theme and WooCommerce plugin but I couldn't find where it reads this. so I wanted to know where can I find and change this code or if there is a filter code that I can change the social icons with it.
Edit: there is a switch to show sharing icons at product's details page.
this code is showing the switch at admin panel:
<tr valign="top">
<th scope="row">sharing product</th>
<td>
<label class="ios-switch">
<input type="checkbox" name="product-sharing" value="1" <?php checked( irk_get_option( 'product_sharing' ), 1 ); ?>>
<span class="slider round"></span>
</label>
</td>
</tr>
but I couldn't find the code for retrieving 'irk_get_option' and showing the icons. there was the below code at single-page.php of the theme, but it isn't for product detail page and doesn't change the icons there.
<footer class="card-footer">
<?php
if ( irk_get_option( 'short_link' ) ) {
echo '<div class="short-link float-right" data-toggle="tooltip" data-title="click for copy."><i class="mdi mdi-link-variant"></i>' . wp_get_shortlink() . '</div>';
}
?>
<div class="sharing list-inline">
<a href="https://telegram.me/share/url?url=<?php echo get_the_permalink(); ?>&text=<?php echo get_the_title(); ?>" class="list-inline-item">
<i class="mdi mdi-telegram"></i>
</a>
<a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo get_the_permalink(); ?>" class="list-inline-item">
<i class="mdi mdi-facebook"></i>
</a>
<a href="https://web.whatsapp.com/send?text=<?php echo get_the_title(); ?>&url=<?php echo get_the_permalink(); ?>" class="list-inline-item">
<i class="mdi mdi-whatsapp"></i>
</a>
<a href="https://plus.google.com/share?url=<?php echo get_the_permalink(); ?>" class="list-inline-item">
<i class="mdi mdi-google-plus"></i>
</a>
</div>
</footer>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67225093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use PhantomJS to extract html and text I try to extract all the text content of a page (because it doesn't work with Simpledomparser)
I try to modify this simple example from the manual
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementById('myagent').textContent;
});
console.log(ua);
}
phantom.exit();
});
I try to change
return document.getElementById('myagent').textContent;
to
return document.textContent;
This doesn't work.
What's the right way to do this simple thing?
A: This version of your script should return the entire contents of the page:
var page = require('webpage').create();
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementsByTagName('html')[0].outerHTML;
});
console.log(ua);
}
phantom.exit();
});
A: There are multiple ways to retrieve the page content as a string:
*
*page.content gives the complete source including the markup (<html>) and doctype (<!DOCTYPE html>),
*document.documentElement.outerHTML (via page.evaluate) gives the complete source including the markup (<html>), but without doctype,
*document.documentElement.textContent (via page.evaluate) gives the cumulative text content of the complete document including inline CSS & JavaScript, but without markup,
*document.documentElement.innerText (via page.evaluate) gives the cumulative text content of the complete document excluding inline CSS & JavaScript and without markup.
document.documentElement can be exchanged by an element or query of your choice.
A: To extract the text content of the page, you can try thisreturn document.body.textContent; but I'm not sure the result will be usable.
A: Having encountered this question while trying to solve a similar problem, I ended up adapting a solution from this question like so:
var fs = require('fs');
var file_h = fs.open('header.html', 'r');
var line = file_h.readLine();
var header = "";
while(!file_h.atEnd()) {
line = file_h.readLine();
header += line;
}
console.log(header);
file_h.close();
phantom.exit();
This gave me a string with the read-in HTML file that was sufficient for my purposes, and hopefully may help others who came across this.
The question seemed ambiguous (was it the entire content of the file required, or just the "text" aka Strings?) so this is one possible solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18453993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: RESTful Design: Paging Collections I am designing a REST api that needs paging (per x) enforces from the server side.
What would be the right way to page through any collection of resources:
Option 1:
GET /resource/page/<pagenr>
GET /resource/tags/<tag1>,<tag2>/page/<pagenr>
GET /resource/search/<query>/page/<pagenr>
Option 2:
GET /resource/?page=<pagenr>
GET /resource/tags/<tag1>,<tag2>?page=<pagenr>
GET /resource/search/<query>?page=<pagenr>
If 1, what should I do with GET /resource? Redirect to /resource/page/0, reply with some error or reply with the exact same as /resource/page/0 without redirecting?
A: With my limited understanding of what REST is about, then the following might be the "most" restful.
GET /resource/?page=<pageenr>&asof=<datetime>
Since the content of the representation would never change unexpectedly, and caching could be used.
But to actually answer your question, I think the parameter page is the preferred method.
A: I'd go with option (2). Why?
*
*You can later add page-size parameter to the query so the client can specify the page size.
*In case no page parameter was specified you can just return the first page (the default). In many cases you client might need only the first page, so it simplifies the protocol between client and server.
A: What the URI looks like is not the most important part. What you should be thinking about instead is how it is presented to the user. A page should for example have a link to the "next" page and another link to the "previous" page (if there is one). Take a look at RFC 5005 Feed Paging and Archiving
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/501013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Clearing the screen in C++ using other compilers Hello I'm interested in learning a way to clear the screen. I'm using C++ but it seem that some possible code to use are only known to work with Windows compilers. I'm using Ubuntu with a "g++ compiler".
code i have research in order to use and have tried...
---This don't work with g++ compiler
system("cls"); error: sh: 1: cls: not found
system("clrscr"); sh: 1: clrscr: not found
I stumble upon this code that it works, i know it prints lot's of lines ...
cout << string(50, '\n');
any cleaner methods that I could possibly use ?
A: The Unix command for clearing the terminal is clear.
Alternatively, send the terminal codes for doing same (this varies by terminal, but this sequence works for most):
cout << "\033[H\033[2J";
(I got the sequence by simply running clear | less on my system. Try it and see if you get the same result.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18326415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Unable to navigate to next variable defined in eclipse template I have written eclipse template to inject a Dependency :
${:import(org.springframework.beans.factory.annotation.Autowired)}
private final ${class_to_inject} ${var_name};
@Autowired
public ${primary_type_name}(${class_to_inject} ${var_name}){
this.${var_name} = ${var_name};
}
When I select class_to_inject using ctrl-space. After successful import, eclipse loses the focus on other template variables. I am not able to navigate to next variable using tab key. Below are screen shot that explain the problem -
step 1: Injecting the template
step 2: Template loaded in Eclipse
step 3: Selecting the Bean
Location Repository is bean that I want to inject
step 4: Dependency added in code
After adding the dependency now, I am unable to move to next variable var_name using tab key as IDE loses the focus on template variables.
Any eclipse expert can help here?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72600439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Concatenate distinct values from multiple columns I have this in a table
party1 | party2
A | E
B | D
C | H
D | B
E | A
F | H
G | I
Result I am trying to get is distinct concatenation of party1 and party2, i.e.
AE (will same as EA so only one instance is required)
BD (will same as DB so only one instance is required)
CH
FH
GI
Party1 and Party2 are formed using CTE. Parties A-I flows from single table Party and are identified as party1 and party2 using business logic of code 4 and 1.
Below is the query i could form
WITH CTE AS
(
SELECT
DISTINCT CPR1.PARTY_IDENTIFIER AS PARTY1,
CPR2.PARTY_IDENTIFIER AS PARTY2,
CCR.CLIENT_RELATIONSHIP_TYPE_CODE,
CPR1.CLIENT_TYPE_CODE
FROM GOLD.CLIENT_TO_PARTY_RELATIONSHIP CPR1
JOIN GOLD.CLIENT_TO_CLIENT_RELATIONSHIP CCR
ON CPR1.CLIENT_IDENTIFIER = CCR.CLIENT_IDENTIFIER
AND CCR.CLIENT_RELATIONSHIP_TYPE_CODE = '04'
AND CPR1.CLIENT_TYPE_CODE = '1'
JOIN GOLD.CLIENT_TO_PARTY_RELATIONSHIP CPR2
ON CPR2.CLIENT_IDENTIFIER = CCR.CLIENT_IDENTIFIER
WHERE (CPR1.PARTY_IDENTIFIER_INACTIVE_DATE IS NULL OR CPR1.PARTY_IDENTIFIER_INACTIVE_DATE ='')
AND (CPR2.PARTY_IDENTIFIER_INACTIVE_DATE IS NULL OR CPR2.PARTY_IDENTIFIER_INACTIVE_DATE ='')
AND CPR1.PARTY_IDENTIFIER<>CPR2.PARTY_IDENTIFIER
AND CPR1.DATA_AS_OF_DATE LIKE '201912%'
AND CPR2.DATA_AS_OF_DATE LIKE '201912%'
AND CCR.DATA_AS_OF_DATE LIKE '201912%'
)
SELECT
DISTINCT CONCAT("PG","_",TRIM(CAST(PARTY1 AS STRING)) ,"_",TRIM(CAST(PARTY1 AS STRING))) AS PG_KEY,
party1,
party2
FROM CTE
A: Your description says that you are actually not interested in the concatenation but in the (2-element) sets that are composed from the paired data. Representing them (as you do) as a 2-letter string, go along the following template.
WITH CTE AS
(
SELECT CPR1.PARTY_IDENTIFIER AS PARTY1,
CPR2.PARTY_IDENTIFIER AS PARTY2,
CCR.CLIENT_RELATIONSHIP_TYPE_CODE,
CPR1.CLIENT_TYPE_CODE
FROM GOLD.CLIENT_TO_PARTY_RELATIONSHIP CPR1
JOIN GOLD.CLIENT_TO_CLIENT_RELATIONSHIP CCR
ON CPR1.CLIENT_IDENTIFIER = CCR.CLIENT_IDENTIFIER
AND CCR.CLIENT_RELATIONSHIP_TYPE_CODE = '04'
AND CPR1.CLIENT_TYPE_CODE = '1'
JOIN GOLD.CLIENT_TO_PARTY_RELATIONSHIP CPR2
ON CPR2.CLIENT_IDENTIFIER = CCR.CLIENT_IDENTIFIER
WHERE (CPR1.PARTY_IDENTIFIER_INACTIVE_DATE IS NULL OR CPR1.PARTY_IDENTIFIER_INACTIVE_DATE ='')
AND (CPR2.PARTY_IDENTIFIER_INACTIVE_DATE IS NULL OR CPR2.PARTY_IDENTIFIER_INACTIVE_DATE ='')
AND CPR1.PARTY_IDENTIFIER<>CPR2.PARTY_IDENTIFIER
AND CPR1.DATA_AS_OF_DATE LIKE '201912%'
AND CPR2.DATA_AS_OF_DATE LIKE '201912%'
AND CCR.DATA_AS_OF_DATE LIKE '201912%'
)
select
distinct CASE WHEN party1 < party2
THEN party1 || party2
ELSE party2 || party1
END pair
FROM CTE
;
Caveats
Pull the CTE definition out of the subquery. Concat syntax may vary depending on the sql dialect / database product you are using.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61596740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google API to check if new version of app has been deployed I have an app on the Google Playstore and I want a way to alert my users whenever I deploy a new version of the app. I want to know how to make this possible. Does Google Playstore provide any APIs or SDKs to make this possible?
I use React-native for development, incase the answer may depend on this.
A: Yes, the Playstore supports this feature named In-app-updates
There is no official implementation for this here, but take a look at this.
A: You can use In-app updates:
In-app updates is a Google Play Core libraries feature that prompts
active users to update your app.
There are mainly two update flows.
*
*Flexible updates
*Immediate updates
Here is a detailed guide that describes how to support in-app updates in your app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74263396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Stopping sqlldr I have a process that load data using sqlldr.
But sometimes due to other factors in the system it does not stop in a reasonable amount of time. Is there a way to kill sqlldr safely. Using kill -9.
A: A few issues you can run into if you just kill the sqlldr process:
*
*If the number of commit rows is small you may have data already-commited which will now have to be removed. This may not matter if you are truncating the tables before use but the cleanup is an operational issue that is dependent upon your system.
*If the number of commit rows and the size of your file is large then you may get issues with the rollback segments being too small or the rollback itself taking a long time to complete (shouldn't an issue if you are using direct path).
You can kill using kill -9 as mentioned, or you can kill the session from within the database:
alter system kill session 'sid,serial#';
If you are using Windows then you can use the orakill utility.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8724321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can someone explain JS Event Loop? So I kind of understand the JS event loop, but still have a few questions. Here is my scenario and a few questions.
So let's say I have these functions:
*
*function1 - reads an absolute huge file.
*function2 - console.log("Hey");
*function3 - console.log("What's up");
The way I am understanding this, and correct me if I'm wrong, what would happen is that the function1, function2, and function3, would be added to the queue. Then function1 would be added to the call stack followed by the next two functions.
Now the part where I'm confused is because the first function is going to take an extremely long time what happens to it? Does it get pushed somewhere else so that the next two functions are executed? I think the answer to this is that the only way it gets pushed somewhere else so that you can continue running is to make it an asynchronous function. And the way you make it a asynchronous function is either by using a callback function or promises. If this is the case how does it know that this is a asynchronous function? And where does it get pushed to so that the other two functions can be executed since they are relatively simple?
I think I answered the question myself but I keep confusing myself so if somebody could explain in extremely simple terms that would be great and sorry for the extremely stupid question.
A: Ordinary function calls are not pushed on the event queue, they're just executed synchronously.
Certain built-in functions initiate asynchronous operations. For instance, setTimeout() creates a timer that will execute the function asynchronously at a future time. fetch() starts an AJAX request, and returns a promise that will resolve when the response is received. addEventListener() creates a listener that will call the function when the specified event occurs on an element.
In all these cases, what effectively happens is that the callback function is added to the event queue when the corresponding condition is reached.
When one of these functions is called, it runs to completion. When the function returns, the event loop pulls the next item off the event queue and runs its callback, and so on.
If the event queue is empty, the event loop just idles until something is added. So when you're just starting at a simple web page, nothing may happen until you click on something that has an event listener, then its listener function will run.
In interactive applications like web pages, we try to avoid writing functions that take a long time to run to completion, because it blocks the user interface (other asynchronous actions can't interrupt it). So if you're going to read a large file, you use an API that reads it incrementally, calling an event listener for each block. That will allow other functions to run between processing of each block.
There's nothing specific that identifies asynchronous functions, it's just part of the definition of each function. You can't say that any function that has a callback argument is asynchronous, because functions like Array.forEach() are synchronous. And promises don't make something asychronous -- you can create a promise that resolves synchronously, although there's not usually a point to it (but you might do this as a stub when the caller expects a promise in the general case). The keyword async before a function definition just wraps its return value in a promise, it doesn't actually make it run asynchronously.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72496077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why i can't retrieve username and password from Firebase realtime database I want to login using username and password that is stored in Firebase realtime database. But my code does not work. I include my database picture and code. Please help me.
This is database image:
This is my main activity code MainActivity.java
databaseReference=FirebaseDatabase.getInstance().getReference("Client");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Query query = databaseReference.child("Client").orderByChild("username").equalTo(editTextUsername.getText().toString().trim());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot user : dataSnapshot.getChildren()) {
Users usersBean = user.getValue(Users.class);
if (usersBean.password.equals(editTextPassword.getText().toString().trim())) {
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "wrong", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
Here is my users java class Users.java
public class Users {
String email;
String id;
String password;
String username;
public Users() {
}
public Users(String email, String id, String password, String username) {
this.email = email;
this.id = id;
this.password = password;
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
A: To solve this, please change the following line of code:
databaseReference=FirebaseDatabase.getInstance().getReference("Client");
to
databaseReference=FirebaseDatabase.getInstance().getReference();
There is no need to get a reference of the Client node since you are using a call to .child("Client") in your query.
Edit:
To solve the error you get now according to your comment, plase change the type of your id property in your Users class from String to long and the getter and setter like this:
public class Users {
String email;
long id;
String password;
String username;
public Users() {
}
public Users(String email, long id, String password, String username) {
this.email = email;
this.id = id;
this.password = password;
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55334387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to wrap pjsua-lib with Swig? I'm trying to find a way to wrap the whole pjsua library into java classes with SWIG to use it on android. Does anyone have an experience in how to proceed?
Regards
A: Take a look at http://code.google.com/p/csipsimple, they have already created Java wrapper with SWIG.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16526382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GPU usage with Cuda and Pytorch When I started to use GPU for ML applications, i went to the task manager to see how much GPU it used and found six different graphs, in which just 2 were showing activity. Compute_0 and Copy. The Compute_0 had an interval between 85-95 % and Copy 5-15 %, but it just represented a 8-12% of the full use of the GPU.
I would like to know how it exactly works and find if there's a way to increase that 8-12% because it's also other graph with title Compute_1 indicating a constant zero usage, implying (by the name) that it can be used too.
This is the implementation code:
if torch.cuda.is_available():
device = torch.device('cuda:0')
I'm working with a NVIDIA GeForce 940MX
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59508030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: fwrite result PHP Im currently trying to write a few words on a file, and then open it.
currently, i do have the following outcome:
When my desired outcome would be something like:
How come it is like that?
TextAr is just some numbers from a textarea. ( one id each line)
code:
$text = preg_replace('/\n+/', "\n", trim($_POST['ids']));
$textAr = explode("\n", $text);
foreach ($textAr as $k=>$v) if(empty(trim($v))) unset($textAr[$k]);
$textAr = array_filter($textAr, 'trim');
$handle = fopen("file.txt", "w");
$saveresult = '';
foreach ($textAr as $line) {
$line = str_replace(' ', '', $line);
$line = preg_replace('/\D/', '', $line);
$result = httpPost($url, $line);
$showID = ($showID ? "".$result['id']." -" : '');
$notexisting = ($showasnull ? 0 : "N/A");
if ($result['manual'] == true) {
$saveresult .= "".$showID." Manual".PHP_EOL;
}
if ($result['hit'] == true && $result['manual'] != true) {
$saveresult .= "".$showID." " . $result['price'] . "".PHP_EOL;
} else if ($result['hit'] == false) {
$saveresult .= "".$showID." ".$notexisting."".PHP_EOL;
}
$saveresult .= "\r\n";
?>
<?PHP }
fwrite($handle, $saveresult);
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
EDIT
i removed $saveresult .= "\r\n"; but still same result.
EDIT 2:
example of textAr:
array(2) { [0]=> string(8) "43631132" [1]=> string(8) "43631132" }
example of $result
array(4) { ["id"]=> string(8) "43631132" ["price"]=> int(0) ["hit"]=> bool(false) ["manual"]=> bool(false) }
A: You can write each line independantly. This way you can check if the line itself is empty before writing.
foreach ($textAr as $line) {
$saveresult = "";
$line = str_replace(' ', '', $line);
$line = preg_replace('/\D/', '', $line);
$result = httpPost($url, $line);
$showID = ($showID ? "".$result['id']." -" : '');
$notexisting = ($showasnull ? 0 : "N/A");
if ($result['manual'] == true) {
$saveresult .= "".$showID." Manual";
}
if ($result['hit'] == true && $result['manual'] != true) {
$saveresult .= "".$showID." " . $result['price'];
} else if ($result['hit'] == false) {
$saveresult .= "".$showID." ".$notexisting;
}
$saveresult = trim($saveresult);
if (!empty($saveresult)) {
fwrite($handle, $saveresult.PHP_EOL);
}
}
fclose($handle);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42066328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: code has expired (within the last hour) dropbox Hi everyone i am new in dropbox api (php version).
i am getting authCode using authorizeUrl, its working good for only one time if i reload page error message shows on
'HTTP status 400 {"error_description": "code has expired (within the last hour)", "error": "invalid_grant"}
how to get permanent authCode from dropbox.
$appInfo = dbx\AppInfo::loadFromJsonFile("api-key.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = "****************************************";
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);
A: Found the solution in this error
some steps to solve this problem
*
*go to Apps page Dropbox apps
*add your site or localhost link to OAuth 2 Redirect URIs
*next to generate access token, then copy the access token and use it .
*finally remove this lines
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
and paste directly in your access token into
$accessToken =
"VTEp2cvkQ8************************************";
it's working perfectly
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44800891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Check if the Intervals of a list are overlaped with the Intervals of another list I have two lists with Intervals ie
[2021-06-29T00:00:00.000+03:00/2021-06-30T23:59:00.000+03:00, 2021-07-01T00:00:00.000+03:00/2021-07-06T23:59:00.000+03:00]
[2021-06-25T00:00:00.000+03:00/2021-06-30T23:59:59.000+03:00, 2021-07-01T00:00:00.000+03:00/2021-07-06T23:59:59.000+03:00, 2021-07-06T00:00:00.000+03:00/2021-07-11T23:59:59.000+03:00, 2021-07-11T00:00:00.000+03:00/2021-07-16T23:59:59.000+03:00....]
I want to check whether the elements of the first one overlaps with the elements of the second or not. In case there isn't an overlap, I need to have a list with the intervals that they aren't overlaped with the first list.
A: Essentially, you'd want to go over the first list, and for each item go over the second list and check if any interval overlaps it. Streams make this a tad more elegant:
List<Interval> list1 = // some intervals...
List<Interval> list2 = // some more internvals...
List<Interval> result =
list1.stream()
.filter(i1 -> list2.stream().allMatch(i2 -> i1.overlap(i2) == null))
.collect(Collectors.toList());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68132858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Occurence of a element in unsorted array by O(n) This is driving me nuts:(
Problem statement:
An unsorted array is inputed.Next the user gives a collection of numbers and the program should print the occurrence of the given number in that array.
This should run at O(n) time complexicity.
Example:
Input array:[1, 1, 1, 2, 2, 0]
Collection of numbers:
1
2
1
0
Output:
3
2
3
1
Constrains:Array can be of size 10^5 and collection of number can be of size 10^5
P.S:I have made a code with O(n^2)
#include<stdio.h>
#include<stdlib.h>
void main(){
int *n,size,key,count=0;
scanf("%d",&size);
n=(int*)malloc(size*sizeof(int));
for(int i=0;i<size;i++){
scanf("%d",&n[i]);
}
scanf("%d",&key);
for(int i=0;i<key;i++){
count=0;
int temp=0;
scanf("%d",&temp);
for(int j=0;j<size;j++){
if(temp==n[j])
count+=1;
}
printf("\n");
if(count==0){
printf("NOT PRESENT");
}
else{
printf("%d",count);
}
}
}
Any help is welcomed :)
A: The range of elements is small. So create an array of counters for the possible values and increment the count for each value you find. For example, if you find 2, increment counter[2].
Then given your collection of numbers, just do an array lookup to get the count.
A: The time complexity is O(max(m,n)) where m is the size of the array and n is the size of the collection. The space required is O(p) where p is the range of the integers that may appear in the array. We'll use p0 to denote the lower bound of this range.
The solution is simple:
*
*Construct an array C of size p and set all values to zero
*Walk over the input array and for each value k - increase C[k-p0] by 1. Now you have a count of each value.
*Walk over the collection and for each value k - print C[k-p0]
A: A very simple way to do this would be to have your resulting array's keys be where the values are.
My C skills are kind of weak, but here is how in pseudo-C (you'll have to tweak it to make it work properly:
int size = 10*10*10*10*10;
int[size] input = getInput();
int[size] results = new int[size](0); // fill array with zeros
for(int i = 0; i < size; i++) {
if (input[i] === -1)
break; // assuming -1 signifies the end of the input
output[input[i]]++; // increment the value at the index that matches the number by one
}
for(int i = 0; i < size; i++) {
if (output[i] === 0)
continue; // number wasn't in array
printf('%d', output[i]);
}
Basically, you put the input of the array in the matching index of output.
So, if your input is 5,3,2,1,1,5,3,2,1, you would put into output:
output[5]++;
output[3]++;
output[2]++;
output[1]++;
output[1]++;
output[5]++;
output[3]++;
output[2]++;
output[1]++;
resulting in an array that looks like this:
[0, 3, 2, 2, 0, 1]
Then you just output it, skipping the zeros because they weren't present.
A: You can simply make a array of 10^5 and initialize it with 0. Now iterate over array and increment the value in array. Like you encounter a 5 increment arr[5] and now you can answer the queries in O(1) time.
Below is a code in java.
import java.util.Scanner;
public class test
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in());
int n=s.nextInt();
int arr[]=new int[100001]; //Array is initialized 0
for(int i=0;i<n;i++)
{
int num=s.nextInt();
arr[num]++;
}
while(s.hasnextInt())
{
int p=s.nextInt();
System.out.println(arr[p]);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45196515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to ask for admin permission in a batch? Since a few weeks, my scripts for modifying my IP address don't work anymore. I suspect an update of Windows 10.
Up to now, I was using the script given in this thread :
@echo on
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params= %*
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
<YOUR BATCH SCRIPT HERE>
But now, I got this error:
Failed to load script: C:\Users\me\AppData\Local\Temp\getadmin.vbs: access denied
The strange thing is, getadmin.vbs is indeed created in the Temp directory.
Here is the exact output :
C:\Users\arc\Desktop\ConfigLAN>REM --> Check for permissions
C:\Users\arc\Desktop\ConfigLAN>IF "AMD64" EQU "amd64" ("C:\WINDOWS\SysWOW64\cacls.exe" "C:\WINDOWS\SysWOW64\config\system" 1>nul 2>&1 ) ELSE ("C:\WINDOWS\system32\cacls.exe" "C:\WINDOWS\system32\config\system" 1>nul 2>&1 )
C:\Users\arc\Desktop\ConfigLAN>REM --> If error flag set, we do not have admin.
C:\Users\arc\Desktop\ConfigLAN>if '5' NEQ '0' ( echo Requesting administrative privileges... goto UACPrompt ) else (goto gotAdmin ) Requesting administrative privileges...
C:\Users\arc\Desktop\ConfigLAN>echo Set UAC = CreateObject("Shell.Application") 1>"C:\Users\arc\AppData\Local\Temp\getadmin.vbs"
C:\Users\arc\Desktop\ConfigLAN>set params=
C:\Users\arc\Desktop\ConfigLAN>echo UAC.ShellExecute "cmd.exe", "/c ""C:\Users\arc\Desktop\CONFIG~1\newBatch.bat"" ", "", "runas", 1 1>>"C:\Users\arc\AppData\Local\Temp\getadmin.vbs"
C:\Users\arc\Desktop\ConfigLAN>"C:\Users\arc\AppData\Local\Temp\getadmin.vbs"
(error is triggered here)
C:\Users\arc\Desktop\ConfigLAN>del "C:\Users\arc\AppData\Local\Temp\getadmin.vbs"
C:\Users\arc\Desktop\ConfigLAN>exit /B
A: You can use the following sequence that works perfectly fine for me.
@echo off
::::::::::::::::::::::::::::::::::::::::::::
:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' (goto gotPrivileges) else (goto getPrivileges)
:getPrivileges
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo For Each strArg in WScript.Arguments >> "%temp%\getadmin.vbs"
echo If strArg = WScript.Arguments.Item^(0^) Then d = Left^(strArg, InStrRev^(strArg,"\"^) - 1^) >> "%temp%\getadmin.vbs"
echo args = args ^& " " ^& strArg >> "%temp%\getadmin.vbs"
echo Next >> "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd.exe", ^("/c start /D """ ^& d ^& """ /B" ^& args ^& " ^& exit"^), , "runas", 4 >> "%temp%\getadmin.vbs"
cscript "%temp%\getadmin.vbs" ""%~s0"" %*
del /q "%temp%\getadmin.vbs"
exit /b
:gotPrivileges
:: Your code here
This VBS script uses perfectly the UAC.ShellExecute, you can point by yourself the changes. You used a lot of tricks and the VBS code doesn't even call UAC in the correct way, which is why it gives permission denied. I believe that the use of cacls and this script was very useful in the past, used by Malware to obtain administrative access without the user's permission, there are many programs that use icacls for this, I will not even point out, but that may have made using icacls difficult.
You can also use Powershell previously to do it.
Powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c C:\YourPath\yourprogram.bat'"
Both of the scripts works perfectly fine for me. I can see a lot of errors in your .vbs, but there is no point in pointing them out because the script is not yours.
I recommend that you use the Powershell, it is much more useful and simple, to integrate:
NET FILE >NUL 1>NUL 2>NUL
if %errorlevel% equ 0 (goto gotprivileges) else (start Powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c C:\YourPath\yourprogram.bat'" & exit)
Hope this helps,
K.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67226353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# / VBS Automate Team Project Creation in TFS 2015 Update 3 I'm looking for a way to automate team project creation in TFS 2015 Update 3.
I did a quick crawl over the web and found various posts on how to do it but nothing specific to 2015 version update 3.
Some links I found:
#1
#2
I'd like to do it as simple and lightweight as possible.
A rough idea would be to fill up all the details needed e.g.:
Sign in details, server, collection, project name, etc... on an excel, save the information somewhere (like an xml for presented on link#2) and trigger a batch file to do the necessary stuff via vbs macro.
To be honest I do not know where to start yet, like how to even automate the project creation part.
Appreciate if you can point me in the right path to start this out. Ideas are also welcome :). Thanks in advance!
A: You could use this REST API to create a team project. TFS also provide to using C# code to create a team project:
public static TeamProject CreateProject()
{
string projectName = "Sample project";
string projectDescription = "Short description for my new project";
string processName = "Agile";
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(new NetworkCredential("username", "password", "domain")));
VssConnection connection = new VssConnection(new Uri("http://v-tinmo-12r2:8080/tfs/MyCollection"),c);
// Setup version control properties
Dictionary<string, string> versionControlProperties = new Dictionary<string, string>();
versionControlProperties[TeamProjectCapabilitiesConstants.VersionControlCapabilityAttributeName] =
SourceControlTypes.Git.ToString();
// Setup process properties
ProcessHttpClient processClient = connection.GetClient<ProcessHttpClient>();
Guid processId = processClient.GetProcessesAsync().Result.Find(process => { return process.Name.Equals(processName, StringComparison.InvariantCultureIgnoreCase); }).Id;
Dictionary<string, string> processProperaties = new Dictionary<string, string>();
processProperaties[TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityTemplateTypeIdAttributeName] =
processId.ToString();
// Construct capabilities dictionary
Dictionary<string, Dictionary<string, string>> capabilities = new Dictionary<string, Dictionary<string, string>>();
capabilities[TeamProjectCapabilitiesConstants.VersionControlCapabilityName] =
versionControlProperties;
capabilities[TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityName] =
processProperaties;
//Construct object containing properties needed for creating the project
TeamProject projectCreateParameters = new TeamProject()
{
Name = projectName,
Description = projectDescription,
Capabilities = capabilities
};
// Get a client
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
TeamProject project = null;
try
{
Console.WriteLine("Queuing project creation...");
// Queue the project creation operation
// This returns an operation object that can be used to check the status of the creation
OperationReference operation = projectClient.QueueCreateProject(projectCreateParameters).Result;
// Check the operation status every 5 seconds (for up to 30 seconds)
Operation completedOperation = WaitForLongRunningOperation(connection, operation.Id, 5, 30).Result;
// Check if the operation succeeded (the project was created) or failed
if (completedOperation.Status == OperationStatus.Succeeded)
{
// Get the full details about the newly created project
project = projectClient.GetProject(
projectCreateParameters.Name,
includeCapabilities: true,
includeHistory: true).Result;
Console.WriteLine();
Console.WriteLine("Project created (ID: {0})", project.Id);
}
else
{
Console.WriteLine("Project creation operation failed: " + completedOperation.ResultMessage);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception during create project: ", ex.Message);
}
return project;
}
private static async Task<Operation> WaitForLongRunningOperation(VssConnection connection, Guid operationId, int interavalInSec = 5, int maxTimeInSeconds = 60, CancellationToken cancellationToken = default(CancellationToken))
{
OperationsHttpClient operationsClient = connection.GetClient<OperationsHttpClient>();
DateTime expiration = DateTime.Now.AddSeconds(maxTimeInSeconds);
int checkCount = 0;
while (true)
{
Console.WriteLine(" Checking status ({0})... ", (checkCount++));
Operation operation = await operationsClient.GetOperation(operationId, cancellationToken);
if (!operation.Completed)
{
Console.WriteLine(" Pausing {0} seconds", interavalInSec);
await Task.Delay(interavalInSec * 1000);
if (DateTime.Now > expiration)
{
throw new Exception(String.Format("Operation did not complete in {0} seconds.", maxTimeInSeconds));
}
}
else
{
return operation;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43624368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Arranging Images in a grid layout I have a set of thumbnail images to be shown in a div. Width of the div can vary based on the screen size.The images are all of fixed size of 150px * 150px with a padding of 5px. I want these thumbnail images to be arranged in a grid layout and also I want these images to be center aligned with respect to the outer div. I could try text-align: center on the outer div.
But this way the images in the last row would appear in the center wherein I want them to be arranged from left. So i thought of calculating the free space available after placing the images and apply a padding-left (=freespace/2) to the outer div so that contents would appear center aligned.
This is the code I have used.
CSS
#outer {
border: 1px solid;
resize: horizontal;
overflow: auto;
width: 700px;
padding: 0;
}
.inner {
width: 150px;
height: 150px;
background: #ccc;
padding: 5px;
display: inline-block;
}
jQuery
$(document).ready(function() {
$("#position").click(function() {
var maxCount = Math.floor($("#outer").outerWidth() / $(".inner").outerWidth());
console.log("maxcount::" + maxCount);
var freeSpace = $("#outer").outerWidth() - ($(".inner").outerWidth() * maxCount);
console.log("freeSpace::" + freeSpace);
$("#outer").css("padding-left", freeSpace / 2);
});
$("#text").toggle(function() {
$("#outer").css("text-align","center");
},function(){
$("#outer").css("text-align","left");
});
});
HTML
<button id="position">
Adjust position
</button>
<button id="text">
Toggle text align
</button>
<div id="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>
A demo here - http://jsfiddle.net/userdude/fzjrm/1/
But this is not working as I expected because the contents are not perfectly center aligned. May be that logic needs some tweaking and I am not able to figure it out.
A: At first I would recommend you to use $("#outer").innerWidth() when calculating maxCount as in general if you have also a padding in container, you can use only the inner part of the element.
And finally as a solution to your problem I can suggest you to add
box-sizing: border-box;
-moz-box-sizing: border-box;
to the #outer div to maintain its width. Unfortunately this doesn't work as I expect, there is a little more space from rigth side than from left. But there is another strange thing that I don't understand, those white spaces between divs (see the screenshot), I can't find CSS affecting these parts. I think that these spaces are affecting the calculation that's why I get a little more left-padding than we need.
Here is the jsFiddle link
A: Here you go: http://jsfiddle.net/dan_barzilay/fy494/
What i did was instead of changing the #outer padding left to freeSpace / 2 and by that increasing the size only from the left side I changed both padding-right and padding-left by freeSpace / 4 to keep the images in the center.
$("#outer").css({"padding-left": freeSpace / 4, "padding-right": freeSpace / 4});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12122578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Updating Cordova Plugin results in failed plugin I'm running Cordova 3.4.1 and decided to update the one and only plugin I have, Console. I did based on the update to plugins dated April 23, 2014 ( http://cordova.apache.org/news/2014/04/23/plugins.release.html ).
Updating is done by first removing and then adding back the plugin. In other words:
cordova plugin rm org.apache.cordova.console
cordova plugin add org.apache.cordova.console
I then ran
cordova build
which does a lot of voodoo, after which I compiled and ran the app on iOS via Xcode.
The result is this fail: every time my code calls console.log I get this error in the XCode debugger output
CDVPlugin class CDVLogger (pluginName: Console) does not exist.
ERROR: Plugin 'Console' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
-[CDVCommandQueue executePending] [Line 158] FAILED pluginJSON = [
"INVALID",
"Console",
"logLevel",
[
"LOG",
"text i want to see"
]
]
Plainly the process of updating plugins is not working properly. How can fix this myself? And if I do will it effect any subsequent fix by the Cordova team?
FWIW: I repeated this process, tried an cordova platform update ios to no avail. I am loath to reinstall the entire thing given all the mysterious Xcode configuration and build stuff and hoping there's a simple fix...
A: I diff'ed the project against an earlier version I'd kept that worked properly and came up with this fix:
In Xcode, under your Phonegap or Cordova project, select
Target -> Build Phases -> Compile Sources
Add your plugin into the list there, in this case CVLogger.m located in your file structure under "Plugins".
After this, the project compiles without error and the console plugin works. No need to reinstall and reconfigure your entire project for this...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23460990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: bootstrap css file and jquery js file are not linked in thymeleaf header file I am a newbie of spring boot. The below image shows the folder location of my bootstrap css file and jquery js file on spring boot thymeleaf template.
And these are my home html scripts
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<div th:fragment="header-css">
<title>Spring Boot Blog</title>
<script th:src="@{/js/jquery-2.1.4.min.js}"></script>
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" th:href="@{/css/bootstrap.min.css}" />
<link rel="stylesheet" type="text/css" href="/css/main.css" th:href="@{/css/main.css}" />
</div>
</head>
<body>
<div th:fragment="header">
.....
But css and js scripts are not linked at all.
Any idea, please!
== UPDATED ==
I am evaluating the spring blog example. I think my problem is related to login controller. First this is the login controller codes.
@Controller
public class LoginController {
@GetMapping("/login")
public String login(Principal principal) {
String username = (principal != null ? principal.getName() : "ANONYMOUS");
if(principal != null) {
return "redirect:/home";
}
// ALWAYS PRINTING "ANONYMOUS is WRONG!!!!"
System.out.println(username + " is WRONG!!!!");
return "/login";
}
}
And even more
return "/login"
line brings wrong files. In below login.html file,
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<div th:replace="/fragments/header :: header-css"/>
</head>
<body>
<div th:replace="/fragments/header :: header"/>
<div class="container">
<div class="row" style="margin-top:20px">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form th:action="@{/login}" method="post">
<fieldset>
the controller call the following css file and display its contents.
<link rel="stylesheet" type="text/css" href="/css/main.css" th:href="@{/css/main.css}" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53314186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: adding values put in by users i am trying to write some sort of code, which adds two numbers the user puts in, this is my code:
l.add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int i= Integer.parseInt(l.input1.getText().toString());
int j= Integer.parseInt(l.input2.getText().toString());
int sum = i+j;
l.result.setText(sum);
}
});
for some reason the emulator just collapse, i am new to this all, and am really greatfull for any help. THANK YOU.
A: setText() of TextView either accepts a String value as parameter to display or a integer value which is a string resource id that you have described in res/values/strings.xml
The integer value you passing is a real value and you have make the TextView to understand it as real value and not a String resource reference. So convert the integer to String and then set the value inside text view.
Solution:
l.add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int i= Integer.parseInt(l.input1.getText().toString());
int j= Integer.parseInt(l.input2.getText().toString());
int sum = i+j;
l.result.setText(String.valueOf(sum));
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32671337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AttributeError: 'NoneType' object has no attribute 'cursor' Error in Robot framework for Stored Procedure call I am working on updating database records using Stored procedure in Robot framework.
I am referring https://franz-see.github.io/Robotframework-Database-Library/api/1.0.1/DatabaseLibrary.html#Call%20Stored%20Procedure.
After executing the script I get the following error
AttributeError: 'NoneType' object has no attribute 'cursor'
I have no clue why I get this error, I searched on various stackoverflow threads but couldn't figure out how to resolve this. Could you please help?
Here is my code sample
*** Settings ***
Suite Setup Connect To Database Using Custom Params ibm_db_dbi ${db_connection}
Suite Teardown Disconnect From Database
Library DatabaseLibrary
Library OperatingSystem
Resource ../resources/variables/variables.txt
*** Test Cases ***
Test updatedb storedprocedure
@{ParamList} = Create List 3 <Key><empid>1234</empid></Key> 10.5
@{QueryResults} = Call Stored Procedure ${SPName} ${ParamList}
Log to console ${QueryResults}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52753022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I get the file owner on Windows with Go? I'm trying to get file owner on Windows with Go and it's such a pain to find any help on it after hours on go src I found this:
// TODO(brainman): fix all needed for os
func Fchdir(fd Handle) (err error) { return EWINDOWS }
func Link(oldpath, newpath string) (err error) { return EWINDOWS }
func Symlink(path, link string) (err error) { return EWINDOWS }
func Fchmod(fd Handle, mode uint32) (err error) { return EWINDOWS }
func Chown(path string, uid int, gid int) (err error) { return EWINDOWS }
func Lchown(path string, uid int, gid int) (err error) { return EWINDOWS }
func Fchown(fd Handle, uid int, gid int) (err error) { return EWINDOWS }
func Getuid() (uid int) { return -1 }
func Geteuid() (euid int) { return -1 }
func Getgid() (gid int) { return -1 }
func Getegid() (egid int) { return -1 }
func Getgroups() (gids []int, err error) { return nil, EWINDOWS }
Does it mean its not yet possible ?
I probably miss something any help would be appreciated.
A: File and security systems are operating system specific. Go is modeled on Linux, Darwin, and other Unix-like operating systems. The Go Windows port emulates most things, but, as you have discovered, not everything (some are just stubs). If the features you need are not in the Go standard library, look for independently written, open-source Go packages. The last resort is to write your own interface to the Microsoft Windows API.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51321950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Idiomatic way to get from nested structures in Clojure Which of these is more idiomatic Clojure?
(def book {:title "Joy of Clojure"
:authors ["Michael Fogus" "Chris Houser"]})
(get-in book [:authors 0])
;; => "Michael Fogus"
(-> book :authors first)
;; => "Michael Fogus"
When I have much more complicated data structures, this becomes more relevant. Presumably there's no technical difference between the two?
A: get-in is better for nested structures, because many interesting keys are not callable, in particular indexes in a vector (other than first or second) or string keys in hash-maps.
user=> (get-in [{:a 0} 1 nil "unknown" {:b {"context info" 42}}] [4 :b "context info"])
42
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28347223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to solve VBA Insert into linked table error 3134? I am working on a MS ACCESS front end connected to a Oracle SQL database via linked tables.
The issue: I try to insert some records with the statement below and always receive the 3134 error syntax error in insert statement
INSERT INTO DD_HR (USER_NAME, IS_DELETED, DATE_CREATED, DATE_MODIFIED, SNAPSHOT, HR_ID, COMPANY_CODE, CREATE_USER, CUSTOMER_NAME, CUSTOMER_NUMBER, DOCUMENT_NUMBER, PO_NUMBER, DUE_DATE, CURRENCY, ORIGINAL_AMOUNT, UNRESOLVED_AMOUNT, CREATED_DATE, CORRESPONDENCE, CORRESPONDENCE_DATE, PROCESSOR_DEADLINE_DATE, REASON_CODE, RESOLUTION_TYPE, STATUS, OWNER, PROCESSOR) VALUES ('username', 0, Now(), Now(), #05/10/2019#, 28588630, 'Org name', 'User name','Company',9999,'10397990','Subscription',#06/01/2019#,'USD',36558,36558,#04/25/2019#,'Yes',#04/25/2019#,#05/03/2019#,'Billing Issue','Rebill','Open','Billing WW','Billing WW')
Does anyone see from where the error might be? I tried to run the query in the database by just changing the Now() to sysdate and the dates from #mm/dd/yyyy# to to_date() just to be compliant with the Oracle SQL statements.
A: Ok, I got the error, and fixed the issue: the CURRENCY field name is also a restricted word and needs to be enclosed within '[]'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56077797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Type mismatch when trying to replace I have a variable age_n . it is numeric (float).
for exampel if i type
count if age_n>65
If gives me 77.
So then if I type
replace age_n = "0" if (age_n < "65")
it says type mismatch.
I have tried putting 65 without quotes and it still doesn't work.
A: Another form to do it is
recode age_n (0/65=0 "0") (66/150=1 "over 65")
So you have a dummy with your requirement (from 0 to 65, values change to 0, appearing a "0" in the table; from 66 to 150, values change to 1, appearing this time "over 65" in the table). If you want to maintain values of age_n,
gen age_n2=age_n
and do the process with age_n2 instead of age_n.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36222307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: asynchronous commenting using ajax I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
A: There are 3 main problems in your code:
*
*You are not returning anything from insert.php via ajax.
*You don't need to replace the whole comment_part, just add the new comment to it.
*Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
A: You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36243448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Postgres function returning a string from a select statement I am trying to get this function to return a string that comes from the SELECT statement.
CREATE OR REPLACE FUNCTION dbo.fnRepID (pram_ID BIGINT)
RETURNS varchar AS $$
DECLARE
pram varchar := '';
BEGIN
SELECT pram = pram || (Case COALESCE(a.Name, '') WHEN '' THEN '' ELSE b.Name || ' - ' END )
|| (Case COALESCE(b.Name, '' ) WHEN '' THEN '' ELSE b.Name || ' - ' END )
|| f.NAME || ';'
FROM dbo.ClassRelationship a
LEFT JOIN dbo.ClassRelationship b ON a.ParentClassID = b.ClassID and b.Type = 2 and a.Type = 1;
RETURN pram;
END;
$$ LANGUAGE plpgsql;
GRANT EXECUTE ON FUNCTION dbo.fnRepID (BIGINT) TO "postgres";
And this function creation seem to go through just fine, now I want to call this function with 0 as pram_ID but it's saying this basically no matter what I do.
ERROR: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function dbo.fnrepid(bigint) line 5 at SQL statement
SQL statement "SELECT dbo.fnRepID(0)"
PL/pgSQL function inline_code_block line 2 at PERFORM
SQL state: 42601
I have tried a DO PERFORM block as I have seen similar examples
DO $$ BEGIN PERFORM dbo.fnRepID(0); END $$;but I basically want to get the return value from this function somehow. If there's anything wrong with my procedures please let me know, as I am new to postgres. Thank you.
Edit: Would the following work if I want to append each row of the results into the same var? (can I use select into with the variable on both sides to append to itself?)
CREATE OR REPLACE FUNCTION dbo.fnRepID (pram_ID BIGINT)
RETURNS varchar AS $$
DECLARE
pram varchar := '';
BEGIN
SELECT pram || (Case COALESCE(a.Name, '') WHEN '' THEN '' ELSE b.Name || ' - ' END )
|| (Case COALESCE(b.Name, '' ) WHEN '' THEN '' ELSE b.Name || ' - ' END )
|| f.NAME || ';' INTO pram
FROM dbo.ClassRelationship a
LEFT JOIN dbo.ClassRelationship b ON a.ParentClassID = b.ClassID and b.Type = 2 and a.Type = 1;
RETURN pram;
END;
$$ LANGUAGE plpgsql;
GRANT EXECUTE ON FUNCTION dbo.fnRepID (BIGINT) TO "postgres";
A: You're doing
SELECT pram = (…) FROM dbo.ClassRelationship a …;
where (…) is an expression that is evaluated and then compared to the current value of pram (which was initialised to an empty string). The query does nothing else, there is no destination for this boolean value (comparison result) it computes, you're getting an error.
You most likely meant to either perform an assignment
pram = SELECT (…) FROM dbo.ClassRelationship a …;
or use an INTO clause:
SELECT (…) INTO pram FROM dbo.ClassRelationship a …;
Notice that you don't even need pl/pgsql to do this. A plain sql function would do as well:
CREATE OR REPLACE FUNCTION dbo.fnRepID(pram_ID BIGINT) RETURNS varchar
LANGUAGE sql
STABLE
RETURN (
SELECT
'' ||
(CASE COALESCE(a.Name, '') WHEN '' THEN '' ELSE b.Name || ' - ' END) ||
(CASE COALESCE(b.Name, '' ) WHEN '' THEN '' ELSE b.Name || ' - ' END) ||
f.NAME ||
';'
FROM dbo.ClassRelationship a
LEFT JOIN dbo.ClassRelationship b ON a.ParentClassID = b.ClassID AND b.Type = 2 AND a.Type = 1
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73128371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pass state as prop to child component As the title says, how can I pass state data to a new component. I have a parent class that loads some data from an IndexedDb.
I will pass the information of "image" as prop to my child component.
class Parent extends Component<Props> {
constructor(props: Props) {
super(props);
// map state to json structure
this.state = {
data: {
image: ''
[...]
};
}
public componentWillMount() {
const dataProvider = new DataProvider(DataProvider.DBNAME);
dataProvider.loadData('somedoc')
.then((data: object) => this.setState({data}));
}
public render() {
const {data}: any = this.stat
return (<Child image={data.image} />);
}}
In my child Component I will use the prop to make a new request for retrieving the image. The problem is that the prop in the componentWillMount method is empty.
interface IImageProps {
image: string;
}
Class Child extends Component<IImageProps> {
constructor(props: IImageProps) {
super(props);
}
public componentWillMount() {
console.log("image", this.props.image); // <-- it's allways empty
// do some async stuff
}
public render() {
console.log("image", this.props.image); // <-- the image information is shown
}}
What did I miss, cause in the render methode I can use the prop? How do I pass the variables correctly?
A: Thank you for helping. I solved my problem with the componentDidUpdate() method. As describe in the documentation https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/postrender_with_componentdidupdate.html
For now my final solution:
componentDidUpdate() {
const imageName: string = this.props.imageName;
const dataProvider = new DataProvider(DataProvider.DBNAME);
dataProvider.loadImage('somedoc', imageName)
.then((response: any) => {
let {imageDataUrl}: any = this.state;
if (imageDataUrl !== response) {
imageDataUrl = response;
this.setState({imageDataUrl});
}
})
.catch((error: any) => console.log(error));
}
A: Since your loadData function is asynchronous, data.image will be an empty string when the Child component is mounted.
You could e.g. wait with the rendering of the Child component until the request has finished.
Example
class Parent extends Component<Props> {
constructor(props: Props) {
super(props);
this.state = {
data: {
image: null
}
};
}
public componentDidMount() {
const dataProvider = new DataProvider(DataProvider.DBNAME);
dataProvider
.loadData("somedoc")
.then((data: object) => this.setState({ data }));
}
public render() {
const { data }: any = this.stat;
if (data.image === null) {
return null;
}
return <Child image={data.image} />;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51638428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to put translations from Developer Console in an android app's resource file? I paid for translation services from the Google Play Developer Console and all of the languages were translated successfully. I successfully translated my app's store listing description into 9 languages.
But how does one go about translating all of the strings in strings.xml? I downloaded a file with all of the translated strings, but what do I do with this and where do I put it?
A: You'll be needing to create separate folders for strings.xml that contains the different languages. You can see/read this from the How to Create Alternative Resources guide:
*
*res/values/strings.xml Contains English text for all the strings that the application uses, including text for a string named title.
*res/values-fr/strings.xml Contain French text for all the strings, including title.
*res/values-ja/strings.xml Contain Japanese text for all the strings except title.
If your Java code refers to R.string.title, here is what will happen
at runtime:
If the device is set to any language other than French, Android will
load title from the res/values/strings.xml file. If the device is set
to French, Android will load title from the res/values-fr/strings.xml
file.
Check this Multilingual app tutorial for a hands-on experience.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41572645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Typescript errors on creating instance via @nestjs/sequelize I am using Nest.js, ts and sequelize (@nestjs/sequelize, sequelize, sequelize-typescript) in my project.
I have such User model:
Column,
Model,
Table,
PrimaryKey,
DataType,
HasOne,
AllowNull,
Unique,
AutoIncrement,
} from 'sequelize-typescript';
import { UserLocationModel } from './user-location.model';
import { UserHealthIndicatorModel } from './user-health-indicator.model';
import crypto from 'crypto';
@Table({ tableName: 'User' })
export class UserModel extends Model<UserModel> {
@PrimaryKey
@Unique
@AutoIncrement
@Column(DataType.INTEGER)
id: number;
@AllowNull(false)
@Column(DataType.STRING(256))
name: string;
@AllowNull(false)
@Column(DataType.DATEONLY)
birthDate: Date;
@AllowNull(false)
@Unique
@Column(DataType.STRING(256))
email: string;
@AllowNull(false)
@Column(DataType.STRING(256))
passwordHash: string;
@AllowNull(false)
@Column(DataType.STRING(256))
token: string;
@HasOne(() => UserLocationModel)
location: UserLocationModel;
@HasOne(() => UserHealthIndicatorModel)
status: UserHealthIndicatorModel;
static makePasswordHash(password: string): string {
return crypto
.createHash('sha512')
.update(password, 'utf-8')
.digest('hex')
.substring(0, 526);
}
static makeRandomToken(): string {
return crypto.randomBytes(256).toString('hex').substring(0, 256);
}
}
And following register method:
public async register(
email: string,
password: string,
name: string,
birthDate: string,
): Promise<string> {
const oldUser = await this.userModel.findOne({ where: { email } });
if (oldUser) {
throw new ConflictException('User already exists');
}
const passwordHash = UserModel.makePasswordHash(password);
const user = await this.userModel.create({
email,
passwordHash,
name,
birthDate: new Date(birthDate),
token: UserModel.makeRandomToken(),
});
return user.token;
}
Typescript unable to compile:
error TS2345: Argument of type '{ email: string; passwordHash: string; name: string; birthDate: Date; token: string; }' is not assignable to parameter of type 'UserModel'.
I can remove generic from model (change "class UserModel extends Model<UserModel>" to "class UserModel extends Model") or comment ts compiler, but i wonder if exist more exquisite solution of this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66495940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Make a character move upwards on click I am making a game similar to Flappy Bird. The character is supposed to move upwards when the browser window is clicked, but my code for this does not work. Here are the relevant lines of code:
var dudeYSpeed = 0;
var dudeXSpeed = 0;
var dudeJumping = false;
var jumpSpeed = -3;
if (mouseDown && dudeJumping === false){
dudeJumping = true;
dudeYSpeed = jumpSpeed;
}
else {
translateY += dudeYSpeed;
dudeYSpeed += gravity;
dudeJumping = false;
}
translateX += dudeXSpeed;
A: You only update translateY and dudeYSpeed if dudeJumping is true. You should update these variables in every frame, no matter what the input was.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35827644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Swift 4.0 Right Padding a String I padded a Swift String up to X amount of characters. Which is the most efficient way to achieve this in Swift 4.0?
Option 1
extension String {
mutating func right_padding(padding: Int, padding_char: Character) {
let idx = self.endIndex
for _ in (1...padding) {
self.insert(padding_char, at: idx)
}
}
}
Option 2
SO article: Padding a swift String for printing
let test = "ghost" + "\(String(repeatElement("!", count: 40)))"
Option 3
???
Option 2 seems the simplest & most efficient, but I may be missing a better way...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47750201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I call python directly inside Ansible playbook, in a for loop? I have developed a playbooks that sends a mail indicating a list of 3-zero-padded numbers.
I want to make the padding in the for loop which prints the information in the mail body.
The playbook takes the number to pad from variable hostvars[host]['number'].
The padding is made via the Ansible syntax
myhost-{{ '%03d' % hostvars[host]['number']|int }}
as you can see in the following task.
Now, I would like to do the padding via Python, because later I want to make more formatting operations on each element printed by the loop.
So I have tried to substitute the upper line with
{{ "myhost-" + str(hostvars[host]['number']).zfill(3) }}
but I am getting this error:
Sending e-mail report...
localhost failed | msg: The task includes an option with an undefined variable. The error was: 'str' is undefined
So I tryed to substitute it (as suggested in comments of this question) with
myhost-{{ hostvars[host].number.zfill(3) }}
but now I get
Sending e-mail report...
localhost failed: {
"msg": "The task includes an option with an undefined variable. The error was: 'int object' has no attribute 'zfill'
}
So, how can I call python inside the for loop in order to manipulate the information to print with Python instead than Ansible?
Note: I want to call python directly in the loop and I don't want to define variable in python and substitute them into the body of the mail.
the task of my playbook:
- name: Sending e-mail report
community.general.mail:
host: myhost
port: 25
sender: mymail
to:
- people@mail.it
subject: "mail of day {{ current_date }}"
subtype: html
body: |
<br>title
<br>text
{% for host in mylist %}
myhost-{{ '%03d' % hostvars[host]['number']|int }}
<br>
{% endfor %}
<br>text
<br>closure
A: SOLVED
Since the first time the error was raised by the use of bulit-in python str() function , while other elements of python syntax did not raise any error, I guessed python built-in functions cannot be interpreted by Ansible (still I don't understand why).
So I looked up for a way to do the data manipulation by using some python methods of the object, instead than a python function.
So instead of turning the int object into a string with str(my_object), I exploited the int python method .__str__().
So I substituted the upper line with
myhost-{{ hostvars[host].number.__str__().zfill(3) }}
and this time it worked.
Conclusion
This makes me think one cannot use python functions inside ansible {{ }} tags, but only python objects methods.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75212803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Count duplicate values and display each different value from mysql table using PHP I have a table (url_log) with a column (referer) of urls. Some urls are unique and some are duplicates. Using PHP I want to display each different url (without repeating) and the number of times the url appears in the column.
This is what I came up with but it is definitely wrong:
echo '<table>';
$ref=$icdb->get_row("SELECT COUNT(referer) AS frequency, referer FROM url_log WHERE u = '".$dom."' GROUP BY referer ORDER BY frequency DESC");
foreach ($ref as $details) {
echo "<tr><td>".$details['referer']."</td><td>".$details['frequency']."</td></tr>";
}
echo '</table>';
Any tips?
A: If I understand your question, this should do it.
SELECT DISTINCT(referer), COUNT(referer) AS frequency
FROM url_log
GROUP BY referer
ORDER BY frequency DESC;
A: for selecting each different value of a column use this query
SELECT DISTINCT(column) AS columnname_key FROM table ;
to count duplicate use this code
SELECT Count(*) duplicatetable
FROM
(
select columname_to_check_dulicate_values, Count(*)
from tablename
group by name
having Count(*) > 1
) x
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21671947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: My panel-collapse not minimizing When I click the View Map link the collapse show but when I click it again
it the div does not hide. I don't know what to do. I searched but its not working.
<a href="#collapse2" data-toggle="collapse">View Map</a>
<div id="collapse2" class="panel-collapse collapse">
<?php
$map_url = $loc;
$map_url = str_replace(" ", "+", $map_url);
?>
<iframe width="350" height="250" allowfullscreen frameborder="0" src="http://maps.google.nl/maps?q=<?=$map_url?>&hl=nl&ie=UTF8&t=v&hnear=<?=$map_url?>&z=13&output=embed"></iframe>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34702955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Selenium webdriver test run speed varies I was curious about why does Selenium webdriver run with varying speed. I have noticed it that whenever I run the tests after a gap of 2-3 days the speed is noticeably slow as compared to tests run back to back day after day. The send keys execution is slow, like earlier it was all keys at once in textbox and now its one by one key input. I googled about this but there are no ways to control the speed of webdriver. Any clues about this?
Note:- Environment parameters (Net connectivity, PC free memory etc.) are the same they were when test run was at lightning speed.
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23478953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NetBeans save edited .jar I am currently using a library for "Notify My Android". The library is using an outdated URL so i tried to change it. I attached the source file and now I can edit the code. Before attaching the source file it just said "compiled code". But when i save it it does not seem to save the changes. It is still using the old URL. Also the change I made is underlined in blue. I hope somebody knows how to make the .jar to accept my changes.
Thanks in advance
A: it's highly discouraged to modify jars you depend on simply because if you ever want to upgrade versions you'd need to modify the new jar you are looking for.
In those situations you have these options:
*
*if it is an open source project, contribute to the project and correct the URL
*try and set the property from your code (this may not be possible in certain situations)
*try and extend the class you're trying to use and set the URL on the property you need (like the previous one, it may not be possible to do this)
*this should be your last resource: create your own project (from the original jar), make the changes you require, package it up and add it to you app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40008933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: IIS 404/405 errors I am running IIS7 on Windows 7 Pro. I have a VS2010 solution from which some projects are web services using IIS. Until recently all services worked correctly. However, whenever I add/configure/update a service reference or hit it directly via a web browser, I receive the following error:
There was an error downloading 'http://localhost/myapp.Web/myservice.svc'.
The request failed with HTTP status 404: Not Found.
Metadata contains a reference that cannot be resolved: 'http://localhost/myapp.Web/myservice.svc'.
The remote server returned an unexpected response: (405) Method Not Allowed.
The remote server returned an error: (405) Method Not Allowed.
If the service is defined in the current solution, try building the solution and adding the service reference again.
Further investigation reveals that this is likely IIS disallowing POST verbs or some other configuration error with the same effect (GET requests work fine and there are other developers using the same code with no issues). Trying to load the wsdl returns a 404.3.
I have tried recreating the sites and applications in IIS, changing their settings in the application pools, reinstalling IIS, etc without success. Does anyone have some ideas on how to fix what is going on?
More info: I'm not sure if it's relevant or not, but I changed some settings in MSMQ around the same time when I was trying to resolve permission problems, but all have been reverted, MSMQ has been reinstalled, etc and the problem with IIS remains.
Thanks.
A: I found the problem. Somehow my WCF and ASP.NET installations became corrupted. Reinstalling fixed the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6830888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: STL unordered map with custom key type I have some graph-related C++ code that works using an std::map structure. I do not need the elements to be strictly ordered, and therefore I would like to switch to an std::unordered_map structure.
The relevant part of the code is as follows:
typedef unsigned size_type;
struct internal_edge{
size_type node1_uid;
size_type node2_uid;
};
std::map<size_type, internal_edge> edges_;
When I switch to std::unordered_map, the compiler complains of "too few template arguments for class template 'unordered_map'". I tried putting in a default hasher and comparator (edit: thanks @rems4e for the corrected version):
struct size_type_hash {
std::size_t operator()(const size_type& k) const
{
return std::hash<size_type>()(k);
}
};
struct size_type_equal {
bool operator()(const size_type& lhs, const size_type& rhs) const
{
return lhs == rhs;
}
};
std::unordered_map<size_type, internal_edge, size_type_hash, size_type_equal> edges_;
This still yields the same error message:
./Graph.hpp:384:9: error: too few template arguments for class template 'unordered_map'
std::unordered_map<size_type, internal_edge, size_type_hash, size_type_equal> edges_;
^
/usr/bin/../lib/c++/v1/__hash_table:86:28: note: template is declared here
class _LIBCPP_TYPE_VIS unordered_map;
^
In file included from viewer.cpp:21:
./Graph.hpp:384:82: warning: private field 'edges_' is not used [-Wunused-private-field]
std::unordered_map<size_type, internal_edge, size_type_hash, size_type_equal> edges_;
My Makefile:
...
CXX := $(shell which clang++) -stdlib=libc++ -std=gnu++11
...
And the output of clang++:
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin12.5.0
Thread model: posix
I am sort of stuck there, as this is one of my first excursions into the world of C++. Any ideas on how to make the unordered map constructor work?
A: The standard library headers can include each other in unspecified ways, and headers can also contain extra declarations, so the error (if any) you get when you forget to include a header isn't necessarily what you'd expect.
Here, for instance, one of the headers you included included the <__hash_table> internal header of libc++, which contains a forward declaration of unordered_map. This forward declaration contains no default template arguments (it can't have default arguments because the rules of the language prevents you from giving a template parameter default arguments in two declarations in the same scope, so if it did and then the user also included <unordered_map> - which must provide default arguments - the compiler would complain), so when the compiler sees you trying to use unordered_map with the default arguments, it complains that you have too few template arguments, rather than that unordered_map isn't declared.
If you actually passed the requisite number of template arguments, the compiler will probably complain instead that you are attempting to instantiate a template that's declared but not defined.
The fix is simple: include <unordered_map>. There's no need for a custom hasher or comparer either for unsigned - just use the default ones.
A: Your problem probably comes from a bad copy-and-paste, as you are trying to get first and second fields from size_type variables, which are typedef to unsigned int.
Replace your hash functors by these and your code will compile:
struct size_type_hash {
std::size_t operator()(const size_type& k) const
{
return std::hash<size_type>()(k);
}
};
struct size_type_equal {
bool operator()(const size_type& lhs, const size_type& rhs) const
{
return lhs == rhs;
}
};
Just to be sure, do not forget to include the header in your file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25827993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AWS Amplify error on sign in: We have our backend made in AWS and using AWS Amplify in our iOS App for login/signup, API calls, storage access. We have enabled MFA(Multi-factor Authentication) for the signing in/up the users. The signup process is as follows:
*
*We let the user enter his phone number, email, and password for signing up. (signup API call)
*User receives OTP after initiating signup on their phone number (confirm signup API call)
*User is redirected to the sign-in page where he/she enters their email and password registered with us. (sign in API call)
*User receives an OTP again for authentication of their sign-in. (confirm sign-in API call)
Now, this process goes smoothly. The user gets confirmed and we get an active session for the current User. We get the current user ID through API
Amplify.Auth.getCurrentUser()
But,
If the user logs out successfully using Amplify.Auth.logout() and try to get back in through the sign-in process (step 3 and 4), we get the following error:
could not find 'Data'. the token is not a base64 encoded string
We decoded that the error is being generated in AWSMobileClientExtensions class, but we are not able to identify the source of the error. Please help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64869513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Difference between this Java and C code? I tried to convert some C code to Java, but it is working slightly different. It is XOR encryption and for some data it returns the same results, so I know it is pretty close, but for some data it doesn't work exactly the same (different results).
C code (runs on x86 Windows, compiled with Borland Builder):
void Crypt(unsigned char *data,long len)
{
char key[] = "X02$B:";
ULONG crypt_ptr;
long x;
for(crypt_ptr=0,x=0;x<len;x++)
{
data[x] ^= key[crypt_ptr];
if(crypt_ptr < (sizeof(key) - 2))
key[crypt_ptr] += key[crypt_ptr + 1];
else
key[crypt_ptr] += key[0];
if(!key[crypt_ptr])
key[crypt_ptr] += (char) 1;
if(++crypt_ptr >= sizeof(key) - 1)
crypt_ptr = 0;
}
}
Java Code (which runs on the Android platform if it matters):
public static void Crypt(byte[] data,int offset,int len)
{
// EDIT: Changing this to byte[] instead of char[] seems to have fixed code
//char[] key = {'X','0','2','$','B',':'};
byte[] key = {'X','0','2','$','B',':'};
int size_of_key = 7;
int crypt_ptr;
int x;
for(crypt_ptr=0,x=0;x<len;x++)
{
data[x+offset] ^= key[crypt_ptr];
if(crypt_ptr < (size_of_key - 2))
key[crypt_ptr] += key[crypt_ptr + 1];
else
key[crypt_ptr] += key[0];
if(key[crypt_ptr] == 0)
key[crypt_ptr] += (char) 1;
if(++crypt_ptr >= size_of_key - 1)
crypt_ptr = 0;
}
}
I have confirmed that the data going in to each function is the same, and for the Java version I am passing in the correct offset value within the byte array. As mentioned, it works sometimes, so I don't think it is a major/obvious issue, more like some minor issue between signed vs unsigned values. If it helps at all, the first byte that was different was at byte 125 (index 124 if zero-based) in the data. I didn't see a pattern though, like every 125 bytes, it was pretty much random after that. The data is only 171 bytes, and I can figure out how to post as an attachment probably if needed, but I don't think it is.
A: I guess it's because char is 16-bit in java. So when you increment key key[crypt_ptr] += (char) 1 or add two chars key[crypt_ptr] += key[crypt_ptr + 1], it acts in different way from c (where char is 8-bit).
Try to use bytes everywhere instead of chars, just use symbol codes for initialization.
A: Your key values need to be 8-bit. Try
byte[] key = "X02$B:".getBytes();
A: Why don't you show us an example where the differences manifest themselves?
BTW, I would write:
char[] key = {'X','0','2','$','B',':', '\0'};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8125210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mapbox Map doesn´t load after react build my mapbox doesn´t work after I built my react-app.
On localhost everything works fine, so I guess, it can´t be anything wrong with my access-token.
Do you have any idea or had a similar issue before?
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
const ProjectTemplate = (props) => {
const [map, setMap] = useState(null);
const mapContainer = useRef(null);
useEffect(() => {
mapboxgl.accessToken = '--accessToken--';
const initializeMap = ({ setMap, mapContainer }) => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/paul0711/cke1dpmlf0sua19nxso3b1zm7",
center: [props.lon, props.lat],
zoom: 17
});
map.on("load", () => {
setMap(map);
map.resize();
map.addControl( new mapboxgl.NavigationControl() );
map.addControl(new mapboxgl.GeolocateControl({ trackUserLocation: true }));
new mapboxgl.Marker({ color: "#575656", scale: 1.5})
.setLngLat([props.lon, props.lat])
.addTo(map);
});
};
if (!map) initializeMap({ setMap, mapContainer });
}, [props.lat, props.lon, map]);
return( <div className='project__template__map' ref={el => (mapContainer.current = el)} /> )
}
Cheers guys!
A: Found the solution! It is a bug from mapbox.
You have to use the version 1.13.0.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65682452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Name for HTTP Request+Response There's one thing I haven't found in RFC 2616 ("Hypertext Transfer Protocol -- HTTP/1.1") and that's a "canonical" name for a request/response pair. Is there such thing?
4.1 Message Types:
4.1 Message Types
HTTP messages consist of requests from client to server and responses
from server to client.
HTTP-message = Request | Response ; HTTP/1.1 messages
Taking this as a template, which word would you put in the following sentence?
A single complete HTTP ... consists of one HTTP Request and one HTTP Response
HTTP-... = Request Response
roundtrip? cycle?
A: *
*RFC2616 calls it an Exchange.
*Wireshark and HTTPNetworkSniffer call it a Request/Response.
*Fiddler calls it a Session.
*Charles calls it a Sequence.
*HTTP Scoop calls it a Conversation.
*Other vocabulary includes: Message, Transaction, Communication.
I would go for Exchange or RequestResponse.
I also went to name it Operation in my code as I would queue Operations, flush Operations, pause or resume Operations.
A: The spec calls them "exchanges" (or "request/response exchanges").
Per section 1.4, "Overall Operation":
In HTTP/1.0, most implementations used a new connection for each request/response exchange. In HTTP/1.1, a connection may be used for one or more request/response exchanges […]
A: Exchanges is nice name, also we can use Connection, Communication or session
A: Payload
In my project, I needed a name so that I can differentiate between models (Database) and HTTP interaction objects, so I am using payload, like:
*
*ProductPayload, ProductModel
*CartPayload, CartModel
*OrderPayload, OrderModel
A: Transaction, yes, or "A singe HTTP Request consists of one HTTP Request message and one HTTP Response message."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/325346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
}
|
Q: Entity Framework DBContext.Entry() is very slow I am trying to get some data out of the database. Using the .Entry is very slow, over 65% of time spent is right there. Does anyone have any ideas how to optimize my query? I only want to get the data as read only.
Sorry about adding the code as an image, but it would not let me post the question when it was formatted using the code sample button.
A: Your query is definitively far from being optimized. Try this instead:
seismic2DSurvey.EndsAndBends = winPicsDbContext.Locations
.Where(t => t.surveyId = seismic2DSurvey.Id && (t.IsBend || (t.IsEnd.HasValue && t.IsEnd.Value))).OrderBy(t => t.TraceNumber).ToList();
seismic2DSurvey.TraceCount = locations.Count();
seismic2DSurvey.SurveyLocations = null;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30764320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ssh client side audit Now I am trying to design some ssh audit framework. I want to log all the user inputs.
I have found on the server site, logs(e.g, bash history) are kept and we can even use auditd to capture the user actions after he/she opened a file with vi.
My question is that is it possible to audit it on the SSH client side? Is there any ssh option or packages available? I haven't found any~
Thanks,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38317956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EmrCreateJobFlowOperator returns "ERROR - The conn_id `emr_default` isn't defined" I am using Airflow in EKS for a project. I am using the EmrCreateJobFlowOperator to create a new EMR cluster. When the Dag runs the step fails and I get an error:
{taskinstance.py:1150} ERROR - The conn_id emr_default isn't defined
Here is my step in the code:
job_flow_creator = EmrCreateJobFlowOperator(
task_id='create_job_flow',
job_flow_overrides=JOB_FLOW_OVERRIDES,
aws_conn_id='aws_default',
emr_conn_id='emr_default',
dag=dag
)
I am using Airflow 1.10.11, and I know this is probably not an issue in later versions, but it's difficult for me to upgrade the version at the moment. I found other threads that advise on going into Airflow Connections and adding a new connection, but I don't know how to set that connection up and I cannot find resources on the subject.
Any help is appreciated, thanks!
A: Yes. You should create conection of emr_default of the right type for the operator (you have to pick the right one from the list) .
Here is a detailed instruction on what to do. This is is "1.10.11" Airlfow documentation and if you need any other airflow resources and docs you can always go there and use "Saerch" functionality. I got to that page by choosing Airlfow 1.10.11 version and searching for "connection".
https://airflow.apache.org/docs/apache-airflow/1.10.11/howto/connection/index.html?highlight=connections
A: Try the following connection of emr_default that works for me.
Connection Id: emr_default
Connection Type: Amazon Elastic MapReduce
Login: access_key
Password: secret_key
Extra: {"region_name": "eu-west-3"}
Replace "eu-west-3" with your region
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70222696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dart: Synchronous post request I would like to send a synchronous POST request from the client-side. According to the documentation we can use the 'async' named parameter:
https://www.dartlang.org/articles/json-web-service/#saving-objects-on-the-server
var url = "http://127.0.0.1:8080/programming-languages";
request.open("POST", url, async: false);
But the above example throws the following syntax error:
The keywords 'async', 'await', and 'yield' may not be used as identifiers in an asynchronous or generator function.
How can I send a synchronous POST request?
UPDATE (27 May, 20:23)
I found a workaround to solve this problem:
Future<String> deleteItem(String id) async {
final req = new HttpRequest()
..open('POST', 'server/controller.php')
..send({'action': 'delete', 'id': id});
// wait until the request have been completed
await req.onLoadEnd.first;
// oh yes
return req.responseText;
}
But I don't like the above solution because it doesn't seem elegant enough.
A: This is a known issue with this named parameter https://github.com/dart-lang/sdk/issues/24637
A: The solution is to use postFormData() instead of send(). For example:
final req = await HttpRequest
.postFormData(url, {'action': 'delete', 'id': id});
return req.responseText;
A: Future<String> deleteItem(String id) async {
final req = new HttpRequest()
..open('POST', 'server/controller.php')
..send({'action': 'delete', 'id': id});
// wait until the request have been completed
await req.onLoadEnd.first;
// oh yes
return req.responseText;
}
this one is the point, where sometimes you need "PUT" or "DELETE"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37489623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Call a stored procedure, passing a valid school ID and a leader score of 50, but procedure doesn't work I have written a SQL IF statement to update the stored procedure:
CREATE OR REPLACE PROCEDURE UPDATE_LEADERS_SCORE (
IN in_School_ID INTEGER, IN in_Leader_Score INTEGER)
LANGUAGE SQL
MODIFIES SQL DATA
BEGIN
UPDATE SCHOOLS
SET Leaders_Score = in_Leader_Score
WHERE School_ID = in_School_ID;
IF in_Leader_Score > 0 and in_Leader_Score < 20 THEN
UPDATE SCHOOLS
SET Leaders_Icon = 'Very_weak'
WHERE School_ID = in_School_ID;
ELSEIF in_Leader_Score >=20 and in_Leader_Score < 40 THEN
UPDATE SCHOOLS
SET Leaders_Icon = 'Weak'
WHERE School_ID = in_School_ID;
ELSEIF in_Leader_Score >=40 and in_Leader_Score < 60 THEN
UPDATE SCHOOLS
SET Leaders_Icon = 'Average'
WHERE School_ID = in_School_ID;
ELSEIF in_Leader_Score >=60 and in_Leader_Score < 80 THEN
UPDATE SCHOOLS
SET Leaders_Icon = 'Strong'
WHERE School_ID = in_School_ID;
ELSEIF in_Leader_Score >=80 and in_Leader_Score < 100 THEN
UPDATE SCHOOLS
SET Leaders_Icon = 'Very_strong'
WHERE School_ID = in_School_ID;
END IF;
END
@
but when I call the stored procedure, it doesn't work
CALL UPDATE_LEADERS_SCORE(609676, 50);
And I have errors like :
Message d'erreur
Value "Average" is too long.. SQLCODE=-433, SQLSTATE=22001, DRIVER=4.27.25
Does anyone have ideas?
A: Your function code performance will be slow. Because in your code update command will be executed on 2 times. It is possible to write this function very simply and with high performance.
CREATE OR REPLACE PROCEDURE update_leaders_score(in_school_id integer, in_leader_score integer)
LANGUAGE plpgsql
AS $procedure$
begin
update schools
SET
leaders_score = in_leader_score,
leaders_icon =
case
when (in_leader_score > 0 and in_leader_score < 20) then 'Very_weak'
when (in_leader_score >= 20 and in_leader_score < 40) then 'Weak'
when (in_leader_score >= 40 and in_leader_score < 60) then 'Average'
when (in_leader_score >= 60 and in_leader_score < 80) then 'Strong'
when (in_leader_score >= 80 and in_leader_score < 100) then 'Very_strong'
end
WHERE school_id = in_school_id;
END;
$procedure$
;
A: Increase the length of the Leaders_Icon by using below code before calling stored procedure, It will work.
ALTER TABLE SCHOOLS ALTER COLUMN Leaders_Icon SET DATA TYPE VARCHAR(20);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69929578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I build latest AOSP? After configuring the AOSP fully. I tried to build it using make -j4. But I got the below error:
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=4.0.4
TARGET_PRODUCT=full
TARGET_BUILD_VARIANT=eng
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a
HOST_ARCH=x86
HOST_OS=linux
HOST_BUILD_TYPE=release
BUILD_ID=IMM76
============================================
Checking build tools versions...
************************************************************
You are attempting to build with the incorrect version
of java.
Your version is: java version "1.7.0_55".
The correct version is: Java SE 1.6.
It is trying to build 4.0.4, not the Android-L. Thats why it is asking for Java 6, because java 6 is needed for building 4.0.4.
How do I build for Android-L which can be build with Java-7? I want to contribute to AOSP. For which I only need latest AOSP master branch to be build not the older versions.
Any help would be great. Thanks.
A: It looks like you init your manifest on the incorrect version of AOSP. See Downloading the Source for a good explanation of what you need to do to setup AOSP.
The main part from there that you want though, is:
repo init -u https://android.googlesource.com/platform/manifest -b android-4.0.1_r1
Which would init your repository on AOSP version 4.0.1_r1. If you want to init on the l-preview branch, it would be:
repo init -u https://android.googlesource.com/platform/manifest -b l-preview
Just keep in mind this isn't actually android l's source code, its a GPL update. I am not sure if they have moved it over to using java version 1.7 yet, as I have not personally tried.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24847719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I prevent a 301 Redirection when a user requests a folder? I've been attempting to make a front controller that would ignore existing directories. In some cases, I've been getting 301 redirects where I wish would not occur. I'm using the following .htaccess file:
DirectoryIndex index.php
Options -Indexes
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ index.php?action=$1 [QSA,L]
At the directory I've been testing this, I have the following setup:
test/
.htaccess
index.php
If I attempt to query the server, my second example results in a 301 redirect:
curl -s server/tes | Outputs: tes
curl -s server/test | 301 Redirect; on follow will output: test
curl -s server/test/ | Outputs: test/
How can I prevent a 301 from occurring when accessing server/test? I feel like I'm missing something pretty trivial here.
A: That is happening because test is a directory and mod_dir module that runs after mod_rewrite adds a trailing slash and does a 301 redirect. You can prevent it by adding this line on top of your .htaccess:
DirectorySlash Off
However keep in mind that it is considered a security risks as it can show directory listing.
You can make this redirect in htaccess itself using this rule:
# add a trailing slash to directories
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,R=302]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29498077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Set up authoritative DNS server I am trying to set up a hosting company. The hosting company is going to have a client with the domain widgets.de
The name of my company is hostingcompany.de. The name servers I am setting up are called ns1.hostingcompany.de and ns2.hostingcompany.de
In the zone file for widgets.de, I have
NS ns1.hostingcompany.de.
NS ns2.hostingcompany.de.
In the zone file for hostingcompany.de, I have
hostingcompany.de 300 IN NS ns-110.awsdns-13.com
hostingcompany.de 300 IN NS ns-1130.awsdns-15.com
ns1.hostingcompany.de. 300 IN A 34.65.125.52
ns2.hostingcompany.de. 300 IN A 52.43.124.76
Also, I created two more hosted zones per Amazon's guidance
124.43.52.in-addr.arpa.
NS ns-2035.awsdns-62.co.uk.
SOA ns-2035.awsdns-62.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400
34 PTR ns1.hostingcompany.de
and
76.124.43.in-addr.arpa.
NS ns-799.awsdns-35.net.
SOA ns-2435.awsdns-62.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400
52 PTR ns2.hostingcompany.de
However, this is not working. When I try to submit these zone files, RIPE rejects them saying that ns1.hostingcompany.de and ns2.hostingcompany.de do not exist as objects. I think I have to do something with PTR records, but I don't know what.
A: PTR records are usually necessary if you are running a DNS or SMTP server to provide some proof that you are legitimate. I found this article to be quite illuminating.
I think the answer to this question is found towards the bottom of the link in the question. You have to fill out a form and AWS will create the PTR record for you. Creating a hosted zone in Route 53 for the pointer record does not appear to have any effect. Nothing in the RFC prohibits the owner of the public IP address from allowing a customer to create a PTR record for that public IP address. Although AWS could allow customers to create PTR records for their Elastic IP addresses, they do not.
There are a lot of articles discussing how you need to create your own hosted zones for the PTR records, such as but not limited to Amazon's own article the question linked to. You can definitely do this for private IP addresses if you are running a DNS server for a private network. However, if you are running a publicly available DNS or SMTP server on a public IP address, more vetting is required.
In order to verify that the records are set up correctly, you have to get an answer to:
dig -x 34.65.125.52 (must answer ns1.hostingcompany.de)
Unless you do this, the TLD registrar will not accept your nameserver, and your SMTP mail will probably be rejected as spam.
In addition to the above, another problem was that these lines should also be included in the zone file for hostingcompany.de
hostingcompany.de. 300 IN NS ns1.hostingcompany.de.
hostingcompany.de. 300 IN NS ns2.hostingcompany.de.
It is still unclear to me why the top level domain requires that the domains own nameservers are listed as being nameservers for its own domain, but this does appear to be a requirement for some top-level domains. After correcting the above problems, everything works.
I spent a long time trying to track down the above problems, and it did not seem to be documented anywhere, so I hope this helps someone. I also found this RFC to be quite interesting and informative. It is always good to read stuff written by the authorities.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42079958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python Requests response decode I send a request using python requests and then print the response, what confuse me is that the Chinese characters in response is something like \u6570\u636e\u8fd4\u56de\u6210\u529f
Here is the code:
# -*- coding:utf-8 -*-
import requests
url = "http://www.biyou888.com/api/getdataapi.php?ac=3005&sess_token=&urlid=-1"
res = requests.get(url)
if res.status_code == 200:
print res.text
Below is the response
response data
What should i do to tranfer the response? I have try to use encode and decode but it dose work.
A: Use requests.Response.json and you will get the chinese caracters.
import requests
import json
url = "http://www.biyou888.com/api/getdataapi.phpac=3005&sess_token=&urlid=-1"
res = requests.get(url)
if res.status_code == 200:
res_payload_dict = res.json()
print(res_payload_dict)
A: How to use response.encoding using Python requests?
For illustrate, let’s ping API of Github.
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com')
# print response
print(response)
# print encoding of response
print(response.encoding)
output:
<Response [200]>
utf-8
So, in your example, try res.json() instead of res.text?
As in:
# encoding of your response
print(res.encoding)
res.encoding='utf-8-sig'
print(res.json())
sig in utf-8-sig is the abbreviation of signature (i.e. signature utf-8 file).
Using utf-8-sig to read a file will treat BOM as file info instead of a string.
A: import requests
import json
url = "http://www.biyou888.com/api/getdataapi.php?ac=3005&sess_token=&urlid=-1"
res = requests.get(url)
res_dict = {}
if res.status_code == 200:
print type(res.text)
print res.text
res_dict = json.loads(res.text) # get a dict from parameter string
print "Dict:"
print type(res_dict)
print res_dict
print res_dict['info']
Use json module to parse that input. And the prefix u just means it is a unicode string. When you use them, the u prefix won't affect, just like what I show at the last several lines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45818881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: mmap big endian vs. little endian If I use mmap to write uint32_t's, will I run into issues with big endian/little endian conventions? In particular, if I write some data mmap'ed on a big-endian machine, will I run into issues when I try to read that data on a little-endian machine?
A: If you're using mmap, your probably concerned about speed and efficiency. You basically have a few choices.
*
*Wrap all your reads and writes with htonl, htons, ntohl, ntohs functions. Calling htonl (host to network) order on Windows will convert the data from little endian to big endian. On other architectures it will be a noop. These conversions do have an overhead, but depending on your operations, they may or may not be significant. AFAIK, this is the approach used by SQLite
*Your other option is to always write data in host format, and provide routines if users need to migrate their data across platforms. Databases usually read and write data in host format, but provide tools like bcp which will write to either ASCII or network byte order.
*You can tag the header of your file with a byte order mark. When your program starts, it will compare it's byte order with that of the file, and provide any translation if needed. This is often good for simply data formats like UTF-16, but not for formats where you have a number of variable length types.
Additionally, if you do things like provide length prefixes, or file offsets, you may have a mixture of 32 bit and 64 bit pointers. A 32 bit platform can't create a mmap view larger than 4GB, so it's unlikely that you would support file sizes larger than 4 GB. Programs like rrdtool take this approach, and support much larger file sizes on 64 bit platforms. This means your binary file wouldn't be compatible across platforms if you used the platform pointer size inside of your file.
My recommendation is to ignore all byte order issues up front, and design the system to run fast on your platform. If/when you need to move your data to another platform, then choose the easiest/quickest/most appropriate method of doing so. If you start out by trying to create a platform independent data format, you will generally make mistakes, and have to go back and fix those mistakes later. This is especially problematic when 99% of the data is in the correct byte order, and 1% of it is wrong. This means fixing bugs in your data translation code will break existing clients on all platforms.
You'll want to have a multi-platform test setup before writing code to support more than one platform.
A: Yes.
mmap maps raw file data to process address space. It does not know anything about what the raw data represents, let alone try to convert it for you. If you are mapping the same file on architectures with different endianness, you'll have to do any necessary conversion yourself.
As a portable data format across computers, I'd consider something of higher abstraction level such as JSON or even XML that does not tie the data format to a particular implementation. But it really depends on your specific requirements.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1025783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Entity Framework "The current transaction cannot be committed and cannot support operations that write to the log file." A piece of software I'm working on is used to upload data from CSV files into a database. Interaction with the database is using EF6. To submit data, there is a Stored Procedure named "InsertRow" which accepts an InterfaceID (string), the row of data(string), the delimiter character(string), and has output paramaters: Error Code (int) and Error Message (0). The SP definition looks like this:
CREATE PROCEDURE [dbo].[InsertRow]
(
@InterfaceID NVARCHAR(MAX) ,
@Row NVARCHAR(MAX) ,
@Delimiter NVARCHAR(MAX) ,
@ErrorCode INT OUTPUT ,
@ErrorMessage NVARCHAR(MAX) OUTPUT
)
It's called from Entity like this:
public virtual int InsertRow(string interfaceID, string row, string delimiter)
{
var errorCode = new ObjectParameter("ErrorCode", typeof(int));
var errorMessage = new ObjectParameter("ErrorMessage", typeof(string));
var interfaceIDParameter = interfaceID != null ?
new ObjectParameter("InterfaceID", interfaceID) :
new ObjectParameter("InterfaceID", typeof(string));
var rowParameter = row != null ?
new ObjectParameter("Row", row) :
new ObjectParameter("Row", typeof(string));
var delimiterParameter = delimiter != null ?
new ObjectParameter("Delimiter", delimiter) :
new ObjectParameter("Delimiter", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("InsertRow", interfaceIDParameter, rowParameter, delimiterParameter, errorCode, errorMessage);
}
The Procedure works only if a temporary table has been created (done before this is called), so the EF context needs to remain open while all rows are submitted. This is not a problem and is being managed. The procedure performs some validation and obviously some conversion from string to the correct data types. The output parameters Error Code and Error Message get populated with error info for the application to handle. The procedure ends with a catch that does this:
BEGIN CATCH
SET @ErrorCode = ERROR_NUMBER()
SET @ErrorMessage = ERROR_MESSAGE()
INSERT INTO ErrorLog values (GetDate(),@InterfaceID, @Row, @Deliminator, ERROR_NUMBER(), ERROR_MESSAGE())
END CATCH;
Most of the time, this works. However, in some circumstances, the Error Code and Error Message are not being set, and instead an EntityCommandExecutionException is thrown with the following Inner Exception message:
"The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction."
I'm struggling to understand why some errors that are thrown get caught here and handled correctly, while others fail. An example of this is when submitting the string "date text" as a part of the Row that should be entered into a DateTime field. This should be caught and reported, but instead I get the generic exception.
It's also worth noting that I have removed the insert statement from the Catch block too. The exception's message then changes to
"Uncommittable transaction is detected at the end of the batch. The transaction is rolled back."
Has anyone seen this issue before? What are we missing here that can help us to resolve it? What can cause the transaction to be uncommittable? We need to effectively capture these messages so we can report back to the user the issues with their files.
A: Sometimes the transaction is indeed uncommitable, for example if you're trying to INSERT a row, and there's a trigger on the target table, and the trigger fails.
You should always check XACT_STATE() in BEGIN CATCH block to see if you can commit the transaction. See the docs for more info.
And if you want to log the failure reliably, I'd recommend using SQL Audit feature, and EXEC sp_audit_write procedure in BEGIN CATCH block. Again, see the docs for more info. Alternatively there's RAISERROR ... WITH LOG which logs messages to SQL Server Error Log, if you can't use the Audit.
A: Entity Framework threw this exception.
TRIGGERS were the culprits. I had modified some Models, added migrations, updated the databse ... but NOT the TRIGGERS
This exception was thrown at some point in the processing.
Fixing the TRIGGERS solved the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24240699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it safe to use a uintptr as a weak reference I want to implement a weak reference in Go such that I can use a finalizer to detect when a data structure is no longer required and be able to store/clean up data.
One way I have found to do it is to use a uintptr as a map key such that when a finalizer is called, I can access/cleanup the data using the pointer value passed to the finalizer function. Is this safe to do?
I think my question is: does Go use a moving garbage collector? Or will it?
A: The link that you yourself quoted in a comment provides the answer to the question you meant to ask: instead of giving clients a pointer to the underlying object that you'd like to fuss with, give them a pointer to a wrapper object:
type internal struct {
// all the internal stuff goes here
}
// change the name Wrapper below to something more suitable
type Wrapper struct {
*internal // or p *internal if you want to be overly verbose
}
func NewWhatever(/*args*/) *Wrapper {
p := &Wrapper{...} // fill this part in
runtime.SetFinalizer(p, wrapperGotCollected)
return p
}
func wrapperGotCollected(p *Wrapper) {
// since p itself is about to be collected,
// **p (or *((*p).p)) is no longer accessible by
// the user who called NewWhatever(). Do
// something appropriate here.
}
Note that this does not use a finalizer on the *internal, but rather a finalizer on the *Wrapper: at the time that wrapperGotCollected is called, the *internal object itself is guaranteed still to be live because p itself has not yet been GC-ed (it's sort of halfway there, and will be the rest of the way there as soon as, or shortly after, wrapperGotCollected returns).
A: The unsafe documentation allows for GC that moves values in memory.
A uintptr is an integer, not a reference. Converting a Pointer to a uintptr creates an integer value with no pointer semantics. Even if a uintptr holds the address of some object, the garbage collector will not update that uintptr's value if the object moves, nor will that uintptr keep the object from being reclaimed.
A: For completeness this is what I wound up doing something like:
type actualThing struct {
Data int
}
type internalHandle struct {
*actualThing
}
type ExternalHandle struct {
*internalHandle
}
So a user of ExternalHandle can still write code like ExternalHandle.Data but the internal maintenance code can still atomically update *actualThing. A finalizer on a pointer to an ExternalHandle will signal the rest of the stack to delete references to internalHandle and stop propagating updates to it.
Basically the super convenient thing is that by nesting the structs as such, users of ExternalHandle use it without realizing or dealing with the fact that it's a double pointer dereference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63025066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Passing php variable to javascript in a different file I'm having problems with passing php variables to javascript.
It does pass through the variable that is declared at the top, but I don't know how to call the function to get the new version of variable after the IF statement is done.
$info = "A message";
if (true){
$info = 'Message to be passed';
}
The script that is used to pass the php variable to javascript file:
<script type='text/javascript'>
var info = "<?php echo $info; ?>";
</script>
I was wondering what could I do to fix this problem?
A: The simple way (this requires both files to be PHP files):
<?php
require_once "your_php_file_here.php"; // Change to your PHP file here
?>
<script type='text/javascript'>
var info = "<?php echo $info; ?>";
alert(info);
</script>
This will only allow you to get the value on page load. You need to reload the page if you want it to get a new value.
The (in my opinion) better way (the file can be HTML) using Ajax:
<script type='text/javascript'>
var info;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'your_php_file_here.php'); // Change to your PHP file here
xhr.onload = function() {
if (xhr.status === 200) {
info = xhr.responseText;
alert(info);
} else {
alert('Request failed: ' + xhr.status);
}
};
xhr.send();
</script>
This can be put in a function and called as many times as you want. It can get the new value without the need to reload the page.
For this to work, you need to change your PHP code to:
$info = "A message";
if (true){
$info = 'Message to be passed';
}
echo $info;
I did not add support for IE6 and below because I think it's about time we stop supporting browsers that lost support by their developers many years ago.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41092673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple commit in single pull request I am working on a project in Github using fork repo. I am new to Github and I have to make a GitHub action YAML file so for debug I simply do commit on the GitHub and now when everything is working fine, I have to make a pull request to the main repo but now I have 130 commits in a single pull request. My question is how to make it one or some better way to do so?
WHat I have tried is to cherry-pick the last commit make a new branch and push it to first my remote repo, but it also contains 130 commits.
A: git rebase is showing noop since you're not specifying the starting commit of where you want to rebase from. You can do the following from command line.
Checkout to your noetic branch. Run the following command.
git rebase -i HEAD~130
In the interactive window, leave the first commit as pick and change the next 129 commits to squash. I have Vim as my default editor so I can run the following to easily squash the 129 unneeded commits:
:s/pick/squash/ 129
Once you're done, save & exit with: :wq
Do :wq again when the editor asks you to write your commit message (or edit the commit message as you like)
After this your rebase should be complete and you should have only one commit with all your changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70818317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disable a href after click once and add new element at the same time?
Is it posible to add new element with javascript by using href and disable href at the same time?
So href only clicked once, and after that the new element will appear.
I wrote this code, but still no luck
JS
$(document).ready(function() {
$("#add_app").click(function() {
$("#box").append("<p>jQuery is Amazing...</p>");
this.removeAttribute('href');this.className='disabled';
}});
HTML
<a href="#" id="add_app" ><strong>Summon new element and disable me</strong></a>
The only does the job is in JS line
$("#box").append("<p>jQuery is Amazing...</p>");
Need help..
Thanks
--------------------------------------UPDATE---------------------------------
-Using improved code by PacMan, Linus Aronsson, and guest271314 and it works like a charm.
So basically we use .one() event handler to solve the problem.
Thanks for the feedback guys
A: You can use .one(); note js at Question is missing closing parenthesis ) at click()
$(document).ready(function() {
$("#add_app").one("click", function() {
$("#box").append("<p>jQuery is Amazing...</p>");
this.removeAttribute('href');this.className='disabled';
})
});
A: Use this jQuery:
$(document).ready(function() {
$("#add_app").one("click", function() {
$("#box").append("<p>jQuery is Amazing...</p>");
this.removeAttribute('href');
});
});
I'm using the .one() event handler to indicate that you only want the click event to take place once. The rest of the code was more or less correct with a few small changes.
Here's a fiddle: https://jsfiddle.net/0mobshpr/1/
A: you can try this
HTML
<a style="cursor: pointer;" id="add_app" ><strong>Summon new element and disable me</strong></a>
<div id="box"></div>
and in your JS code you can write this i have tested it and it worked fine
$(function(){
$("#add_app").one("click",function(){
$("#box").append("<p>jQuery is Amazing...</p>");
});
});
A: you need to return false whwn the link is click.
try this one JQuery code..
$("#add_app").click(function() {
$("#box").append("<p>jQuery is Amazing...</p>");
return false;
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37903154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 'Location'(geolocation) support in OS versions Is 'Location'(geolocation) native api supported in all iphnoe os versions from iphone 2.o to ios 4+ ? Is there any documentation to get the list of all API's and the supporting versions ?
A: Sure, its called core Location Framework:
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW1
A: Here is the apple documentation about CoreLocation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6857960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why is RenderingContext.drawElements clearing the screen before it draws? Is RenderingContext.drawElements correct when it clears the screen before it draws?
Consider these screenshots that show a step across a call to drawElements with the object already drawn being erased.
A: WebGL effectively clears the screen after the page has been composited. When you're stepping through stuff one line at a time it's going to be composited every time you stop.
If you don't want it to be cleared ask for preserveDrawingBuffer: true when you create the WebGL context as in
gl = someCanvas.getContext("webgl", { preserveDrawingBuffer: true });
As for why, from the spec
While it is sometimes desirable to preserve the drawing buffer, it can cause significant performance loss on some platforms. Whenever possible this flag should remain false and other techniques used. Techniques like synchronous drawing buffer access (e.g., calling readPixels or toDataURL in the same function that renders to the drawing buffer) can be used to get the contents of the drawing buffer. If the author needs to render to the same drawing buffer over a series of calls, a Framebuffer Object can be used.
Implementations may optimize away the required implicit clear operation of the Drawing Buffer as long as a guarantee can be made that the author cannot gain access to buffer contents from another process. For instance, if the author performs an explicit clear then the implicit clear is not needed.
The TL;DR version is preserveDrawingBuffer: false (the default) allows WebGL to swap buffers when compositing (that doesn't mean it will swap buffers but it can if it chooses to). preserveDrawingBuffer: true means it can't swap buffers, it must copy buffers. Copying is much slower than swapping.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27812153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I authenticate user with Email and password using React and Firebase I am invoking a method through on Click where this code is placed
handleEmail =()=>{
firebase.auth().createUserWithEmailAndPassword('abc@abc.com', '123').catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45090645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: method call problem with Python So I'm learning python, and I seem to be having a consistent problem with calling setText() methods on Text objects. The process works fine when I'm in the interactive IDLE GUI, but when I save modules and then try to run them, I get:
nonetype object has no attribute setText
Do I need to assign some sort of return type to the text assignment? Why would there be different behavior from IDLE to saved modules? I've searched the site and Python documentation and was unable to turn up anything. Any help would be much appreciated.
message1 = Text(Point(50,50), "Click).draw(win)
message1.setText("")
Edited to add…
Thanks Geo, your suggestion fixed things.
Now my question is, what's the difference between...
message = Text(Point(50,50), "Click").draw(win)
… and …
message = Text(Point(50,50), "Click")
message.draw(win)
… with regards to returning something, or ensuring that the message object has a type that supports certain functions?
A: Perhaps the draw method is not returning anything. Try changing your code to this:
message1 = Text(Point(50,50), "Click")
message1.draw(win)
message1.setText("")
A: I'm not sure how to answer your second question properly..so I'll just do it as an answer here.
The reason the first does not work is because you are assigning the return value of Text.draw to message. Since it returns nothing, then message is None.
In the working code, you assign message with the type Text and initialize the object. You then call the draw method of this object, and the setText method.
In the non-working code, you are calling the draw method on a new Text object, then assigning the return of that - that is, NoneType - to message. And since None has no setText method, you get an error.
(Sorry if I have mixed up NoneType and None there)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5171234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: update post meta on function.php does not work Im trying to update post meta when the post saved.
I like to have published date into custom field named '2a' only once when it is saved. No update of '2a' by modifying post.
This is code I added on function.php. It does not afect anything on custom field. Is there any wrong on my code?
When I ver_dump it, it returns correct value I expected. However, it does not update post meta...
function add_custom_field( $post_id, $post, $update ) {
if ( is_single() && metadata_exists( 'post', $post_id, '2a' ) ) :{
$date = get_post_meta( $post_id, '2a', true );
update_post_meta($post_id, '2a', $date );}
else:{
$date = get_the_date('Y-m-d', $post_id);
return update_metadata('post', $post_id, '2a', $date,);
}
endif;
}
add_action( 'save_post', 'add_custom_field', 10, 3 );
I found even this simple code does not work... why
function update_custom_field( $post_id, $post, $update ) {
$date = get_the_date('Y-m-d', $post_id);
update_post_meta($post_id, '2a', $date);
}
add_action( 'save_post', 'update_custom_field', 10, 3 );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60636067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simulate key press? I am looking for a method that allows me to press freely on the Android screen. Simply put, it would emulate what a person can do to move on the Android device
I want him to press the buttons of this game. I want to make a bot.
A: To get the control of the keystrokes from a background app you need to be root. Instead of that, you can use monkeyrunner to make scripts using Python. Another option is to use direct commands in ADB, as stated in this answer. Every option needs to be connected to a computer via USB cable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59445984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are pyc files independent of the interpreter architecture? From the tests I've done, with the same version of python (same magic number), a 64 bit interpreter can load pyc files made with a 32 bit version of python. And reciprocally I assume.
But is it totally safe? Can this lead to unexpected behavior?
A: pyc files are stored in the python marshal format.
http://daeken.com/python-marshal-format
it seems that the only issue is with encoded integers which are automatically downgraded to 32 bit integers when you read the pyc on a 32 bit machine.
However the pyc format doesn't include 64bit addresses/offset inside it so the same pyc should run on both 64bit and 32bit interpreters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3821728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: In Hybrid Authentication Azure Ad Claims are overridden by Identity user Hi I have Local Db and Azure Ad Connect with OpenId connect login.
when user login by using Azure Ad we got claims and object id in claims.
What is happening after that claims are overridden by identity because that
user has entry in AspNetUser too.
I have to keep both local db login and azure ad login but need to check if user is from azure ad
login then the object should be in local db which will be seeded later in local db or we can say that it is in local db, how to create a way where our both user can use the app.
this code is where I am using the OpenId connect and then then checking the claims
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, "Login To Azure Ad", options =>
{
options.Authority = string.Format(configuration["AzureAd:Instance"], configuration["AzureAd:TenantId"]);
options.ClientId = configuration["AzureAd:ClientId"];
options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
options.CallbackPath = configuration["AzureAd:CallbackPath"];
options.RequireHttpsMetadata = false;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.ClientSecret = "abX8Q~OQpPs04CW6hEWWr7tQfQRLXc47htf5Xasn";
options.Scope.Add("email");
options.SignInScheme = IdentityConstants.ExternalScheme;
options.Events = new OpenIdConnectEvents
{
OnAuthorizationCodeReceived = async ctx =>
{
var request = ctx.HttpContext.Request;
var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);
var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
string userId = ctx.Principal?.Claims?.Where(m => m.Type == "oid")?.FirstOrDefault()?.Value ?? string.Empty;
foreach (var item in ctx.Principal?.Claims)
{
ctx.HttpContext.User.Claims.Append(item);// binding it claims
}
}
};
});
Image 1 : here in HomeController I used custom Authorize(CustomerAuthorize) to check the upcoming claims.
Image 2 : like this in after login from azure ad I am getting the required data
now here after my custom authorize the claims are over ridden by identity.
Image 3 : I just want to authenticate azure ad user by it's claims values
Help me to find any solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75483443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: windows alert - DriverToaster.exe parameter incorrect I got this windows 10 alert suddenly. drivertoaster.exe found 0 on google. anyone familiar with this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45298924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How To: Specific complex grouping query I am not sure if this query I repeated, if so please do guide me according to the "Answered" query. And I am not sure what could be appropriate title for this query.
I have the following data in my SQL Server 2008 R2
|Date |Status |
|------------------|------------|
|29-Mar-2016 07:30 |X |
|29-Mar-2016 07:31 |Y |
|29-Mar-2016 07:32 |Y |
|29-Mar-2016 07:33 |Y |
|29-Mar-2016 07:34 |Y |
|29-Mar-2016 07:40 |X |
|29-Mar-2016 07:43 |Z |
|29-Mar-2016 07:45 |Z |
The result what I am expecting is as follows
|Start Date | End Date |Status |
|------------------|------------------|-----------|
|29-Mar-2016 07:30 |29-Mar-2016 07:31 |X |
|29-Mar-2016 07:31 |29-Mar-2016 07:34 |Y |
|29-Mar-2016 07:40 |29-Mar-2016 07:43 |X |
|29-Mar-2016 07:43 |29-Mar-2016 07:45 |Z |
Any suggestion on the SQL queries.
A: DECLARE @TEMP AS TABLE(
[Date] DATETIME,
[Status] VARCHAR
)
INSERT INTO @TEMP VALUES('29.03.2016 07:30','X')
INSERT INTO @TEMP VALUES('29.03.2016 07:31','Y')
INSERT INTO @TEMP VALUES('29.03.2016 07:32','Y')
INSERT INTO @TEMP VALUES('29.03.2016 07:33','Y')
INSERT INTO @TEMP VALUES('29.03.2016 07:34','Y')
INSERT INTO @TEMP VALUES('29.03.2016 07:40','X')
INSERT INTO @TEMP VALUES('29.03.2016 07:43','Z')
INSERT INTO @TEMP VALUES('29.03.2016 07:45','Z')
SELECT * FROM @TEMP
;WITH TEMP(n,d,s)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY [Date]),[Date],[Status]
FROM @TEMP
), StatePeriods(n,T_n,T_d,T_s,TL_n,TL_d,TL_s,TR_n,TR_d,TR_s)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY T.d),T.n,T.d,T.s,TL.n,TL.d,TL.s,TR.n,TR.d,TR.s
FROM TEMP AS T
LEFT JOIN TEMP AS TR ON T.n = TR.n-1
LEFT JOIN TEMP AS TL ON T.n-1 = TL.n
WHERE T.s <> TR.s OR T.s <> TL.s OR TR.s IS NULL OR TL.s IS NULL
)
SELECT SP1.T_n,SP1.T_d,SP1.T_s,SP1.TL_d,SP1.TL_s,CASE WHEN SP1.T_s = SP3.T_s THEN SP3.TR_d ELSE SP3.T_d END
FROM StatePeriods AS SP1
LEFT JOIN StatePeriods AS SP2 ON SP1.n-1 = SP2.n
LEFT JOIN StatePeriods AS SP3 ON SP1.n+1 = SP3.n
WHERE NOT (SP1.T_s=SP2.T_s AND SP1.TL_s IS NOT NULL AND SP1.TR_s IS NOT NULL)
And you can filter first or last row
This is a very resource-intensive solution. But you can use temporary tables instead of 'WITH'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36275398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to find location of Hibernate configurations for changing dialect As a newbie in web applications I'm finding myself stranded from time to time. Currently I am trying to fix a web application (written/set up in Jboss) that has been built by someone else who I can no longer ask for help. The application deploys correctly. However, a warning is given when deploying about the dialect of Hibernate. While not a major issue, I would like to change the dialect. Warning below:
10:29:10,935 WARN [Oracle9Dialect] The Oracle9Dialect dialect has been deprecated; use either Oracle9iDialect or Oracle10gDialect instead
However, I cannot find the location where to adjust this. I cannot find a hibernate.properties, hibernate.cfg.xml or other configuration file anywhere.
For several reasons I have to run the application on jBoss EAP 5.2. This has some consequences for the Hibernate set up, I guess.
I am using Jboss 7.1.1; installed JDK is 1.7.0_60. I also use Maven 3.0.4 and Hibernate 4.2.7. I am a little wary to install a newer version of Hibernate as I am not sure what the consequences will be and which configurations I need to do.
Thanks in advance!
A: Thank you for your replies.
A short-term solution was found in copying the HibernateUtil.class and pasting this file into the source, and setting the dialect in that file.
However, when trying to solve an unrelated problem, I found that there were several more classes and files I needed but couldn't find. At last I've been able to find these missing files in a total different directory (which was still in the repository and not checked-out), and it also included a HibernateUtil.class and hibernate.cfg.xml.
This problem seemed to be quite application-specific, but at last it is solved :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26252545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Drag and Drop - button event dont work in listviewitems I have build an own drag and drop with two listviews. My items in in my listview hast textblocks and a button. When i select a item and when i click on my Buttons in my listviewitem it dont work, because he jumped in my move function for the drag and drop, but he must go in click event and i dont know why. If there isnt any item selected it works.
This are the two components.
Here is some of my Code in XAML i think thats Okay :
<ListView x:Name="LeftListView" Grid.Row="1" ItemsSource="{Binding}" ScrollViewer.PanningMode="None"
ItemContainerStyle="{StaticResource Itemstyle}"
AllowDrop="True" FontSize="18" FontWeight="Light"
PreviewMouseLeftButtonDown="ListViewOnPreviewMouseLeftButtonDown"
PreviewMouseLeftButtonUp="listView_PreviewMouseLeftButtonUp"
PreviewMouseMove="ListViewOnMouseMove" Drop="ListViewOnDrop"
SelectionChanged="ListViewOnSelectionChanged" BorderThickness="1" BorderBrush="#EE7F00"></ListView>
<Button x:Name="CompleteProjectButton" Margin="0, 0, 3, 3" Style="{StaticResource ButtonTemplate}" Click="CompleteProjectButton_Click
Background="Transparent" Grid.Column="2" Grid.Row="1" Grid.RowSpan="2" Visibility="Visible">
<Border Background="Transparent" Height="25" Width="25">
<Path Stretch="Uniform" Fill="#059600"
Data="F1 M 23.7501,33.25L 34.8334,44.3333L 52.2499,22.1668L 56.9999,26.9168L 34.8334,53.8333L 19.0001,38L 23.7501,33.25 Z ">
</Path>
</Border>
</Button>
This is the code behind, with the event he jumped in everytime when an item is selected:
private ListView dragSource;
private void ListViewOnMouseMove(object sender, MouseEventArgs mouseEventArgs)
{
dragSource = (sender as ListView);
if (mouseEventArgs.LeftButton == MouseButtonState.Pressed)
{
if (dragSource.SelectedItems.Count > 0)
{
var items = (dragSource.SelectedItems as IList);
dragSource.AllowDrop = true;
DataObject dataObject = new DataObject(typeof(Collection), items);
DragDrop.DoDragDrop((sender as ListView), dataObject, DragDropEffects.Copy);
}
}
}
And thats the simple click event :
private void CompleteProjectButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Translations.BatchCompleted);
}
And the other drag and drop methods :
private void ListViewOnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var clickedItem = getClickedItem(e);
if (clickedItem == null)
return;
if (((clickedItem as ListViewItem).IsSelected) && (!Keyboard.IsKeyDown(Key.LeftShift)) &&
(!Keyboard.IsKeyDown(Key.RightShift)))
{
_mouseOnSelected = true;
e.Handled = true;
}
}
private ListViewItem getClickedItem(MouseButtonEventArgs e)
{
var dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is ListViewItem))
{
dep = VisualTreeHelper.GetParent(dep);
}
var item = dep as ListViewItem;
return item;
}
private void ListViewOnDrop(object sender, DragEventArgs dragEventArgs)
{
var items = dragEventArgs.Data.GetData(typeof(Collection)) as IList;
if (items != null)
{
dragSource.AllowDrop = true;
var listView = dragEventArgs.Source as ListView;
var itemCache = new ArrayList(items);
var itemAtPosition = VisualTreeHelper.HitTest(sender as ListView, dragEventArgs.GetPosition((sender as ListView)));
var dataContext = itemAtPosition.VisualHit.GetValue(DataContextProperty);
int itemIndex = -1;
if (dataContext != null)
itemIndex = (sender as ListView).Items.IndexOf(dataContext);
listView.SelectedItem = null;
foreach (var item in itemCache)
{
RemoveItemFromSourceView(item, dragSource);
AddItemToDestinationView(item, listView, itemIndex);
selectMovedItem(listView, item);
}
_selectedListView = listView;
}
}
its a very strange drag and drop, but i hope everybody can help me, thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31693298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to understand the flow of this JavaScript function I'm a beginner who is learning JavaScript, after HTML/CSS. I'm at the very beginning of the book of Head First, struggling to understand this function.
How does this function work in every step? What happens starting from thingamajig(5)?
function clunk(times) {
var num = times;
while (num > 0) {
display("clunck");
num = num - 1;
}
}
function thingamajig(size) {
var facky = 1;
clunkCounter = 0;
if (size == 0) {
display("clanck");
} else if (size == 1) {
display("thunk");
} else {
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
}
function display(output) {
console.log(output);
clunkCounter = clunkCounter + 1;
}
var clunkCounter = 0;
thingamajig(5);
console.log(clunkCounter);
A: Here's what will happen when we run this:
*
*starting from the top, we define three different functions: clunk, thingamajig and display
*then we initialize a variable called clunkCounter and assign to it the number 0
*then we call the thingamajig function, passing in the argument 5 for the size parameter
*in thingamajig, we'll enter the else branch, and we'll end up going through the while loop 4 times, so we're effectively doing facky = 1 * 5 * 4 * 3 * 2, so facky ends up with a value of 120
*then we call clunk(120)
*so we'll call display("clunk") 120 times
*display just logs "clunk", and as a side-effect increments the clunkCounter, to record how many times we've done this
*then finally we log out clunkCounter, which will be 120
Why would we want to do this? I don't know. It's a very contrived example which demonstrates how to use if/else conditionals and incrementing variables. I wouldn't worry too much about what it all "means". If you haven't already, try running it in the browser console, and messing around to see what happens if you change the value you pass in to thingamajig.
Edit: Very well explained. Just to add a little, its calculating the Factorial of a number and printing its value at the end.
A: The main thing to understand for those that still don't get it (like I did not understand when I first looked at this) is that "facky" changes values every time the while loop runs. So if you start with thingamajig(5), facky=5. But then size becomes "size=4" which makes it so you go through the while loop again. THIS TIME facky is going to be "facky=5x4" and therefore it is "facky=20". Then you go through the while loop again with "size=3" which makes it "facky=20x3" and there for it is "facky=60". One last time through the while loop and you get "facky=60x2" and therefore it is "facky=160".
A: it starts with thingamajig(5);
function thingamajig(size) {
var facky = 1;
clunkCounter = 0;
if (size == 0) {
display("clanck");
} else if (size == 1) {
display("thunk");
} else {
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
}
it takes "5" as parameter which means the "size" variable is 5 and starts to check the conditions in if blocks.
now lets see. the size is 5 so it will skip the first 2 part of the if block
`if (size == 0) {
display("clanck");
} else if (size == 1) {
display("thunk");
}`
and execute the else part
else {
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
this while loop will work until the size > 1 that means the size should be 1 to break the loop. there are some calculations in the while loop.
the "facky" variable changes but in the end the "size" variable will be "1" and the "facky" will be 96
when the "while loop" ends it will call clunk(facky);
that means
`function clunk(96) {
var num = 96;
while (96 > 0) {
display("clunck");
num = num - 1;
}
}`
this function will call "display" function 96 times. and display function will console log "clunck" word for 96 times in the console.
in the end the clucnkCounter will be consoled log.
I hope i understand the question right. because answering this question in writing is hard.
A: *
*in thingamajig() function the value is passed 5.
*and its is checked whether its matches with 0 or 1, then its goes to else block,
here is while loop. facky variable initial value is 1 but here its value is
assign again so its become 5, and size is decremented so become 4
*again in while its greater than 1, again 5*4=20, facky become 20.
*while continue until size value is 1. when size value is 1, facky become 120.
*(5)x(4)x(3)x(2) = 120
*now clank function is called and times = 120
*here num = times, so num = 120
*while num > 0, it call another function display, which console.log(output). And
here output = "clunk".
*And increase the value of clunkCounter by 1.
*Its keep on repeating until num = 0, and making clunkCounter = 120
A: -The code starts executing from the else code block in the function thingamajig(size), since the if and else if statement are false.
else {
while (size > 1) {
facky = facky * size;
size = size - 1; }
clunk(facky); }
}
In the else statement we have a while loop with a condition (size > 1), size is 5 inserted as an argument for the size parameter when invoked
thingamajig(5);.
The code loops till size = 1, when the condition becomes false.
*
*LOOP 1,
while size = 5 , facky is = 1, facky = 1 * 5 = 5, size - 1 =size becomes 4.
*LOOP 2,
while size = 4, facky = 5, facky = 4 * 5 = 20, size - 1 = size becomes 3.
*LOOP 3,
while size = 3, facky = 20, facky = 3 * 20 = 60, size - 1 = size becomes 2.
*LOOP 4,
while size = 2, facky = 60, facky = 3 * 60 = 120, size - 1 = size becomes 1.
*
*Before loop stops The clunk() function is invoked and facky is passed as an argument to the times parameter, the function clunk starts executing.
function clunk(times) {
var num = times;
while (num > 0) {
display("clunk");
num = num - 1; }
}
Here, times = facky = 120 = num, The while loop starts executing until num = 0 when the condition becomes false, in this loop the display() function is invoked with the string 'clunk' as an argument.
function display(output) {
console.log(output);
clunkCounter = clunkCounter + 1;
}
*
*The display('clunk') function starts executing.
*'clunk' string is copied into the output parameter and it is logged into the console & clunkCounter variable increments.
-The both continues logging string 'clunk' & incrementing clunckCounter, until num = 0, as num decrements from 120 till it gets to 0.
Results
console.log(output);
*
*'clunk' strings logs into the console 120 times.
console.log(clunkCounter);
-clunkCounter increments till its 120 so 120 is logged into the console.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62487970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ramdom 78 x 78 Pixels I am trying to learn how to code and not to sure where to start,
I would like to produce a box that is 78 pixels by 78 pixels
and then have them all a difrent random colour.
how would I do this on a html or php web page please ?
not realy sure where to start.
thanks for your help and time.
A: There are many ways to approach such a problem, a simple one is using a table and rand() PHP function to set the background of each cell:
<?php
$size=78;
$cellsize=4;
$table="<table cellpadding='$cellsize' cellspacing='1'";
for($y=0;$y<$size;$y++) {
$table.="<tr>";
for($x=0;$x<$size;$x++) {
// Random color
$r=rand(0,255);
$g=rand(0,255);
$b=rand(0,255);
$table.="<td style='background-color:rgb($r,$g,$b)'></td>";
}
$table.="</tr>\n";
}
$table.="</table>";
print $table;
?>
This code produces an HTML table. You can use other systems (for example GD).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19149262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Model Validation not showing error messages I am developing an ASP.NET Core MVC web app, however, I am having a problem with the data annotations.
For int and decimal, I cannot override the default error message for the data annotations. For string, the data annotation works.
This should be showing the required error message that I set, it is an int
This is showing the correct error message - it is a string
The is should be showing an error message that I set in it's model
This is happening for int and decimal data types as previously mentioned.
Here are the properties in my model:
[Required(ErrorMessage = "Please provide the model")]
[StringLength(55, ErrorMessage = "The model is too long")]
public string MODEL { get; set; }
[Required(ErrorMessage = "Please provide the service period")]
[Range(0, 5, ErrorMessage = "Please provide a smaller number")]
[RegularExpression("([0-9]+)", ErrorMessage = "Not a number")]
public int SERVICE_PERIOD { get; set; }
As I previously said, the string data type is working as expected, however, the int data type is not showing my own required error message, nor is it showing the error message that says it is not a number. The decimal data type error only working is the data annotation for when the number is longer than 5 numbers which is the Range data annotation.
I would appreciate any help, thank you.
A: It is working for me.
Try this attribute:
[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")]
Or you can use regular expression:
[RegularExpression("([0-9]+)", ErrorMessage = "Please enter valid Number")]
public int bmi_number { get; set; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66334806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Null object pattern with entity framework code first We've implemented the null object pattern in our domain model. We're using code first with fluent api to persist our domain model.
One of our entities has a navigation property - this navigation property is a FK and is where we use the null object pattern.
Our null object has the default 0 value for it's id.
Is there a way with fluent api (or direct mappings) to tell EF 'if this is one of those null objects, REALLY throw null in the database fk field, and not that invalid 0 id'.
EDIT:
As an example, imagine you have a Student Entity, and a FavoriteSubject entity. A student has a reference to a FavoriteSubject, unless he has no FavoriteSubject, then the null object would be something like NoFavorite.
When we persist this to the database, we get the Id of NoFavorite (0) where we'd really like NULL in the db as NoFavorite is a null object (follows null object pattern).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32213932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: React event is undefined when checkbox selected I have multiple checkboxes, when i clicked on them i want to display items which includes selected tags.
my code is below. it works fine when i console.log(response.items). but when i add
this.setState({ itemsByTag: response.items }) i got an event is undefined error after i click on checkbox
componentDidUpdate(){
this.onBoxChange()
}
onBoxChange = (event) => {
console.log(event.target.checked, event.target.name)
this.getItemsByTag(event.target.name)
}
getItemsByTag = (tagname) => {
this.client
.getEntries({
content_type: "models",
"fields.tags[all]": tagname
})
.then(response => this.setState({ itemsByTag: response.items }))
.catch(console.error)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55704052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deploy to Amazon EC2 from Cloudbees Is it possible to set up Cloudbees to deploy to an Amazon EC2 instance after a successful build?
Thanks,
W
A: Yes, but you don't provide many details of what you mean by "deploy". I suppose you mean using scp? If so, you must copy your Jenkins public key to an authorized keys file, and make sure that your security group rules allow CloudBees' build machines to talk to your EC2 instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14594318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to invoke text change method without lossing focus i am developing application in which i have a text box for writing supplier and shows the list of supplier match with the input text by calling text change method and shows the result in grid view but the problem is, that the method is invoked when i click outside the text box but i want it, to fire as soon as user types in the text box
ASP code
<table style="width: 100%;">
<tr>
<td style="font-weight: bold; font-size: medium; text-align: right;">
Supplier Name
</td>
<td style="text-align: left">
<asp:TextBox ID="txtSuppName" runat="server" Width="357px"></asp:TextBox>
</td>
</tr>
</table>
<asp:Panel ID="Panel1" runat="server" Height="616px" ScrollBars="Auto">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="gvSuppPayment" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="" GridLines="None" Width="100%"
OnRowCommand="GetSuppOrderDetails" BorderStyle="Solid" CssClass="shadow">
<Columns>
<asp:TemplateField HeaderText="Emaiil ID">
<ItemTemplate>
<asp:LinkButton ID="restorantName" runat="server" CommandName="Email" CommandArgument='<%#Eval("Supp_Email_ID")+ ";" +Eval("Supp_Name")+ ";" +Eval("Area") %>' Text='<%# Bind("Supp_Email_ID") %> '>LinkButton</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Supp_Name" HeaderText="Supp Name" />
<asp:BoundField DataField="Area" HeaderText="Area" />
<asp:BoundField DataField="Total_Orders" HeaderText="Total Orders" />
<asp:BoundField DataField="Total_Amount" HeaderText="Total Amount" />
<asp:BoundField DataField="Total_Ammount_Recievable"
HeaderText="Total Ammount Recievable" />
<asp:BoundField DataField="Total_Ammount_Payable"
HeaderText="Total Ammount Payable" />
<asp:BoundField DataField="Is_Deleted" HeaderText="Is Deleted" />
</Columns>
<HeaderStyle BackColor="#454545" Font-Bold="True" ForeColor="#35a7c1" />
<RowStyle CssClass="cartBackground" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
C# Code
protected void txtSuppName_TextChanged(object sender, EventArgs e)
{
DataTable CustomRangePaymentDT = new DataTable();
CustomRangePaymentDT = SrcHldObj.BalSearchViewAccess("SELECT *FROM payment_view WHERE trimmed_date BETWEEN '" + (Convert.ToDateTime(txtFromDate.Text)).ToString("MM/dd/yyyy") + "' AND '" + (Convert.ToDateTime(txtToDate.Text)).ToString("MM/dd/yyyy") + "'");
if (CustomRangePaymentDT.Rows.Count == 0)
{
lblError.Text = "Sorry! No result found";
lblError.Visible = true;
}
gvSuppPayment.DataSource = CustomRangePaymentDT;
gvSuppPayment.DataBind();
}
Thanks in adv..
A: Upto to which I can understand is, you want an auto suggestion functionality for your textbox. You need to do this in the keydown event of the textbox. You can make an AJAX call to get the suggestion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18611655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I design a REST interface that allows for updating the sort order of a list of related items? Assuming I want to develop a client application that manages playlists of songs and has the following objects stored on the server:
*
*Playlist { title:unique }
*PlaylistSong { PlaylistId, SongId, sortOrder }
*Song { title:unique }
How could I design a REST interface so that the order of a playlist can be changed from the client, and that a new song could be entered into an existing playlist at a specific position.
In other words, I do not know what the REST interface would look like in order to implement the following two actions:
*
*Add song to playlist in specific location
*Update the order of the playlist
The basic set of actions I want to implement, I understand should look like this:
User action: Rest Resource
Create playlist: POST /playlist
Get Playlist: GET /playlist/{id}
Get Playlist Songs: GET /playlist/{id}/songs
Create song: POST /song
Update song: PUT /song
Get song: GET /song/{id}
A: I would use PUT to change the order of the songs on the playlist:
GET /playlist/{id}/songs
{
{
"id" : "1",
"self" : "http://my.server/song/1",
"name" : "The Little Old Lady From Pasadena"
},
{
"id" : "2",
"self" : "http://my.server/song/2",
"name" : "Love Potion #9"
}
}
PUT /playlist/{id}/songs
{
{
"id" : "2",
"self" : "http://my.server/song/2",
"name" : "Love Potion #9"
},
{
"id" : "1",
"self" : "http://my.server/song/1",
"name" : "The Little Old Lady From Pasadena"
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22362611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why do My C Code go Wrong The below is my code. Compiler generates the errors as
#include<stdio.h>
struct Shelf{
int clothes;
int *books;
};
struct Shelf b;
b.clothes=5;
*(b.books)=6;
Compiler generates the errors as below for both statements b.clothes=5; and b->books=6; in above code.
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
I'm not a beginner at C and I believe that what I have written is correct. Kindly solve my problem
A: FIRST
You cannot do this
struct Shelf{
int clothes;
int books;
};
struct Shelf b;
b.clothes=5;
b.books=6;
In global scope
You can assign value inside a function
int main (void )
{
b.clothes=5;
b.books=6;
}
Or initializing values on declaration
struct Shelf b = { .clothes = 5, .books = 6 };
Moreover as you can see b is not a pointer so using -> is not correct: use . to access members of struct.
SECOND
Your struct has a pointer member book
struct Shelf{
int clothes;
int *books;
};
What you can do is to set it to the address of another variable, like
int book = 6;
struct Shelf b = { .clothes = 5, .books = &book };
Or allocate memory for that pointer like
int main (void )
{
b.clothes=5;
b.books=malloc(sizeof(int));
if (b.books != NULL)
{
*(b.books) = 6;
}
}
BTW I guess you want an array of books, so
int main (void )
{
b.clothes=5;
b.books=malloc(sizeof(int) * MAX_N_OF_BOOKS);
if (b.books != NULL)
{
for (int i=0; i<MAX_N_OF_BOOKS; i++)
b.books[i] = 6;
}
}
COMPETE TEST CODE
#include <stdio.h>
#include <stdlib.h>
struct Shelf
{
int clothes;
int *books;
};
int main(void)
{
struct Shelf b;
b.clothes = 5;
b.books = malloc(sizeof(int));
if (b.books != NULL)
{
*(b.books) = 6;
}
printf ("clothes: %d\n", b.clothes);
printf ("book: %d\n", *(b.books) );
}
OUTPUT
clothes: 5
book: 6
A: b is a struct, not a pointer, so -> is not correct.
It's like doing (*b).books, which is wrong.
struct Shelf{
int clothes;
int *books;
};
One data member of the struct is a pointer, however:
struct Shelf b;
is not a pointer, it is just a struct as I said before.
As for your question in comment:
b.clothes=5;
is correct. Also something like this would be ok:
int number = 6;
b.books = &number;
A: -> operator used to access of member of struct via pointer. b is not dynamically allocated so b->books=6; is wrong. You should first allocate memory for member books and then dereference it.
b.books = malloc(sizeof(int));
*(b.books)= 6;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43873415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using @classmethod for creating objects in django for testing purposes Both on the higher level perspective work, however which is preferred method for creating objects for testing and why ?
Clarification: For testing purposes, that is , for testing the model created in the test_models.py file
First Way:
Using @classmethods
class AuthorModelTest(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(first_name="Big", last_name="Bob")
Second Way:
Or passing self instead of referring to the class
class AuthorModelTest(TestCase):
def setUpTestData(self):
Author.objects.create(first_name="Big", last_name="Bob")
A: It's defined as classmethod in TestCase so you should do the same in your code. Maybe both versions work right now but in the future releases of Django it can break the compatibility of your code with Django. You can check the documentation.
classmethod TestCase.setUpTestData():
The class-level atomic block described above allows the creation of
initial data at the class level, once for the whole TestCase.
Just follow the example from docs:
from django.test import TestCase
class MyTests(TestCase):
@classmethod
def setUpTestData(cls):
# Set up data for the whole TestCase
cls.foo = Foo.objects.create(bar="Test")
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55646726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: The data structure of multiple fields in Lucene If I have one document with two fields title and content, the data as: title is: Java Book, content is: Java book is selling. What will the inverted index structure looks like, I mean it would be one inverted index which store the fields in doc object in posting table,like:
java doc1(title,content)
book doc1(title,content)
selling doc1(content)
Or there would be two inverted indexes representing different fields:
Field title:
java doc1
book doc1
Field content:
java doc1
book doc1
selling doc1
A: In Lucene term (an indexed element) consists of two parts: a field name and value. So in you case it will be one inverted index and will be look like this:
title:java -> doc1
title:book -> doc1
content:java -> doc1
content:book -> doc1
content:selling -> doc1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33573583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pandas: search multiple columns and return column with found value I'm try to do some auditing for our purchase orders, and I created this dataframe (here's a csv sample of it):
ProductName,Qty,LineCost,BuyQty1,BuyQty1Cost,BuyQty2,BuyQty2Cost,BuyQty3,BuyQty3Cost
SIGN2WH,48,40.63,5,43.64,48,40.63,72,39.11
SIGN2BK,144,39.11,5,43.64,48,40.63,72,39.11
In my data source, some products get different breaks, depending on the quantity purchased. Hence the columns BuyQty1 and BuyQty1Cost. Qty and LineCost are the values I need to audit. So, what I'm trying to do is:
*
*Check what quantity break corresponds to the value on the column
Qty. Example a Qty of 48 implies that the break is BuyQty2,
and the corresponding price should be BuyQty2Cost.
*Then add a column with the ratio of LineCost/BuyQty2Cost. It would be BuyQty3Cost in the case of SIGN2BK (2nd line).
How should I tackle this?
A: import pandas as pd
def calculate_break_level(row):
if row.Qty >= row.BuyQty3:
return row.BuyQty3Cost
elif row.Qty >= row.BuyQty2:
return row.BuyQty2Cost
else:
return row.BuyQty1Cost
# apply the function row-by-row by specifying axis=1
# the newly produced Line_Cost is in the last column.
df['Line_Cost'] = df.apply(calculate_break_level, axis=1)
Out[58]:
ProductName Qty LineCost BuyQty1 BuyQty1Cost BuyQty2 BuyQty2Cost BuyQty3 BuyQty3Cost Line_Cost
0 SIGN2WH 48 40.63 5 43.64 48 40.63 72 39.11 40.63
1 SIGN2BK 144 39.11 5 43.64 48 40.63 72 39.11 39.11
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31122427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Storing serialize array in database? We are building a crm based application and we are using PDO to access the database. We have various modules like contacts,leads,accounts etc. In the modules we are allowing user to add their multiple information like user can add multiple phone numbers,emails and addresses along with the types like email is of (work,personal).
so to save these kind of multiple informations we are using serialize array in database, for example: for the multiple emails we are storing serialize array in the Email column in database.
Serialize format:
a:2:{i:0;a:1:{s:5:"value";s:15:"test1@gmail.com";}i:1;a:1:{s:5:"value";s:15:"test2@gmail.com";}}
we want to confirm that way may not create problem later while using filtering etc. so can anyone please suggest us is this a right way to store the multiple information in database?
A: I can certainly confirm that this way will create A LOT OF PROBLEMS later while using filtering etc.
In general, such an approach is critically against the very relational database architecture. It's ok as long as you treat your database as a silly key-value storage, but absolutely unacceptable if you are going to use your database as a database.
The main rule for the database structure should be: each entity have to be stored separately. this way it will be accessible using standard SQL mechanisms.
One of the possible ways to solve your current case, is creating a table with three columns:
user_id, param_name, param_value
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37341673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Password Reset Email Notification does not work in real server Laravel 8 I implemented password reset using email and it works fine in localhost, but it throws an error in real server.
Here is the error:
Swift_TransportException
Connection could not be established with host mailhog :stream_socket_client():
php_network_getaddresses: getaddrinfo failed: Name or service not known
and here is .env file content:
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=laravel
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygmail@gmail.com
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygmail@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
UPDATE 1:
I tried using this configuration, but still doesn't work.
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=xxxxxxxxxxxx
MAIL_PASSWORD=xxxxxxxxxxxx
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=xxxxxx@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
How to fix this issue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68244193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.