query_id stringlengths 4 64 | query_authorID stringlengths 6 40 | query_text stringlengths 66 72.1k | candidate_id stringlengths 5 64 | candidate_authorID stringlengths 6 40 | candidate_text stringlengths 9 101k |
|---|---|---|---|---|---|
041a5bdbd1b125ee3a4247d181cc857d827c58d08b0dd1d1378140701380d91a | ['425415e2af364c369418662cbb47fee1'] | I am trying to add TinyMCE custom plugin in wordpress that change the direction of selected text by using <bdo>. I register the plugin in wordpress:
/*Register Custom TinyMCE plugin*/
add_filter('mce_external_plugins', 'my_tinymce_plugins');
function my_tinymce_plugins() {
$plugins_array = array(
'tiny' => 'tiny.js' //Plugin directory is same as theme's funtion.php
);
return $plugins_array;
}
But it hide visual editor completely & also make text editor, un-editable. What is wrong?
| 9682198e83d77a302bdf8e15b7fff3711b72cd6789ea7d9601d45f770dc36a59 | ['425415e2af364c369418662cbb47fee1'] | It is possible just on old Nokia Phones (with black & white screen) & with phone like Nokia 1600.
Methode
Write new text message that contain 51 inverted commas ["] in your message & send it to victim. For some mobile phone you need to write 79 inverted commas instead of 51.
You can write comments in the start of message. For example "I am going to turn of your phone" & write commas after two lines.
|
2370e5d490552f6b06d7219d56fbd70713b975dbc61ede37a68b354d3778dab5 | ['425b8148e3964d5aa42da977aafd8d76'] | When referring to the limit of a series of increasing/decreasing sets in Monotonous class, it is common to write this limit as the union/intersection of those sets. For example, when you read the proof of Monotone class theorem, you will find the limit of a set series $A_{1}\subset A_{2}\subset A_{2}\dots$ is $\bigcup^{\infty}_{i=1}A_{i}$ but not $\lim_{n\rightarrow\infty}A_n$. But what is the difference between the two kinds of expressions? Is it just a habit or have something more meaningful? Are there any cases satisfying $\lim_{n\rightarrow\infty}A_n \neq \bigcup^{\infty}_{i=1} A_i$ , or the former does not exist but the later exists?
| 9d345153b505f5b4a926e717b3717242b0d11cafda54ca6e2d66cab89d13c815 | ['425b8148e3964d5aa42da977aafd8d76'] | I have an odd problem I can't seem to diagnose.
I'm calling am external binary, waiting for it to complete and then passing back a result based on standard out. I also want to log error out.
I wrote this and it works a treat in Windows 7
namespace MyApp
{
class MyClass
{
public static int TIMEOUT = 600000;
private StringBuilder netOutput = null;
private StringBuilder netError = null;
public ResultClass runProcess()
{
using (Process process = new Process())
{
process.StartInfo.FileName = ConfigurationManager.AppSettings["ExeLocation"];
process.StartInfo.WorkingDirectory = Path.GetDirectoryName(ConfigurationManager.AppSettings["ExeLocation"]);
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler(NetOutputDataHandler);
netOutput = new StringBuilder();
process.StartInfo.RedirectStandardError = true;
process.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);
netError = new StringBuilder();
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (process.WaitForExit(TIMEOUT))
{
// Process completed handle result
//return my ResultClass object
}
else
{
//timed out throw exception
}
}
}
private void NetOutputDataHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
//this is being called in Windows 7 but never in Windows Server 2008
if (!String.IsNullOrEmpty(outLine.Data))
{
netOutput.Append(outLine.Data);
}
}
private void NetErrorDataHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
//this is being called in Windows 7 but never in Windows Server 2008
if (!String.IsNullOrEmpty(outLine.Data))
{
netError.Append(outLine.Data);
}
}
}
}
So I install it on a Windows Server 2008 box and the NetOutputDataHandler and NetErrorDataHandler handlers are never called.
The app is compiled for .NET v4.
Any ideas what I'm doing wrong?
|
83fcdea2ccbbc144dcb623f162f824d799adde811084501101f73c660fa67a1c | ['4269e58888ff4f51934f4524a39365cb'] | Thank you very much...it is indeed a very powerful tool which can be even used to calculate,say what will be 28 months from now or more very daily life examples...after going through a few books...I saw that even banks use this method for CHECK number , which is immensely helpful . | 966198f7c4c4297b4c8c7d9c12bb34861354b455af8ad45340e5c5b5f988c5ea | ['4269e58888ff4f51934f4524a39365cb'] | I substituted x=cos t,y= sint and evaluated the integral of F.dr i.e (-ydx + xdy ), i.e (((sin t)^2)+((cost)^2)))dt, i.e simply dt from t=0 to t=T to get the value of the integral F.dr along the section of the helix as T...however I have not taken account of the orthogonal tangents as stated in the question |
f3e43c3e6e3406d687510153f4403d31206102f3c3bebbaa58eeea311939acdf | ['427d134b85144ae39475328cdb91bd3f'] | I am trying to access a server and its data from my own application. To log in I need a username and password plus a certificate, which I have. My problem is that I am apparently sending this information wrong, because I keep getting a 401. I should be able to, on this page, get some HAL+JSON data from this server after login. It is posted a field from a previous page and should submit that to the server to get the data.
Here is my code:
$username = 'foo';
$password = 'bar';
$auth_token = $username . '-' . $password;
$url = 'https://data.service.com'.$_POST['url'].'?callback=?';
$ch = curl_init($url);
/* Upon receiving the right certificate
* I should have a cookie with this information.
*/
$data_string = array('cert_url' => 'https://data.service.com/cert/2364o872ogfglsgw8ogiblsjy');
/* That hash at the end corresponds to the Public Key ID
* in the certificate. No idea how to retrieve this,
* or if I need to do it to login
*/
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/javascript',
'Access-Control-Allow-Origin: *',
'Content-Type: application/javascript',
"Authorization: Basic " . base64_encode($username.":".$password)
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);
if(curl_exec($ch) === false){
echo 'Curl error: ' . curl_error($ch);
print_r(error_get_last());
} else {
echo 'Operation completed without any errors';
curl_close($ch);
$response = json_decode($result, true); ?>
| c72d4ff586e1b9bec6b44b1b95335d06c2ee738bc257dc1da7e71475a5ba6194 | ['427d134b85144ae39475328cdb91bd3f'] | I am building a site where I will need a user to login with a name, password and a certificate. The way it should work is to upload the certificate the first time you login. Afterwards there should be a cookie set with the Public key ID (not the public key) and name and password, so that in the future you no longer need to upload a certificate.
I am having trouble with this, in particular getting the public key ID. I can grab the key, no problem, but what I need to do is grab the public key ID and save that as a cookie, and later to the DB along with the username and password.
Here is the code I submit my form to:
<?php
$uploads_dir = '/home/path/to/certs/';
$uploadfile = $uploads_dir . basename($_FILES['cert']['name']);
if (move_uploaded_file($_FILES['cert']['tmp_name'], $uploadfile)) {
$name = './'. $_FILES['cert']['name'];
$pub_key = openssl_pkey_get_public(file_get_contents($name));
$keyData = openssl_pkey_get_details($pub_key);
echo $keyData['key'];
} else {
echo "Nope!\n";
}
?>
|
ef6e2bb2e8338d3ac7882e3412ab424f57c5e7164625b721d3d684f860532100 | ['427f15aee06546dd91e9d8bb1f917013'] | private void pickImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(Create_event.this);
builder.setTitle("Choose Image");
builder.setMessage("Select Image");
builder.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent photoPickerIntent = new Intent(
Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
dialog.dismiss();
}
});
builder.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);
dialog.dismiss();
}
});
builder.show();
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 2 || requestCode == 1) {
try {
Intent cropIntent = new Intent(
"com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(data.getData(), "image/*");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
cropIntent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in
// onActivityResult
startActivityForResult(cropIntent, 3);
} catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
} else if (requestCode == 3) {
try {
Log.e("testing", "return data is " + data.getData());
String filePath = Environment.getExternalStorageDirectory()
+ "/" + TEMP_PHOTO_FILE;
System.out.println("path " + filePath);
uImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
uImage.compress(Bitmap.CompressFormat.PNG, 100, bao);
ba = bao.toByteArray();
ivcreateeventflyer.setImageBitmap(uImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
private File getTempFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {
}
return file;
} else {
return null;
}
}
Use this code to take pic from camera or gallery with crop functionality. hope it may be help you
| f63e40ac77b7819d9dc1fbc0bb7117fb9a9c8ca631bb9223bb173766a7aeb616 | ['427f15aee06546dd91e9d8bb1f917013'] | Here is my code to get user token
NSString *developerToken = @"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlVaMzI1Q0MyMkcifQ.eyJpc3MiOiJEWjI4TDk1OFBCIiwiaWF0IjoxNTI1MjY1NjE0LCJleHAiOjE1Mzg0Mzg0MDB9.frMVLzCx3oaUyqcBzZvSoB60LjCrtqmiCwf-ouQ1Y12UYpW5w8R-cmAX6N_Fwpz_l5CFe3OkYP3uET7uCPvyOw";
[SKCloudServiceController requestAuthorization:^(SKCloudServiceAuthorizationStatus status) {
self->cloudServiceController = [[SKCloudServiceController alloc] init];
[self->cloudServiceController requestCapabilitiesWithCompletionHandler:^(SKCloudServiceCapability capabilities, NSError * _Nullable error) {
[self->cloudServiceController requestStorefrontIdentifierWithCompletionHandler:^(NSString * _Nullable storefrontIdentifier,
NSError * _Nullable error) {
NSString *identifier = [[storefrontIdentifier componentsSeparatedByString:@","] firstObject];
identifier = [[identifier componentsSeparatedByString:@"-"] firstObject];
if (@available(iOS 11.0, *)) {
[self->cloudServiceController requestUserTokenForDeveloperToken:developerToken completionHandler:^(NSString * _Nullable userToken, NSError * _Nullable error) {
NSLog(@"%@",error);
NSLog(@"%@",userToken);
}];
} else {
// Fallback on earlier versions
}
//NSString *countryCode = [self countryCodeWithIdentifier:identifier];
}];
}];
}];
but I am getting userToken as nil and error as
"Error Domain=SKErrorDomain Code=7 "(null)"
UserInfo={NSUnderlyingError=0x1c08437b0 {Error Domain=SSErrorDomain
Code=109 "(null)" UserInfo={NSUnderlyingError=0x1c08437e0 {Error
Domain=SSErrorDomain Code=109 "Cannot connect to iTunes Store"
UserInfo={NSLocalizedDescription=Cannot connect to iTunes Store,
SSErrorHTTPStatusCodeKey=401}}}}}"
What I'm doing wrong ? please help
|
020df0aafe10e6f864829ec9e0afb6d50b9a7cbf9d38d7fb8e78f6c92a2ff28f | ['428e625d9afa4aae9fad2e1c00b4c0af'] | Im new to aws.
I am going to develop a REST full app which is going host on aws.
I decided to use
Amazon S3 for static contents
Amazon Cognito User Pool for Authentication
Amazon DynamoDB as db
I am confused on where my app is going to be hosted. I have 2 ideas for that.
AWS Lambda Function + api gateway
Can I implement entire app on it ?
Elastic Beanstalk
Can i integrate all the above aws services with it ?
(Backend on .net core web api 2.0)
Please guid me
| 3494617b7fb642563ebb121086665b931e0119f32ccc9dd923a5549eae915933 | ['428e625d9afa4aae9fad2e1c00b4c0af'] | First of all, I am new to Auth0 and I don't have a good knowledge when it comes to security.
I have an application that uses React as the client and Dotnet Core as the back end API. I have successfully integrated the Auth0 with both client and server sides. From the client, I can successfully log in using Auth0 and get the access token, and call to a protected route in backend API.
From the API I want to get the user profile corresponding to the access token.
I followed this tutorial but I am getting null for all as well as claims.
Apart from that, I have decoded the access token from JWT.IO then I noticed that there are no values in the payload that I'm looking for.
From another tutorial, they said that I have to include scopes of the request from the client. But that didn't help either.
auth0 = new auth0.WebAuth({
domain: AUTH_CONFIG.domain,
clientID: AUTH_CONFIG.clientID,
redirectUri: AUTH_CONFIG.redirectUri,
audience: AUTH_CONFIG.audience,
responseType: 'token id_token',
scope: 'openid profile email name'
});
On the client, I am getting 2 tokens after a successful login.
Identity Token: Which includes all the information that I need. But can't use as a bearer token to call my endpoint
Access Token: Which I can use as a bearer token to call to the endpoint, But there is no useful information in the payload.
I don't know the way I am following is wrong or not. If there is any other way please help me.
|
3cf323a22019c04170468e68c7fd05d44e7b03113599f351667b3f4b35f278ab | ['42a8c94030754526bd146d6e0ed96e17'] | We have a web (Rails) application where a small number of somewhat large (1 - 10MB) business logic files can be uploaded by administrators. The content files will not change frequently, maybe once a week.
When users interact with the application, another backend (Java) EC2 instance will frequently (multiple times per minute) have to process the contents of the same (single) file.
I am considering using an S3 bucket to store the files, and to use the AWS SDK to retrieve the files.
The goal is to make the application perform well and to prevent reading the file content over and over again. It is acceptable if changes to a file is not immediately visible, though this would be nice.
Is pure S3 the right approach here? Should I implement caching in Java myself, preventing an S3 request? Or is there another AWS approach that should be leveraged here?
| edb88b8b824673641068d1fa786aefe6f57c8294f43a28be23bddb8e86e4890d | ['42a8c94030754526bd146d6e0ed96e17'] | This turns out to have been an issue in the underlying library used by the tutorials for generating the menu, when running with the newer 4.x version of node.js. The issue is under investigation and being tracked at:
https://github.com/nodeschool/discussions/issues/1448
The missing piece in my troubleshooting, for folks who run into anything similar, is that I had not accounted for the change in the node version number, which went quite suddenly from v0.12.7 to a v4.x.x series. On reflection, it's hardly surprising that this broke some things.
So another reminder to never make assumptions, and always determine all of the differences between where it works and where it doesn't.
|
0f95f8493c360265dc40d5d9ef3a3c875b323a70bed3bc349f1a6df4c82c5d1a | ['42ab7d6b05404ca0b24d2e15af043476'] | The answer you're looking for is right in the python signal documentation:
Python signal handlers are always executed in the main Python thread, even if the signal was received in another thread.
Also:
the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point
So when a signal is received, the handler doesn't execute alongside the code in the while loop. Instead, the virtual machine executing your code is told to run the signal handling code 'soon', which could be after X number of bytecode instructions, so essentially your loop goes on pause while the handler code is running. Changing your code a little demonstrates this:
def sig_handler(signal_frame, num):
print('handler PID: {}'.format(os.getpid()))
print('current thread identity: {}'.format(threading.current_thread().ident))
time.sleep(5) # we put a long delay here
signal.signal(signal.SIGTERM, sig_handler)
try:
print('main execution PID: {}'.format(os.getpid()))
print('current thread identity: {}'.format(threading.current_thread().ident))
while True:
time.sleep(1) # sleep less now
print('Hello')
except KeyboardInterrupt:
print('Good bye')
Now, when you send your SIGTERM, you'll notice the execution of your while loop pauses for 5s.
| facb2f30afcc640fe14f2c63d92d62a67d43344849085e7391ed6ee7038afd01 | ['42ab7d6b05404ca0b24d2e15af043476'] | keep track of two pointers, one for the current index for a, and one for b. as we increment pointer a, we keep track of the min difference and index between the elements being pointed to, until pointed_a > pointed_b. update the min difference and index again (if there are changes). there we have our answer for the first element. continue the search similarly by increasing the pointer for b, and pick up pointer a from where we left off.
complexity: O( len a + len b ), therefore linear
|
672b820e34770e011383d60e90db4019191b3aee141b79be2000b2b58db7f522 | ['42b694bb278a439db4dde0c2087e9f1d'] | You can create two variables to accept the search value for "wordName" and "nameWeightpct" and use filter provided by Angular.
Here is a sample code:
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>
<label>Search Name: <input ng-model="searchName"></label>
<label>Search Phone: <input ng-model="searchPhone"></label>
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchName | filter: searchPhone">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
| 34b9dcef668f7656091db2232eeeb4508f11210040482266bdb6a7c07858a2e7 | ['42b694bb278a439db4dde0c2087e9f1d'] | Here is my LogCat
08-08 11:30:20.866 <PHONE_NUMBER>/com.example.sunny.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-4466
Process: com.example.sunny.myapplication, PID: 12663
java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:928)
at android.graphics.Bitmap.createBitmap(Bitmap.java:901)
at android.graphics.Bitmap.createBitmap(Bitmap.java:868)
at com.google.maps.api.android.lib6.impl.a.b$3e99e895(Unknown Source)
at com.google.maps.api.android.lib6.impl.s$5.run(Unknown Source)
at java.lang.Thread.run(Thread.java:841)
|
9b4aa18059134c414e30ce38ce480c5f50693311d689b426a173c2250bca7836 | ['42b991a9a15140efa1644b31b1dadbb9'] | when I run my server application on eclipse it doesn't work and the error is shown as following:
java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at MyServer.main(MyServer.java:17)
Exception in thread "main" java.lang.NullPointerException
at MyServer.main(MyServer.java:26)
| 096a6ff2f87f2811eb4a30990c1120f91abd59331c1ff61e20e584df83c5218f | ['42b991a9a15140efa1644b31b1dadbb9'] | this is my class to connect and send commands to server i try separate connect code in method
but when i test the (SocketConnect) method i found it doesn't work.
my code
public class ConnAndSend {
static Socket socket = null;
static void SendCommand(String cmnd) {
DataOutputStream dataOutputStream = null;
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(cmnd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
};
}
// method to connect to server
static void SocketConnect(String SrvrIP,int SrvrPrt) {
// Socket socket = null;
try {
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}
|
3d854733950c264340dc92bcf764f3026b813c316cf4bf87ea01a4b6540f77d8 | ['42be148c45b940548d0140d8d3ae14de'] | <PERSON> Yeah thanks but I did not understand the explanation you gave <PERSON>. Rereading, I think I may have gotten. Did you mean I should consider applying for "Master 2" which means completing a second master's in only 1 year instead of PhD directly and if not plausible (based on Master 1 exams) then just take a second master's? | 4b7bd1a8a8c57c7a9d7bc72091a7f73ff7ea0762004594a0d41b0e4cc3f92c37 | ['42be148c45b940548d0140d8d3ae14de'] | 4 On Rigor: ugh...I had 1 course on Advanced Prob. We used some chapters of Prob w/ <PERSON> by <PERSON>. StoCal I and II were not very rigorous looking back. Mostly proving results used in finance. We did discuss Our profs didn't discuss convergence of random variables, or go into Radon-Nikodym derivative stuff, but those things were mentioned. They also didn't prove prove <PERSON>'s lemma or Girsanov Theorem. As I recall, we proved stuff involving simple processes or functions but didn't prove further than that. <PERSON>, my program doesn't assume its students will continue to PhD unlike MS Math. |
fd079c4e4a1907ed11e99116d51f144331555902374dbf6c85a20b861a75e737 | ['42db7a327a5046b7a7e0d0f03c306033'] | I have two objects with several properties that are of type boolean.
The properties are identical in terms of naming and I just want to make sure they are equal. I do a lot of these checks and want to know if anyone has any suggestion of a method that can do the following code in one step but is dynamic enough to check the property options by name if they have the same name?
if (options != null && other != null)
return options.Quantities == other.Quantities &&
options.SKUEntityKey == other.SKUEntityKey &&
options.LineItemType_Type == other.LineItemType_Type &&
options.SKUIdentifier == other.SKUIdentifier &&
options.Identifier == other.Identifier;
If what I'm asking isn't clear please let me know
| b38bcf7dc076734d8401a68498595e2815aeac8995589b7f5ba5963349518cb2 | ['42db7a327a5046b7a7e0d0f03c306033'] | I extended the equals method and hashcode to check for equality of two identical objects with boolean properties. when I mutate the object making one of the boolean properties false instead of true it fails to recognize the difference and asserts they are equal;. Any Ideas why?
public override bool Equals(object value)
{
if (!(value is LocationPropertyOptions options))
return false;
return Equals(options, value);
}
public bool Equals(LocationPropertyOptions options)
{
return options.GetHashCode() == GetHashCode();
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override string ToString()
{
return $"{Identifier}{AccountEntityKey}{Address}{Comments}{Contact}" +
$"{Coordinate}{Description}{FaxNumber}{LastOrderDate}{PhoneNumber}" +
$"{ServiceAreaOverride}{ServiceRadiusOverride}{StandardInstructions}" +
$"{WorldTimeZone_TimeZone}{ZoneField}{CommentsOptions}";
}
|
7d6640c181e4764bc81d91b794f779fc89b0fe64964649587589d76402051012 | ['42e3ea58130c412ebe64617eebaf7293'] | Alright I've done the hard part hoping you can finish it up:
tmp = []
def recal(_list):
n = []
if '-' in _list:
for i in 0,1:
t = _list[:]
t[t.index('-')] = i
n.append(recall(t))
else:
tmp.append(l)
return l
recall(['-','-','0','1'])
for l in tmp:
print int(''.join(l),2)
| c7f02a94db8b527dda7f0e7c7a372b31a02d66bd476407068e8d796c852aa93e | ['42e3ea58130c412ebe64617eebaf7293'] | While this code is not pretty to do what your're looking to do you need to change these lines
if num>0:
l+='"'+ str(k) + '"=' + str(num)+' '
True
if True:
lst+=[l]
If you change it to something like
if num>0:
l+='"'+ str(k) + '"=' + str(num)+' '
flag = True
if flag:
lst+=[l]
and then if you reinitialize the flag = False at the beginning of the for loop it should produce the results you want. by doing the if True you are saying to always append to the list vs when there is actually something in there
|
6181375b4b97154705328449d4045113138dd822b84c938b30ba0b94680f0126 | ['42fd1a0994a94552bb39fae7bf1f782f'] | I have a website with checkboxes in the html:
<input onclick="markAsChanged(this); toggleApproveDeny(this);" name="2c9923914b887d47014c9b30b1bb37a1_approveChk" type="checkbox">
<input onclick="markAsChanged(this); toggleApproveDeny(this);" name="2c9923914b887d47014c9b30b1bb37a1_denyChk" type="checkbox">
<input onclick="markAsChanged(this); toggleApproveDeny(this);" name="2c9923914b887d47014c9b8b4f0337df_approveChk" type="checkbox">
<input onclick="markAsChanged(this); toggleApproveDeny(this);" name="2c9923914b887d47014c9b8b4f0337df_denyChk" type="checkbox">
I need a line/script that will 'check' all the boxes with '_approveChk' and leave the others unchecked.
Is there a way to do this in url "javascript:alert();" style?
or a way to call a javascript script stored locally through the url?
| df4d5def6679d5af612e08d45dae020fc5c149df07552a57bd6368ef334107f2 | ['42fd1a0994a94552bb39fae7bf1f782f'] | I require external access to a local server (localhost:xxxx) through my apache server on port 80.
Is there any way to achieve this in php or other scripting languages so that I don't have to port forward the other server?
Basically is there any way to have a script that loads the other server then pushes it through the apache server.
notes: I don't have the ability to modify the other server, it will be only the apache server that I can modify files.
Thanks in advance.
|
383045ce538fa7b0049c447e060cc8b1478fb80ea95b89d17305a4941eb97e0e | ['430304cf02a5437aa455b3e7120e13dd'] | am writing an android application, it allow someone add two numbers and input the answer. but I want this numbers to display for only 5 seconds and then a new number show up, if they input the correct or wrong answer, the timer reset and display new numbers..
i have written the code that does the random numbers and other just the timer am unable to do
someone help please
| 678049983f7d4d7ac9f2ed0a35da7177eb4cafd1daaa0c76acefdd07de16e6c6 | ['430304cf02a5437aa455b3e7120e13dd'] | am making a game in unity but am at that point where i check if the game user is clicking anything or not.. So if the player is idle for certain amount of time, lets say 20 seconds then i will play an animation to indicate that the player is idle
|
e382fc02819bddec13433b4960b5eeee106a048c593c1056895795690ec65d38 | ['431682b8cdf6458a81b4db41dbe88321'] | This post explains the differences/similarities between a Python dictionary and a JavaScript object. However I would like to know the differences/similarities between a JS object and Python dict to a C++ struct. These 3 datatypes seems to be equivalents to each other in their respective languages, however I would assume that there is more nuance to the applications in which each of them would be used. Otherwise there would be no need for other datastructures such as the C++ map.
| 95b26a9bedad30de0186d0a95fd6ecd01791ff3782d0b68a93dd0eef03b19db4 | ['431682b8cdf6458a81b4db41dbe88321'] | I have a workspace open in VS Code with multiple nested subdirectories for different projects. When I go to the Debugging Run in the sidebar and click on create a launch.json file a popup prompt appears to Select a workspace folder to create a launch.json file in or add it to the workspace config file with the options in the dropdown being the 1. current open workspace 2. workspace. When I select (1) and add the required configurations to the launch.json file the .vscode/launch.json is located in the root directory of the workspace and NOT the root directory of the project (in this case a React Native project) and when running the debugger I get the following error:
An error occurred while attaching debugger to the application. Seems to be that you are trying to debug from within directory that is not a React Native project root.
If so, please, follow these instructions: https://github.com/microsoft/vscode-react-native#customization (error code 604) (error code 1410)
How can I configure the launch.json file for a specific project in a VS Code workspace, rather than for the entire workspace?
|
2b2eb80e98e0b807f6cad61bc896153e3496fb1f250b6702b6b3bc140dee1bc8 | ['431a2897611541c091dd57a39779fcf7'] | And like you said, the 50 ohms resistor is a part of the circuit and can not be removed and if the analysis is carried without it, it should be added in series with the thevnin equivalent voltage and resistance at the end but both ways are different and yield different answers | a0cf65b37bf8ccad2f63d2774e732fbb42f8a8a6c9c8249de9804963cd6abe40 | ['431a2897611541c091dd57a39779fcf7'] | I'm attempting to do an Ansible ping ansible all -m ping --ask-pass but I get SSH failures. As the debug log is rather extensive, I've trimmed down the below quote to where I think the problem occurs. Earlier in the log, I am able to connect to the remote host (a headless RHEL5 VM) but when actually executing the "ping", it fails with the below error(s).
debug1: Entering interactive session.
debug2: set_control_persist_exit_time: schedule exit in 60 seconds
debug1: multiplexing control connection
debug2: fd 4 setting O_NONBLOCK
debug3: fd 5 is O_NONBLOCK
debug3: fd 5 is O_NONBLOCK
debug1: channel 1: new [mux-control]
debug3: channel_post_mux_listener: new mux channel 1 fd 5
debug3: mux_master_read_cb: channel 1: hello sent
debug2: set_control_persist_exit_time: cancel scheduled exit
debug3: mux_master_read_cb: channel 1 packet type 0x00000001 len 4
debug2: process_mux_master_hello: channel 1 slave version 4
debug2: mux_client_hello_exchange: master version 4
debug3: mux_client_forwards: request forwardings: 0 local, 0 remote
debug3: mux_client_request_session: entering
debug3: mux_client_request_alive: entering
debug3: mux_master_read_cb: channel 1 packet type 0x10000004 len 4
debug2: process_mux_alive_check: channel 1: alive check
debug3: mux_client_request_alive: done pid = 9664
debug3: mux_master_read_cb: channel 1 packet type 0x10000002 len 264
debug2: process_mux_new_session: channel 1: request tty 1, X 0, agent 0, subsys 0, term "xterm", cmd "/bin/sh -c 'mkdir -p $HOME/.ansible/tmp/ansible-tmp-1392125626.39-45498424175459 && chmod a+rx $HOME/.ansible/tmp/ansible-tmp-1392125626.39-45498424175459 && echo $HOME/.ansible/tmp/ansible-tmp-1392125626.39-45498424175459'", env 0
debug3: mux_client_request_session: session request sent
mm_receive_fd: no message header
process_mux_new_session: failed to receive fd 0 from slave
debug1: channel 1: mux_rcb failed
debug2: channel 1: zombie
debug2: channel 1: gc: notify user
debug3: mux_master_control_cleanup_cb: entering for channel 1
debug2: channel 1: gc: user detached
debug2: channel 1: zombie
debug2: channel 1: garbage collecting
debug1: channel 1: free: mux-control, nchannels 2
debug3: channel 1: status: The following connections are open:
I connected by conventional SSH to the host machine then checked to see if xterm runs on the remote box and while it's installed. It runs but bombs out with the following error:
xterm Xt error: Can't open display:
xterm: DISPLAY is not set
My hunch is that ssh connects, attempts to run the commands then can't because xterm bombs out. I've gone looking for a way to change which terminal to use but haven't been able to find anything in the documentation. Any input or suggestions are greatly appreciated.
|
7be140dbdad5daaad915c69010b7197846202572dea442f48b06a1fb9537ea80 | ['431e453b32404a7a86e02d77378f1573'] | I think this is because the pixelBuffer bytes per row does not match the UIImage bytes per row. In my case (iPhone 6 iOS8.3) the UIImage is 568 x 320 and the CFDataGetLength is 727040 so the bytes per row is 2272. But the pixelBuffer bytes per row is 2304. I think this extra 32 bytes is from padding so that bytes per row in the pixelBuffer is divisible by 64. How you force the pixelBuffer to match the input data, or vice versa, across all devices I'm not sure yet.
| 41011736236a0739adb6a5c61530e489138053bb25d6153c0a75d70b021015c8 | ['431e453b32404a7a86e02d77378f1573'] | This reads the string and creates and array of objects which is used in various operations but when the final array is returned I need the year to be a number but at the moment it is a string
for (let i = 1; i < allFileLines.length; i++) {
const data = allFileLines[i].split("|");
if (data.length === newheaders.length) {
const tarry: Icface = {
title: null as string,
id: null as string,
year: null as number,
};
for (let j = 0; j < newheaders.length; j++) {
tarry[newheaders[j]] = data[j];
}
if (typeof tarry[2] === "number") {
Log.trace("number");
}
// tslint:disable-next-line:no-console
// console.log(lines);
// Log.trace(JSON.parse(JSON.stringify(tarry)));
lines.push(tarry);
}
}
and interface is
export interface Icface {
title: string;
id: string;
year: number;
[key: string]: string | number;
}
So after the processing the year is being returned as "2018" but it needs to be 2018. Kind of baffling that I am able to operate on the string year with < and ===. Any ideas?
|
9a00065bf54a493941e774da68a3a9eceae395ac208e977ac72cddd139b3d02d | ['43249e550ef942dda44c381b9a9ddcd3'] | Aside from the general advise of "use a profiler", there is probably not one bottleneck but either a series of slow calls or the very structure of the procedure is creating unnecessary iterations. At a glance:
The Select against a datatable is generally not very performant.
Reflection carries with it a lot of overhead, it looks like you are dependent on it but if you could limit its scope you will probably get better overall performance.
| 5299fef3365200d7799562e23f98064dabf17718ea4d52d8dadb91a7ffe024ba | ['43249e550ef942dda44c381b9a9ddcd3'] | I'm going to have to add the point that Skeuomorphism was introduced "Because we could", prior to that desktops really didn't have the UNF to pull off the pretty effects. That all being said they more often tended to get in the way than help.
@Bluewater When everything is is not flat it doesn't add any affordance. Things only stand out in opposition to their environment. |
a544ce719e672955d23d11342263dbd61988555bcb81e3355a96e456ae3a6047 | ['432dad5b50044636bfd209fb9fa6386c'] | Apologies for 2 months of inactivity. We've been trying different Linux distro's and the same problem occurs with each distro. Through a little more research, I found that it is the GPU fan that is running constantly. In a related discussion, someone said that their "graphical driver" was unstable which made the card hot. What does this mean? | 4844ce82595a1555351061d141be97ec0460a80a8598582f770f2778731828b6 | ['432dad5b50044636bfd209fb9fa6386c'] | After I used this code to encrypt gpg.txt
$ gpg -c --cipher-algo AES256 --digest-algo SHA512 "GPG.txt"
I checked the result to see if it was encrypted with AES256 and hashed with SHA512
$ gpg --list-packets GPG.txt.gpg
symkey enc packet: version 4, cipher 9, s2k 3, ***hash 2***
gpg: AES256 encrypted data
I found Cipher=9, which is AES256 as I asked, but Hash=2, which stands for SHA1 and is not 10=SHA512 as I had wanted!
Why did this happen? Does anyone know how to force gpg to use SHA512 instead of SHA1?
|
4f4b9570192985c49930f790712af5cb40e8d4b1e5fc54df958d61327c5fe684 | ['4331e9ee0d314e6c813f2c65c568b75f'] | After placing the background image below your actual content, and using AnimatedOpacity() to fade in or out just like <PERSON> mentioned, you can equally use an image as a decoration image as follows for images hosted within the app's assets:
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/drawer.jpg')
),
),
Where 'images/drawer.jpg' is the path to your image in question.
Also make sure to configure your pubspec.yaml file:
# To add assets to your application, add an assets section, like this:
assets:
- images/
| 819d02315bb58a233814b78be861896827c2d4546ad0a3a10002db56fd26e254 | ['4331e9ee0d314e6c813f2c65c568b75f'] | You cannot use $_POST['ans'] because the values of your name attribute do not come as just 'ans'. Instead, they are printed as 'ans' + the id you echoed. For example, let's say your id in the option A of your answers is 1, we will then have 'ans[1]' thus $_POST['ans[1]'].
So, in general, you have to take care of that part of the string that makes your name attribute complete, which comes from <?php echo $id; ?>, meaning if for example $id is 1, then name = "ans[<?php echo $id; ?>]" will be the same as name = "ans[1]" and you will request it as $_POST['ans[1]'].
Hope this helps you out. You're welcome.
|
6bae8b68941f6548c070c9033cfac21faf4282dee103702bfc15472b89bb080c | ['4335a1c4e4804f6688ff94516e32d1c9'] | I am using a webservice to retrieve a JSON and convert it to a string.But i am getting the string as null.
The MainActivity class is:
package com.example.webserviceeg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnshowdata;
TextView txtdata;
String URL="http://www.footballultimate.com/fifa/index.php/api/matchShedule/";
ProgressBar pb;
HttpResponse response;
String result;
HttpEntity entity;
InputStream is;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnshowdata=(Button) findViewById(R.id.btnshowdata);
txtdata=(TextView) findViewById(R.id.txtdata);
pb=(ProgressBar) findViewById(R.id.progressBar1);
btnshowdata.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Retrievevalues().execute();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Retrievevalues extends AsyncTask<String,Void,Void>
{
@Override
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
// TimeZone tz = TimeZone.getDefault();
// Date now = new Date();
// int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
pairs.add(new BasicNameValuePair("time_offset","19800"));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httppost);
result=responsetostring.getResponseBody(response);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// txtdata.setText(result);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
pb.setVisibility(View.INVISIBLE);
}
}
}
I am using a second class containing static methods to convert the response object to a string:
responsetostring.java
package com.example.webserviceeg;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.protocol.HTTP;
public class responsetostring {
// Json Response Processing
// Json Response Processing
public static String getResponseBody(HttpResponse response) {
// TODO Auto-generated method stub
String response_text = null;
HttpEntity entity = null;
try {
entity = response.getEntity();
try {
response_text = _getResponseBody(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return response_text;
}
public static String _getResponseBody(final HttpEntity entity) throws IOException,
ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
StringBuilder buffer = new StringBuilder();
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
return buffer.toString();
}
public static String getContentCharSet(final HttpEntity entity)
throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
}
But the string result in MainActivity , i am getting it as null.Please help
| 3bbb86f3c040ca1e803720ffab4b9754dfa6bb4f54fb3610273722305087f065 | ['4335a1c4e4804f6688ff94516e32d1c9'] | I have a listview on the screen and on the bottom of the page i have 4 buttons.I want the four buttons to persist at the bottom of the screen even after scrolling the listview.I am new to android, should i use fragments or is there any other way to do it.Also can anyone give a link to a good fragments tutorial.Please help!!
|
b66a72ff47801d20117238e9191e5f8bdf6054767b6631f1331c2ab9643b0ab4 | ['434a11b9b64c4c6a8a99268880d81845'] | I am very new to tensorflow.
I am using the CIFAR10 (https://www.tensorflow.org/tutorials/deep_cnn) example and everything is smooth so far.
In this tutorial, How I can use another dataset instead of CIFAR10.
Lets say I have my own dataset and wanna use it instead. It has two folders inside of it, namely Training_Images and Testing_Images.
Also lets say for simplicity my dataset has just 10 classes as well.
In other words, I have a traininng and testing folder of images, and in each folder, i have images of each category (with the same lable) in a folder. I dont know how to feed the network with those images.
I also have read (https://www.tensorflow.org/programmers_guide/reading_data) but didnot really got my answer from it and didnot understand it clearly.
Also, if you guys know of any good example, it would be really appreciated.
Thanks
| 4e6a3985179e68d6bce7094b37b39a207f2d9da8e7c4ab1607121a8cb8828af4 | ['434a11b9b64c4c6a8a99268880d81845'] | I am super new to the field of object detection.
I was wondering if anyone can help me somehow on how I can download and use the object detection datasets such as coco or pascal. When I go to their website even after downloading the datasets i feel like i dont know what should i do with them...
I know this question is stupid, but a hint to start can be super useful.
Thanks
|
6749d90122fc655d52c1721b024766d8702800a3a8e3e6a23dffaa800f868391 | ['434ad6628d8b45e3a37c5815d90fd811'] | I would think of one more case when pessimistic locking would be a better choice.
For optimistic locking every participant in data modification must agree in using this kind of locking. But if someone modifies the data without taking care about the version column, this will spoil the whole idea of the optimistic locking.
| 396cc37589b971f2e1139bc700fcea2f6f7d7443043670c8c102d558905d4925 | ['434ad6628d8b45e3a37c5815d90fd811'] | I just can't get it. As much as I understand docker containers are stateless and when you stop a container any state will be lost. What is the idea and the approaches behind wrapping DB in Image and how the data is saved? I can't find a clear explanation on this topic. Could somebody explain the basics?
|
456ed0db34c744ba9c189007017441faa41dd8d2eba9291c185f78d42b7c87d8 | ['435244b82d684318b7793a597787d5af'] | My two cents: you might want to call the function with a name that describes what it does rather than how it does it.
It works better as self-documenting code and you decouple the name of the function (and the name users of that function have to remember) from the implementation.
Alternatively, if your function sbazzles the foo, you could call it sbazzleFoo and pass it to another function called runAndSchedule that takes sbazzleFoo, runs it and schedules its delayed execution if needed.
| 2bed5afa6e2037fea3dd2069401089b1b769f9becfc46f26decc3c7034857ca5 | ['435244b82d684318b7793a597787d5af'] | I have a custom field with formatter which is currently outputting via field.html.twig
I've modified the theme function to
function mymodule_theme()
{
return [
'field__field_family_and_education' => ['base_hook' => 'field'],
];
}
and the twig debug indicates it's now using this template, however, despite copying the field.html.twig to field--field-family-and-education.html.twig the variables are not being passed to the template. I want the template to reside in the module, not in the main theme so this is being done within the module that defines the field & formatter.
I'm guessing I've missed an obvious step, any ideas?
|
9f7d2e02f7683d54b990e6e583534d2c476e9e514a469873ceb8a9917d66b386 | ['4352ca660ebc49969cb6e153f025598a'] | I faced similar problem today. I worked it out using the following solution:
[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
String nonexistingPath = "C:\\does\\not\\exist\\file.ext";
var mock = new Mock<MyFileType>(nonexistingPath);
try
{
var target = mock.Object;
}
catch(TargetInvocationException e)
{
if (e.InnerException != null)
{
throw e.InnerException;
}
throw;
}
}
| 8ff1d7a7e23f88fbca122ee0006df08e0574528e34b7035fa9db991742f5b28b | ['4352ca660ebc49969cb6e153f025598a'] | For the sake of purity. Of course the <script> tags should be closed, so the correct code snippets are:
<script type="text/javascript" src="{{ asset('bundles/acmefoo/js/jquery.min.js') }}"></script>
and
{% javascripts '@AcmeFooBundle/Resources/public/js/jquery.min.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
Otherwise the whole content of the page would be treated as the content of the script tag and would appear blank.
|
83f0c796b9700b1a81cd19483310493b04ae0e886f58e04850e99f4202eb3a9c | ['435bc88a438f40b99fbe32b8f76b10a0'] | This is related to the disabling netlogon answer. It turned out that turning off netlogon was giving me issues with networked drives so it was a nuisance to disable it. I discovered that a long time I switched my dns provided to google's public dns. This turns out to be a very bad idea in a corporate domain. I switched it back to auto-detect dns and the problem went away.
| 999b884421400414454d2bfd3a9df3504ab0a75cf97c369c8265509afdbb9dd5 | ['435bc88a438f40b99fbe32b8f76b10a0'] | I will just point out one thing that resolved a previous instance of the same problem. On error my emacs went to the *Backtrace*. Since I had never seen it before, I killed it. After that, on error I would just get the error message in the ECHO area. To bring back the *Backtrace* buffer I did M+x debug once. After doing that, I get the *Backtrace* buffer on every error.
|
94c17b3c3d6c92d8bfb25a9c99477db76e488fe9c8cb6042ce879c3a19314c05 | ['4362671ec46844fd8bc03f61a7170145'] | I have noticed that my Magento CE <IP_ADDRESS> compilation configuration look very strange.
Collected Files Count 11083
Compiled Scopes Count 43
Normally is around 4
Looks like a lot of core parts of Magento are included in the count where in the default Magento is not.
Anybody knows how check if all is correct?
Regards
| 5a3599fc6402c39bd7b5de61ee9992e3b5dbc7ff4e879b186b87eeffeb7d3bf9 | ['4362671ec46844fd8bc03f61a7170145'] | I'm creating a static block to show the subcategories of a category in Magento. The code is made by me and with some ideas taken in the web.
The idea is to show a title with plain background called back.png as thumbnail of the subcategory when this one hasn't a thumbnail or the category thumbnail if the image is uploaded. For the moment I can't show the thumbnails, could anybody help me?
Thanks.
<div class="product_list" style="width:900px;">
<?php $_helper = Mage<IP_ADDRESS>helper('catalog/category') ?>
<?php $currentCategory = Mage<IP_ADDRESS>registry('current_category') ?>
<?php if($currentCategory->children_count > 0) { ?>
<?php
$cat = Mage<IP_ADDRESS>getModel('catalog/category')->load($currentCategory->entity_id);
$_categories = $cat->getChildrenCategories();
?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): //print_r($_category); ?>
<?php
$imageUrl = Mage<IP_ADDRESS>getModel('catalog/category')->load($_category->getId())->getThumbnailUrl();
$imageName = substr(strrchr($imageUrl,"/"),1);
$imagePrefx = Mage<IP_ADDRESS>getBaseUrl('media')."catalog/category/";
$newImageUrl2 = $imagePrefx.$imageName;
?><div clas="subcat-el">
<li style="float:left; margin-right:10px;">
<div class="subcat-name" style="z-index:20; width:270px; position:absolute; margin-top:134px;text-align: center;">
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>" style="text-decoration:none;">
<h3 style="margin-left:18px; font-family:Helvetica; font-weight:200;text-shadow: 1px 1px 1px #030;font-size: 24px;color:#fff; ">
<?php echo $_category->getName() ?>
</h3>
</a>
</div>
<div style="width:270px; height:270px;background: #fff;
border: 9px solid #fff; border-radius: 3px;-webkit-border-radius: 3px;-moz-border-radius: 3px;-webkit-box-shadow: 0 0 6px 0 rgba(0,0,0,0.15);-moz-box-shadow: 0 0 6px 0 rgba(0,0,0,0.15);box-shadow: 0 0 6px 0 rgba(0,0,0,0.15);margin-bottom:10px;">
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
<img src="<?php
if ($newImageUrl2 == $imagePrefx): $newImageUrl2 = Mage<IP_ADDRESS>getBaseUrl('skin')."/subcat/back.png";
endif;
echo $newImageUrl2; ?>" alt="<?php echo $_category->getName() ?>" style="width:100%;">
</a>
</div>
</li>
</div>
<?php endforeach; ?>
</ul>
<br style="clear:left;" />
<?php endif; ?>
<?php } else { echo "<h3>No Sub-category found</h3>"; } ?>
</div>
|
43a1fb55956eb6267d7609fee5e484bb8e61fda0a1ee8c552b1f6cd6051591cd | ['436cb2b54c4f415db14068f90b4901b7'] | Template.display_time.time = function() {
var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var now = addZero(hour) + ":" + addZero(minute);
return now
};
At the moment im using this code to display the time.
But I've been trying to use simple javascript to update it every second, yet it wont show up on the page.
Is there a meteor friendly way to do this using the function above?
Like using setTimeout on 1 second interval..
The javascript I used to use.
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (hours < 10)
{
hours = "0" + hours;
}
if (minutes < 10)
{
minutes = "0" + minutes;
}
var v = hours + ":" + minutes + " ";
setTimeout("updateTime()",1000);
document.getElementById('time').innerHTML=v;
}
updateTime();
| 76ce554b43ae431e02e3ac3e9e67a4a83c289eae3db36ddb9655828b29ee7519 | ['436cb2b54c4f415db14068f90b4901b7'] | $thearray = array
(
//(0)ID, (1)NAME, (2)LOCATION, (3)PHONE
array("0","Name 1","Nowhere 11","0004444"),
array("1","Name 2","Everywhere 11","0005555"),
array("2","Name 3","ThisPlace 11","0002222"),
array("3","Name 4","NoPlace 11","0003333"),
array("4","Name 5","ThatPlace 11","0001111")
);
This is how I used to store my information
I would then run through them to find what I needed
and display them using for example
echo $thearray[$i][4]
I want to do the same thing except store that information in Mysql
This is how far I've gotten but I keep getting strange errors and I cant output from the array
This is how far I've gotten
$result = $db->query("SELECT * FROM table");
$thearray = array();
while($thearray = $result->fetch_assoc()){
$thearray[] = $thearray;
}
For some reason this isn't working for me, its like it isnt in a 2d array like I have above :S I can't simply echo it like I did before.
|
17660af41f7131c28db9025da0998aa02af0ab6cddebeebd249439f329ac4770 | ['437497fdc17743cf8726fd3b1510a6c7'] | textstat_keyness in Quanteda is used to compare the relative frequency of WORDS/LEMMAS in two (sub)corpora. But I want to compare parts of speech--not words. Then I want to plot it. I've been able to use textstat_keyness for words, no problem, using the following:
# compare subcorpusA v subcorpusB terms using grouping
genre <- ifelse(docvars(corpusAB, "genre") == "group", "group", "group2")
dfmat3 <- dfm(corpusAB, groups = genre)
head(tstat1 <- textstat_keyness(dfmat3, measure = "lr", sort = TRUE, correction = "<PERSON>"), 20)
tail(tstat1, 20)
head(dfmat3)
textplot_keyness(tstat1, show_reference = TRUE,
show_legend = TRUE,
n = 40,
min_count = 5, margin = 0.05,
color = c("darkblue", "gray")
, labelcolor = "gray30",
labelsize = 2,
font = NULL)
I've also tokenized the corpus using tokens(), and I've parsed using spacy_parse. But I can't figure out how to connect the two. Is there a way to tell <PERSON> to run textstat_keyness on POS instead of words?
| b02609dbe46db05ab25409d0b040a17896c151bdf10477905b8da02858a32ffe | ['437497fdc17743cf8726fd3b1510a6c7'] | This is a followup question from a response here.
Below, I can generate jaccard similarity for adjacent pairs (1993 then 1994). How can I use as.list() to return a list of unique items for each comparison? Here's what I'm working with:
library("quanteda")
data_corpus_inaugural$president <- paste(data_corpus_inaugural$President,
data_corpus_inaugural$FirstName,
sep = ", "
)
head(data_corpus_inaugural$president, 10)
## [1] "<PERSON>, <PERSON>" "<PERSON>, <PERSON>" "<PERSON>, <PERSON>"
## [4] "<PERSON>, <PERSON>" "<PERSON>, <PERSON>" "<PERSON>, <PERSON>"
## [7] "<PERSON>, <PERSON>" "<PERSON>, <PERSON>" "<PERSON>, <PERSON>"
## [10] "<PERSON>, <PERSON>"
simpairs <- lapply(unique(data_corpus_inaugural$president), function(x) {
dfmat <- corpus_subset(data_corpus_inaugural, president == x) %>%
dfm(remove_punct = TRUE)
df <- data.frame()
years <- sort(dfmat$Year)
for (i in seq_along(years)[-length(years)]) {
sim <- textstat_simil(
dfm_subset(dfmat, Year %in% c(years[i], years[i + 1])),
method = "jaccard"
)
df <- rbind(df, as.data.frame(sim))
}
df
})
do.call(rbind, simpairs)
## document1 document2 jaccard
## 1 1789-Washington 1793-Washington 0.09250399
## 2 1801-Jefferson 1805-Jefferson 0.20512821
## 3 1809-Madison 1813-Madison 0.20138889
## 4 1817-Monroe 1821-<PERSON> 0.29436202
## 5 1829-Jackson 1833-<PERSON> 0.20693928
## 6 1861-Lincoln 1865-<PERSON> 0.14055885
## 7 1869-Grant 1873-Grant 0.20981595
## 8 1885-Cleveland 1893-<PERSON> 0.23037543
## 9 1897-McKinley 1901-McKinley 0.25031211
## 10 1913-Wilson 1917-<PERSON> 0.21285564
## 11 1933-Roosevelt 1937-<PERSON> 0.20956522
## 12 1937-Roosevelt 1941-<PERSON> 0.20081549
## 13 1941-Roosevelt 1945-<PERSON> 0.18740157
## 14 1953-Eisenhower 1957-<PERSON> 0.21566976
## 15 1969-Nixon 1973-<PERSON> 0.23451777
## 16 1981-Reagan 1985-<PERSON> 0.24381368
## 17 1993-Clinton 1997-<PERSON> 0.24199623
## 18 2001-Bush 2005-<PERSON> 0.24170616
## 19 2009-Obama 2013-<PERSON><PHONE_NUMBER>
## 2 1801-Jefferson 1805-Jefferson <PHONE_NUMBER>
## 3 1809-Madison 1813-Madison <PHONE_NUMBER>
## 4 1817-Monroe 1821-Monroe <PHONE_NUMBER>
## 5 1829-Jackson 1833-Jackson <PHONE_NUMBER>
## 6 1861-Lincoln 1865-Lincoln 0.14055885
## 7 1869-Grant 1873-Grant <PHONE_NUMBER>
## 8 1885-Cleveland 1893-Cleveland <PHONE_NUMBER>
## 9 1897-McKinley 1901-McKinley <PHONE_NUMBER>
## 10 1913-Wilson 1917-Wilson <PHONE_NUMBER>
## 11 1933-Roosevelt 1937-Roosevelt <PHONE_NUMBER>
## 12 1937-Roosevelt 1941-Roosevelt <PHONE_NUMBER>
## 13 1941-Roosevelt 1945-Roosevelt 0.18740157
## 14 1953-Eisenhower 1957-Eisenhower <PHONE_NUMBER>
## 15 1969-Nixon 1973-Nixon <PHONE_NUMBER>
## 16 1981-Reagan 1985-Reagan <PHONE_NUMBER>
## 17 1993-Clinton 1997-Clinton <PHONE_NUMBER>
## 18 2001-Bush 2005-Bush <PHONE_NUMBER>
## 19 2009-Obama 2013-Obama <PHONE_NUMBER>
So, for example, how would I retrieve the items in 1789-Washington that are not in 1793-Washington, and vice versa? ... And retrieve unique items for each pair of adjacent texts?
|
6573b6576c194bbc02768dfa942c29b487c3a0265399cbd435a16af0c651852e | ['43878eace8c4482181ad60bae7d25e8a'] | The solution described by <PERSON> work. And I also think "Run event handler within a same transaction" should be a feature which should be provided by Spring Data Rest. There are many common use cases to need to split logic to sepreate eventHandler. just like "triggers in database". The version show below is same as <PERSON> solution.
@Aspect
@Component
public class SpringDataRestTransactionAspect {
private TransactionTemplate transactionTemplate;
public SpringDataRestTransactionAspect(PlatformTransactionManager transactionManager) {
this.transactionTemplate = new TransactionTemplate(transactionManager);
this.transactionTemplate.setName("around-data-rest-transaction");
}
@Pointcut("execution(* org.springframework.data.rest.webmvc.*Controller.*(..))")
public void aroundDataRestCall(){}
@Around("aroundDataRestCall()")
public Object aroundDataRestCall(ProceedingJoinPoint joinPoint) throws Throwable {
return transactionTemplate.execute(transactionStatus -> {
try {
return joinPoint.proceed();
} catch (Throwable e) {
transactionStatus.setRollbackOnly();
if(e instanceof RuntimeException) {
throw (RuntimeException)e;
} else {
throw new RuntimeException(e);
}
}
});
}
}
| d4d1009dfc4509bb649a5539f4251cb4dbbda5c73a49f10332bc3d839f31516e | ['43878eace8c4482181ad60bae7d25e8a'] | I close HAL feature, because it is hard to using Resources/Resource by restTemplate. I disable this feature by following code:
public class SpringRestConfiguration implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setDefaultMediaType(MediaType.APPLICATION_JSON);
config.useHalAsDefaultJsonMediaType(false);
}
}
It work for me. HAL is good if there are more support with restTemplate.
|
3e1131ee994edf157a1e569875d5ad497d974ff8adf88479d7809caccc7af193 | ['4388d95eb54b498ba5bc78b21f5f441d'] | When, a long time ago, I held a similar position I was referred to as a "grunt", which is (AFAIK) actually an idiom for infantry man. Being compared to a soldier would not by itself be an insult, but it becomes a derogatory term when it's used by superiors to indicate your lack of status. Wiktionary describes grunt work as
"Work (especially that which is heavy, repetitive or mindless) that is
considered undesirable and therefore delegated to underlings"
so that might be a good fit for your use case.
| 4a17ca78ca0c37dbd6aa3948f54edce4b59d4bbc11e3b685c82e550828eb0c78 | ['4388d95eb54b498ba5bc78b21f5f441d'] | I plugged Nexus 5x into my iMac. Used USB file transfer to move downloaded ringtone from download folder into Android ringtone folder. It then appears in the ringtone list under sounds in settings. Choose it and then it works fine. Double checked by calling my Nexus 5x from my landline.
|
ae3a12e6ad889d38badf99f240763d5c1d5a7cf4fb05bfe2630f70c4f9154c4e | ['438bfedcc8f54edc9bc6482f0a701d5b'] | With vim bindings:
go to line 1
click Shift-V to enter Visual mode, selecting entire lines.
click Shift-G to go to end of file, while selecting all lines
click y to yank (copy) the entire contents created.
Go to the desired file:line and click p to paste the contents in clipboard
| 907b57d795dbe13784478d242abc1a67a82b2093d02cfb2003c2b9d417214200 | ['438bfedcc8f54edc9bc6482f0a701d5b'] | First, refactor your GetOperation method to accept the URL as parameter.
func GetOperation(url, operationID string) (Operation, error)...
Then, use net/http/httptest and create a test server:
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
res.Write(expectedData)
}))
defer func() { testServer.Close() }()
Finally, pass the test server URL as parameter to GetOperation:
GetOperation(testServer.URL, 'some-operation')
Validate that the function calls the url correctly and retrieves the expectedData you've passed into the test server.
|
8744adb63dab430d3b7ad59881f96337cb47f9490c30e0dff9674ff6ed834e10 | ['439473659fe4488d8c13d546806df41c'] | Here is my problem: In Laravel 6, i have a required element with the current options let say a, b, c:
<select class="form-control" name="mySelect" required>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
However, say d was a valid option previously and was saved to my back-end database. So now when I load my page, I'm setting mySelect to what is stored in the database but the select element is empty because d isn't an option anymore.
How can make it so my select element as Invalid if it has a value that is not a valid option?
| 98e7626517dee1f532d2043ae869f90e1e8c95751e44effb85e5f3202ac667be | ['439473659fe4488d8c13d546806df41c'] | I have been tying to work it out since last couple of days... and finally hope i would get some answers from the lavarel community.
While working my Laravel project where I am trying to upload an image (single image) using either drag & drop or select.
NOTE: I have a placeholder image which i want to use it as a dropzone, and also the size may vary depending on where i want to use. Now I should be able to drop an image on this placeholder image.
On drop or select the new image replaces the placeholder image (this part i am able to achieve) but when i am trying to submit the form if I have drop a file it won't get to the controller. But when i select the file i am good.
Here is what i have done so far... Can any one let me know what is wrong with the drag & drop method for submitting... the only issue i can think of is the <input type="file"> is not able to set the value when when file is dropped.
Here is my blade form
<form class="form" action="{{ route('categories.store') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="form-group row">
<label for="category" class="col-sm-4 col-form-label">Category</label>
<div class="col-sm-8">
<input id="category" type="text" class="form-control @error('category') is-invalid @enderror" name="category" value="{{ old('category') }}">
@error('category')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="slug" class="col-sm-4 col-form-label">Slug</label>
<div class="col-sm-8">
<input id="slug" type="text" class="form-control @error('slug') is-invalid @enderror" name="slug" value="{{ old('slug') }}">
@error('slug')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="order" class="col-sm-4 col-form-label">Display Order</label>
<div class="col-sm-8">
<input id="order" type="number" class="form-control" name="order" value="{{ old('order') }}">
</div>
</div>
<div class="form-group row">
<label for="status" class="col-sm-4 col-form-label">Status</label>
<div class="col-sm-8">
<select id="status" class="form-control form__select" name="status">
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="file" class="col-sm-4 col-form-label">Upload Image</label>
<div class="col-sm-8">
<div class="upload-area" id="uploadfile">
{{-- <h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1> --}}
<img class="img-fluid" src="{{ asset('img/640x480.png') }}" height="200px" id="file_preview" alt="img" />
</div>
<input type="file" name="file" id="file">
@error('file')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" class="form__submit">Save</button>
</div>
</div>
</form>
style.css
.upload-area{
width: 42%;
border: 2px solid lightgray;
border-radius: 3px;
text-align: left;
overflow: auto;
}
.upload-area:hover{
cursor: pointer;
}
.upload-area h1{
text-align: center;
font-weight: normal;
font-family: sans-serif;
line-height: 50px;
color: darkslategray;
}
#file{
opacity: 0;
}
and finally my JavaScript
// On File Drop
$('.upload-area').on('drop', function (e) {
e.stopPropagation();
e.preventDefault();
$(this).removeClass("dragover");
var file = e.originalEvent.dataTransfer.files[0];
readFile(file);
var fd = new FormData();
fd.append('file', file[0]);
// uploadData(fd);
});
// Open file selector on div click
$("#uploadfile").click(function () {
$("#file").click();
});
// file selected
$("#file").change(function () {
var file = $('#file')[0].files[0];
readFile(file);
});
function readFile(file) {
var reader = new FileReader();
reader.onload = function (e) {
$('#file_preview').attr('src', e.target.result);
};
reader.readAsDataURL(file);
}
|
cbb005ce012cffb6d26e7f2a08bd9ee1618fe67d54b1372169c552df0ce49389 | ['43a6a2785c2644a480fb385935c8ebb3'] | I asked a very bad question related to this yesterday, sorry - this is more comprehensive and makes more sense.
this is the manual for the nexys 4 FPGA i'm using https://reference.digilentinc.com/reference/programmable-logic/nexys-4-ddr/reference-manual - the relevant section is 16 - mono audio output
based on this manual, I have set the audio output to a pulse-width modulated square wave in order to try to produce a tone (the idea is that I will eventually play a short tune in the background of an arcade game I'm building for a university project). Although there are no errors or anything, I'm not hearing anything when I plug headphones into the audio output.
I'm wondering if I'm going about this the right way and whether anyone has any tips on how to produce a sound output - any sound, really, and I can build from there.
I really appreciate any help
| bbe3d079e81b367ff9d92cc5deb38ea04553001a4f6e48775ae5dea694570b31 | ['43a6a2785c2644a480fb385935c8ebb3'] | Human FOV is actually less than 180. You don't have color in the peripheral areas, and while you can detect something there, you cannot really see it ; It's more movement detection than vision.
Also, when you look at a screen, the angle formed by the lines from edge of your screen to your eye will be something between 70 and 90. An angle of 180 with your screen is only achievable if your screen covers exactly your field of view (something possible in VR).
While for gaming purpose, having a large FOV is practical because you can see much more, from a developer/editor point of view it will deform the screen (you will have to squeeze a FOV of 120 in a real FOV of 80 for instance) and can also affect performance (depending on how the game is being rendered). Plus, a dev may want that you can't see too much at any given time.
As a bonus, if you want to try what tremendous FOV looks like, most games done with the unreal engine use a .ini file for this parameter. Works with the first Borderlands for instance
|
a5e9f2baf1fbe9ae46e1c1f25a52656f26a66328aecf7f993252af932608ced0 | ['43ae42f9d1d4495ba8be4684e53ab42b'] | I don't see my situation pointed out by anyone here, so I'll add an answer:
I have been, for quite some time, playing only (online, of course) bullet games. On chess.com, out of 3889 games, 3192 are bullet. And on lichess I have 2634 bullet games out of 3215 total games.
Recently, I decided that I want to stop playing bullet, and I started focusing on blitz and rapid games. However, after about 500 games, I still finish most 5+0 games with more than 3 minutes and a half on the clock, and if I play 15+10 chances are that I will end with more than 15 minutes.
There's not strategy in it, I'm not trying to deceive the opponent or to buy some "buffer time" for the mid and end game, I have just been playing bullet for such a long time that my brain is "wired" this way and rarely I take more than 10/15 seconds to think I move. I even play fast in correspondence games!
| 8573d9d2895766e15b28eb33943f4ed8f12aa20cb5c2f58e1ebafdd3e2d328c8 | ['43ae42f9d1d4495ba8be4684e53ab42b'] | First, I want to make sure you're not making the same mistakes that most people make when it comes to calves. Doing calf specific work won't necessarily make your calves bigger, unless your chemically enhanced via steroids. When you're a natural lifter, most of your muscle growth (except for when you first start lifting weights for a few months) will happen on a systematic basis. What this means in a nutshell, is something I'm sure you've heard before...big compound movements.
Big compound movements, release more hormones, invoke more protein synthesis, and improve neural efficiency as they recruit more muscles, and energy.
In terms of calves, think about this for a second, when's the last time that you saw someone who could deadlift or squat over 500lbs and had small calves? Probably very rarely...if at all.
Now think about how many people you've seen at the gym with a massive upper body with basically twig calves? I know, I've seen a lot. This is due to not doing lower body compound movements, or just not doing them enough... for example squatting once a week may not even be enough...think about it! Let's say you do bench one day, shoulders another, and arms another...you are engaging your triceps THREE times a week as opposed to training your legs only once, I'm not saying you do this, I'm just trying to show you a picture. Now, when I had small calves, the way I overcame it was by focusing on working my legs more frequently in general, i.e twice a week, and of course adding some calf work at the end of these workouts. Because remember, you can't have big calves without somewhat of a big squat or deadlift...unless you have some great genetics, or are old (old ppl have massive calves usually)
So, to work calves, I would suggest, first do a lot of squats and deadlifts, as your lifts go up in these two movements you'll be surprised how much your calves grow. Remember, when you're natural you're more likely to grow systematically, so you need big movements like these. Particularly, a GREAT exercise for calves that most people don't seem to know about is the stiff legged deadlift, or romanian deadlift. I'm not gonna go over the form here as I'm sure you can look up the details online. But it is VERY good for your calves and a compound movement so even better. If you don't believe me, stand up straight with your legs straight, knees slightly bent, and try to touch your toes...feel the stretch in your hamstrings and calves?
Once you get the big movements out of the way like squats and deadlifts, THEN you should be focusing on some direct calf work if they're your weakness. I will tell you about a very nice trick for working calves at any gym. First, the machine that you have is actually great, and over time as you keep doing it, your shoulders will adapt and so you shouldn't really stop...maybe just go a bit lighter and do higher reps until u can move up. Now, your calves do not need a lot of weight in order to be stimulated...they are one of the few muscle groups that respond well to high rep work, such as forearms and traps. (This is because you use your forearms and calves EVERYDAY in any activity so they need slightly different stimulus in order to invoke growth). Furthermore, something most people don't know is, that your calves mostly function as stabilizers! Now given these two assumptions (they're more or less facts by now, but I'm sure some people won't agree so...), you can do A LOT of different movements to invoke calf growth.
My favourite would be to lay down two 5 or 10 or 25 lbs plates on the ground. Grab two dumbbells , one in each hand, (weight about 20-60lbs ...really depends on you). To begin, place the balls of your shoes, on the weights on the ground so that your heel is still on the ground but your upper feet are on an angle (similar to how you would start on a calf raise machine), then with the two dumbbells by your side, slowly do a calf raise, going ALL the way up , pausing at the top for 1-2 seconds, squeezing the muscle, and going ALL the way down and feeling the stretch . Do this for about 2-5 sets of 10-25 reps...increase the weight as you progress. You can also do this on a smith machine with barbell on your upper traps, but I would really suggest away from this, since like I said, your calves are stabilizers, so stay away from machines until the very end where you can overload the muscles with more weight. I.e, you can just get in a normal squat position with the bar on your back with more or less the same weight you squat with, but just do the weight elevated calf raises instead. At the end, go find a leg press machine, horizontal or vertical doesn't matter...push the weight up with your legs so that your legs are almost straight, but NOT fully locked as this will destroy your knees, keep the weight on the balls of your feet, i.e from half way up your shoes, keeping your heels not touching the platform at all, and do calf presses there for a few sets of 10-20 reps. Search up leg press calf raises for more information if you want. But after squats or/and deadlifts, you shouldn't need more than 1-2 movements for your calves.
Moreover, other than your basic calf raising movements, another great way to stimulate your calves would be to do explosive plyometric jumps. Find a hip-level box, step on it, then "walk" (NOT JUMP) off of it so you impactfully land on the balls of your feet and IMMEDIATELY jump up as high as you can, focusing on pushing and following through with your calves...again you should look this exercise up online as well for more help.
As a final note, if you REALLY have tried everything and your calves just won't grow, it would be a good idea to switch things up and work out your calves FIRST in the workout. Exercise priority (order of exercises performed in a workout) actually matters quite a lot in the long run and will benefit lagging muscles. So go to the gym, start with 1-2 of the calf movements I mentioned above (there's tons online as well, way more than any of us could list), after these your calves will be tired, so that when you perform big movements like a squat or a deadlift, your calves will be exhausted and thus will have to work twice as hard in order to keep up...effectively making the exercise more biased towards training calves.
Hope that helps.
|
fbf16fc8568bffd6ce937bb120ef37ae51723330d736544210afb3c92edfa32f | ['43bff96861e54204a0744a9c93eec072'] | I want to search my table in each column I choose. What am I doing wrong?
this is work
SELECT * FROM TABLE_ID WHERE firstname LIKE '%"+ s +"%' ORDER BY id DESC OFFSET "+ start +" LIMIT "+ localStorage.getItem('delimeter'))
this is not
SELECT * FROM TABLE_ID WHERE firstname LIKE '%"+ s +"%' OR lastname LIKE '%"+ s +"%' ORDER BY id DESC OFFSET "+ start +" LIMIT "+ localStorage.getItem('delimeter'))
| 0ce6b024a33559e193404d391d0c558cfed1b6aad0dc143c5f11ef77f6739880 | ['43bff96861e54204a0744a9c93eec072'] | Twitter uses an encoding method called 'snowflake'. There is github source
The basic format encodes a timestamp (42 bits), data center id (5 bits), and worker id (the computer at the data center; 5 bits)
For tweet IDs, they write the value as a long decimal number. Tweet ID '508285932617736192' is hex value '070DCB5CDA022000'. The first 42 bits are the timestamp (the time_t value is 070DCB5C + the epoch, 1291675244). The next five bits are the data center (in this case, '1'), and the next five bits are the worker id ('2').
For images, they do the exact same thing, but use base64 encoding (following the RFC 4648 standard for URL encoding; the last two base64 characters are hyphen and underscore).
BwjA8nCCcAAy5zA.jpg decodes as 2014-09-02 20:23:58 GMT, data center #1, worker #7
|
61a5b33d7a38a2cb724e100ccab4b21393e996dc96780caaf99c3a35cfe0a87d | ['43cee1b0fdf3471d89df3d8f305f965f'] | I have written a socket program in c. This program will send data from my android phone to my PC. Here what i need that i want to increase my data buffer size to a larger one so that i could send a large data. I used setsockopt() system call to increase the tcp buffer size. But my android not allowing me to increase the size beyond 4096 bytes. Following i pasted my Server side code. Need help
int listenfd = 0;
//Create a socket
if((listenfd = socket(AF_INET, SOCK_STREAM, 0))==-1)
{
printf("\n Could not create socket..");
return -1;
}
sock_buf_size=8192;
setsockopt( listenfd, SOL_SOCKET, SO_SNDBUF,(char *)&sock_buf_size , sizeof(sock_buf_size));
setsockopt( listenfd, SOL_SOCKET, SO_RCVBUF,(char *)&sock_buf_size , sizeof(sock_buf_size));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(8888);
// sock_buf_size = SOCKET_BUFF_SZ;
//Binding the socket
if(bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1 )
printf("\nBind failed ");
else puts("\nBind done");
//Listen to incoming connections
listen(listenfd, 5);
//Accept an incoming connection
puts("\nWaiting for incoming connections...");
c = sizeof(struct sockaddr_in);
connfd = accept(listenfd, (struct sockaddr*)&client, &c);
if((RcvdByteCnt = recv(connfd ,pSendBuff , BuffLength, 0)) != -1)
{
printf("\n Revived Byte->%d",RcvdByteCnt );
}
| 2b3577d1bb892dd03ed6e143dca7a294f138651a8cb9b63ad4ebdef0a881ed36 | ['43cee1b0fdf3471d89df3d8f305f965f'] | I have created one C binary named "SocketServer" for android. I pushed the binary into my rooted android phone's /data/local/tmp directory using
adb shell push SocketServer /data/local/tmp/
I have given permission to the exe using
adb shell chmod 0777 /data/local/tmp/SocketServer
Now i want to run this SocketServer executable using a C program running in a windows PC. Need help..
|
e8b322ed69614171779dfa7e7d0d82c8fa2f9ddd379a846f6204aff3ea953fcf | ['43fdd0ababed4c4c816b4ff57d43695a'] | You can cancel one of the $16 + n$ terms on each side, greatly simplifying the problem. Multiply both sides by $16 + n$. This gives
$$4 = \frac{10 \times 10}{16 + n}$$
Multiply both sides by $16 + n$ again. This gives
$$4(16 + n) = 100$$
Divide both sides by $4$:
$$16 + n = 25$$
Subtract $16$ from both sides:
$$n = 9$$
| ae477245ce80b202439efb32c2c8200e9be7506349787313c7178765c7889a05 | ['43fdd0ababed4c4c816b4ff57d43695a'] | Thank you! This solved my issue. I used the history as a template to figure out what fields were missing and what they should contain. I had to change the input and join fields from history with the actual layers ("top" and "base") from my code above, running the code with the same input as the history didn't cause an error but it did not provide any layer |
9c627bb2e3bc0ef1527f815540b2659ffbb67dfe8ee2aaba0bb9eaf4a96f3764 | ['43fef8ab13e14f0d86580f344f263502'] | I had the exact same error before realizing that I didn't actually define BUILDING_DLL.
Therefore, DLLIMPORT was defined as __declspec (dllimport) and not __declspec (dllexport) as it was intended. After I defined the symbol, the problem was solved.
Since you're on MinGW, you need to pass the following:
-DBUILDING_DLL
as a compiler option, or simply add
#define BUILDING_DLL
at the top of your file. The former is better, only use the #define solution if you can't figure out how to pass the -DBUILDING_DLL option to gcc.
| 761c2cdf194be82ced1103d97e4420c0a6076a24eb6005cbf73501a06e6105a4 | ['43fef8ab13e14f0d86580f344f263502'] | I had the same problem. The compilation went fine, but no .exe was generated in the target folder (.\Debug).
The problem was actually that the file containing the main() function was called "FooProject.cpp". I renamed it to "main.cpp" and then the .exe was generated properly.
In other IDEs such as Eclipse CDT, you don't need to have your main file called "main.cpp" as long as you have a proper main() function. This is apparently not the case for Visual C++.
|
647dd7e7863914a0fc3f0ce1491767012677249b83de40435521da6e7b3a2b4a | ['44011c97af3343228661a40a5ff8f96d'] | I'm getting this error in my handler function but I've no clue what's causing it. I've copied the code and debugged it in a non-handler function and there was no error.
function _responseToNext(e) {
var app = UiApp.getActiveApplication();
app.getElementById('btnPrev').setEnabled(true);
var current = parseInt(CacheService.getPublicCache().get('currentItem'));
var agendaItems = Utilities.jsonParse(CacheService.getPublicCache().get('agenda'));
agendaItems[current]['notes'] = e.parameter.tAreaNotes;
agendaItems[current]['status'] = e.parameter.lboxStatus;
CacheService.getPublicCache().put('agenda', Utilities.jsonStringify(agendaItems));
current = current + 1;
CacheService.getPublicCache().put('currentItem', current);
fillAgendaDetail(app);
// only enabled 'Next' if there are more items in the agenda
if (current < agendaItems.length-1) {
app.getElementById('btnNext').setEnabled(true);
}
return app;
}
| 35d7a0c2894a919455a1ae152e3fdfa0045a271b9d27e225842ed1f7df1af12f | ['44011c97af3343228661a40a5ff8f96d'] | I am working off of mbostock's Mobile Patent Suit
I modified the data format to link nodes by a defined key (name and type) instead of by index. I have tried modifying the tick function and selecting and and appending, but nothing seems to work.
Here's my code on JsFiddle
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node circle {
/*stroke: #fff;*/
cursor: pointer;
stroke: #3182bd;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
pointer-events: none;
text-anchor: middle;
}
.link {
stroke-opacity: .6;
stroke-width: 1.5px;
stroke: #666;
fill: none;
}
.link.deliverFor {
stroke: green;
}
.link.sentTo {
stroke-dasharray: 0,2 1;
}
/* color of nodes based on type */
circle.emailAddress {
fill: blue;
}
circle.ip {
fill: red;
}
circle.missing {
fill: "#3182bd";
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var color = d3.scale.category20();
var linkDistanceScale = d3.scale.linear()
.domain([10, 5000])
.range([2, 300])
.clamp(true);
var force = d3.layout.force()
.linkDistance(30)
.charge(-120)
.size([width, height]);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var graph = {
"nodes": [
{
"name": "<EMAIL_ADDRESS>",
"type": "emailAddress",
"size": 1234
},
{
"name": "192.168.0.1",
"type": "ip",
"size": 870
},
{
"name": "<EMAIL_ADDRESS>",
"type": "emailAddress",
"size": 3423
}
],
"undirectedNeighbors": [
{
"label": "deliverFor",
"left": {
"name": "<EMAIL_ADDRESS>",
"type": "emailAddress"
},
"right": {
"name": "192.168.0.1",
"type": "ip"
},
"weight": 366
},
{
"left": {
"type": "emailAddress",
"name": "<EMAIL_ADDRESS>"
},
"right": {
"type": "emailAddress",
"name": "<EMAIL_ADDRESS><IP_ADDRESS>",
"type": "ip",
"size": 870
},
{
"name": "bar@pp.com",
"type": "emailAddress",
"size": 3423
}
],
"undirectedNeighbors": [
{
"label": "deliverFor",
"left": {
"name": "foo@pp.com",
"type": "emailAddress"
},
"right": {
"name": "<IP_ADDRESS>",
"type": "ip"
},
"weight": 366
},
{
"left": {
"type": "emailAddress",
"name": "foo@pp.com"
},
"right": {
"type": "emailAddress",
"name": "bar@pp.com"
},
"label": "sentTo",
"weight": 777
}
]
};
var my_nodes = graph.nodes.slice(),
my_neighbors = graph.undirectedNeighbors.slice();
console.log("my_neighbors", my_neighbors);
var hash_lookup = [];
// make it so we can lookup nodes by entry (name: x, type, y) in O(1):
my_nodes.forEach( function(node) {
var key = {name: node.name, type: node.type};
hash_lookup[key] = node;
});
// tell d3 where to find nodes info
my_neighbors.forEach( function(link) {
var left = link.left;
var right = link.right;
var leftKey = {name: left.name, type: left.type};
var rightKey = {name: right.name, type: right.type};
link.source = hash_lookup[leftKey];
link.target = hash_lookup[rightKey];
});
console.log("my_neighbors", my_neighbors);
console.log("my_nodes", my_nodes);
console.log("neighobrs", graph.undirectedNeighbors);
/************** SETUP FORCE LAYOUT ****************/
force
.nodes(my_nodes)
.links(my_neighbors)
.linkDistance( function(d) {
console.log("linkDistance", d);
return linkDistanceScale(d.weight);
})
.start();
console.log("force.links()", force.links());
/************** DRAW PATHS ****************/
var link = svg
.append("svg:g") // the "curves" is drawn inside this container
.selectAll("path")
.data(force.links())
.enter()
.append("svg:path")
// .attr("class", "link")
.attr("class", function(d) {
return "link " + d.type;
});
/************** DRAW CIRCLES ****************/
var node = svg
.selectAll(".node")
.data(force.nodes());
var circle = node
.enter()
.append("circle")
.attr("class", "node")
.attr("r", function(d) {
console.log("circle d", d);
return Math.sqrt(d.size) / 10 || 4.5;
})
.attr("class", function(d) {
return d.type || "missing"; // color circle based on circl.* defined above
})
.call(force.drag);
/************** DISPLAY NAME WHEN CURVER HOVER OVER CIRCLE ****************/
var text = circle.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
node
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; });
});
</script>
Any insight would be greatly appreciated.
|
1f6407b56145fc917a41455f38c79bd41f4cccf4f409932700286bb7d6498413 | ['440b2fb586e54b4e822129c170f99adb'] | I am trying to redirect the stderr of a script to a variable to use it in if/else statements. What I need is the program to behave in one way or another according to the stderr.
I have found this post using StringIO which may suit my needs, but I cannot figure out how to make it to redirect stderr. I'm sure it is quite easy, but I'm quite new to python and any detailed help will be really appreciated.
Thanks!
<PERSON>
| e7d3a61561a2af5c2dc3de51185da838263920e348c6d08459a2f646f47f0913 | ['440b2fb586e54b4e822129c170f99adb'] | I am writing a scraper using Scrapy. One of the things I want it to do is to compare the root domain of the current webpage and the root domain of the links within it. If this domains are different, then it has to proceed extracting data. This is my current code:
class MySpider(Spider):
name = 'smm'
allowed_domains = ['*']
start_urls = ['http://en.wikipedia.org/wiki/Social_media']
def parse(self, response):
items = []
for link in response.xpath("//a"):
#Extract the root domain for the main website from the canonical URL
hostname1 = link.xpath('/html/head/link[@rel=''canonical'']').extract()
hostname1 = urlparse(hostname1).hostname
#Extract the root domain for thelink
hostname2 = link.xpath('@href').extract()
hostname2 = urlparse(hostname2).hostname
#Compare if the root domain of the website and the root domain of the link are different.
#If so, extract the items & build the dictionary
if hostname1 != hostname2:
item = SocialMediaItem()
item['SourceTitle'] = link.xpath('/html/head/title').extract()
item['TargetTitle'] = link.xpath('text()').extract()
item['link'] = link.xpath('@href').extract()
items.append(item)
return items
However, when I run it I get this error:
Traceback (most recent call last):
File "C:\Anaconda\lib\site-packages\twisted\internet\base.py", line 1201, in mainLoop
self.runUntilCurrent()
File "C:\Anaconda\lib\site-packages\twisted\internet\base.py", line 824, in runUntilCurrent
call.func(*call.args, **call.kw)
File "C:\Anaconda\lib\site-packages\twisted\internet\defer.py", line 382, in callback
self._startRunCallbacks(result)
File "C:\Anaconda\lib\site-packages\twisted\internet\defer.py", line 490, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "C:\Anaconda\lib\site-packages\twisted\internet\defer.py", line 577, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "E:\Usuarios\Daniel\GitHub\SocialMedia-Web-Scraper\socialmedia\socialmedia\spiders\SocialMedia.py", line 16, in parse
hostname1 = urlparse(hostname1).hostname
File "C:\Anaconda\lib\urlparse.py", line 143, in urlparse
tuple = urlsplit(url, scheme, allow_fragments)
File "C:\Anaconda\lib\urlparse.py", line 176, in urlsplit
cached = _parse_cache.get(key, None)
exceptions.TypeError: unhashable type: 'list'
Can anyone help me to get rid of this error? I interpret that it has something to do with list keys, but I don't know how to solve it.
Thanks you so much!
<PERSON>
|
0019d07d79badef02649cbd43c9b99c5ab1cd4a30b3d8162757e24fb23afe4fa | ['440e5cdb6986475aa0663b12bafb311d'] | I would like to set a specific Date programatically for my control with Angular2, but no matter how I try it, the input always displays "yyyy. mm. dd." in my browser.
Here's my code:
HTML:
<input class="form-control" type="date" [(ngModel)]="dateFrom" name="dateFrom" min="2016-10-01" [value]="2016-10-01" />
Typescript
public dateFrom: Date;
constructor() {
}
ngOnInit() {
this.dateFrom = new Date(Date.parse("2016-10-01"));
}
Please note that min="date" and [value]="date" also didn't work in pure HTML code. Is there something I'm missing or it is a really bad idea, to set an input's value from code?
| 482710ef3fd5d28f8c455908cf9783b936d462438520b6df42bc148a3cc47f9e | ['440e5cdb6986475aa0663b12bafb311d'] | Currently I'm using a quite common solution to load a JSON file's content into my Angular 5 application that I can inject into my components. This works like it's described here under section Runtime configuration.
I'm using an npm package which needs to be initialized in my app.module.ts file
@NgModule({
declarations: [
AppComponent
],
imports: [
/* .... */
[MsalModule.forRoot({
clientID: "...",
authority: "...",
redirectUri: <I need the value here from the JSON file>
})]
],
providers: [
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: (config: ConfigService) => () => config.load(),
deps: [ConfigService],
multi: true
}
]
bootstrap: [AppComponent]
})
export class AppModule { }
I use Angular-CLI and I know that I could use different environment files, but the content of the JSON file might change after building the application and I cannot rely on that.
Is there a way to use a value from the JSON file immediately in the NgModule declaration, where I need it?
|
2af6ec5f21b3383c6378b68a145ecfb110bf9173360bc57d92bd4d6d65deac5a | ['44164dac296943df87c2ed37f65e75f4'] | Good question! In the future, could you also indicate the details of rest of the hand? A fuller history of the hand would help everyone put a read on the hand here, because your 30% odds really depends on what's already made. You have 30% against a lot of hands, but that 5 is only a draw if the flush isn't already made. | 23800fec38890e5fff7c79fc887efb1fde4cacbe9201ac6e36b6541a6bd5eb61 | ['44164dac296943df87c2ed37f65e75f4'] | Ascorbic acid? I haven't tried that before, I do get some spreading when I use much whole grain, and some vitamin C cannot hurt :D Anyway, folding is great way to make the bread firmer. I fold 3-4 times on my sourdough and it firms up for each time I fold. |
ace86c8c0acb1a6df3aadbef005eae94d12d68a4abc51c8e811e6b4a87bb807b | ['441dd7c4882b49c0a702b822ef66d676'] |
My can light junction box has 2 black clamps for NM cables and there are 3 metal knockout holes on 3 sides of junction box. (Picture shows one of these 3 knockouts).
Given the location of LINE wire and can light locations in celling, can I attach 3 NM (romex) cables with one can light ? Can light junction box has only 2 clamps , but can I use knockout hole ( metal) for 3rd cable? All cables are NM cables
1 LINE cable (through Knockout holes)
2 cables connecting to 2 other can lights. ( Through black clamps)
Take a look at diagram with red color can in question.
| 87ee2d799f95814bf0a8a9ce636f3389d53288aa4c9ebaa6db9fed8d418934f6 | ['441dd7c4882b49c0a702b822ef66d676'] | $$ \pi = \int_{-\sqrt{2}}^{\sqrt{2}} \sqrt{2-x^2} dx $$
So, thinking I was going to discover something amazing I reasoned that this is equal to pi, and that all I had to do to get the exact value of pi was to find the indefinite integral.
$$ \int \sqrt{2-x^2} dx = \space ? $$
Of course, I couldn't, not even with partial integrals.
So now I'm wondering whether this is possible, but I don't think so.
:)
|
5b875dcdf6f8239f5aaeb46a91ebe7ed01b295b00464a5cf33634612d8898470 | ['441edafe3fa9468f815390a468441587'] | I'm not sure what exactly I'm doing wrong, but I want to get the variables from the get methods into a print statetment in the testClass. For instance, the user enters all the information, and then outputs the statement.
import java.util.Calendar;
import java.util.Scanner;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class testClass {
public testClass() {
System.out.println("ALARM SET TO: " + getHour ":" + getMinutes + amOrPm);
}
public int getHour() {
Scanner input = new Scanner(System.in);
int getHour;
System.out.println("ENTER HOUR FOR YOUR ALARM: ");
getHour = input.nextInt();
return getHour;
}
public int getMinutes() {
Scanner input = new Scanner(System.in);
int getMinutes;
System.out.println("ENTER MINUTES FOR YOUR ALARM: ");
getMinutes = input.nextInt();
return getMinutes;
}
public int getAMOrPM() {
Scanner input = new Scanner(System.in);
int amOrPm;
System.out.println("ENTER AM or PM FOR YOUR ALARM: ");
amOrPm = input.nextInt();
return amOrPm;
}
public void getSystemTime() {
DateFormat df = new SimpleDateFormat("HH:mm");
Calendar calobj = Calendar.getInstance();
System.out.println(df.format(calobj.getTime()));
}
} // end of testClass
| 4eebacdf8e783902eb62e3aa14e8f38bbf44265822e597733bb8087ffd9a30ca | ['441edafe3fa9468f815390a468441587'] | I'm having problems calling the function displayArray. It says expected an expression. What am I doing wrong? I don't quite fully understand how calling a function works, any help is appreciated. I'm still working on this program and my only problem right now is calling functions.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH myFlush()
#define SIZE 100
#define LB 1
#define UB 100
// ProtoType Functions Here
void myFlush();
int loadArray(int num[], int c);
void displayArray(int num[], int c);
void enterAnumber();
main() {
int userChoice = 0;
do {
CLS;
printf("=======================\n");
printf("====== MAIN MENU ======\n");
printf("=======================\n");
printf("1. Enter a number \n");
printf("2. Display the sum of all numbers entered \n");
printf("3. Display Average of numbers entered \n");
printf("4. Display all numbers entered \n\n");
printf("5. Quit the program \n\n");
printf("Enter your selection: ");
scanf("%i", &userChoice);
switch (userChoice) {
case 1: // Enter a number
enterAnumber();
PAUSE;
break;
case 2: // Display the sum of all nums ent
PAUSE;
break;
case 3: // Display the average of all nums ent
PAUSE;
break;
case 4: // Display all numbers entered
displayArray(int num[], int c);
PAUSE;
break;
case 5: // QUIT THE PROGRAM
PAUSE;
break;
default:
PAUSE;
break;
} // end switch
} while (userChoice != 4);
PAUSE;
} // end of main
//============================================
void enterAnumber() {
int numbers[SIZE];
int count = 0;
// seed the rand function
srand((unsigned)time(NULL));
// displayArray(numbers, count); // ArrayStats
count = loadArray(numbers, count);
}
void displayArray(int num[], int c) {
int i;
for (i = 0; i < c; i++) {
printf("The number selected: %i\n", num[i]);
}
PAUSE;
}
int loadArray(int num[], int c) {
int result;
int i;
int howMany;
printf("How many numbers do you wish to create: ");
scanf("%i", &howMany);
for (i = 0; i < howMany; i++)
num[i] = LB + rand() % (UB - LB + 1);
result = c + howMany;
return result;
} // end loadArray
void myFlush() {
while (getchar() != '\n');
}
|
efea81cc6deb2abfeb6d6ea09bfc4e8f30b3858b9417fe44a8d55a943721cd90 | ['44223c1d8fda4f4095c48fbee6d7f0d2'] | me encuentro trabajando en mi proyecto de titulación y debo hacer un sistema que trabaje en base a una API. Esta API debo integrarla a una Base de Datos, o sea, debo extraer toda la informacion referente a la empresa para la que trabajo e integrarla a una bd local. He probado varias maneras de hacerlo, pero me encuentro con el problema de que el servidor detecta demasiadas peticiones simultaneas. Mi codigo es el siguiente:
<?php
function cambiarFormatoFecha($fechaI){
$cont = 0;
while(strtotime($sumarDias)<strtotime(date('d-m-Y'))){
$sumarDias = date('d-m-Y', strtotime($fechaI. ' + '.$cont.' days'));
$desarmar = explode("-",$sumarDias);
$nuevaFecha = $desarmar[0].$desarmar[1].$desarmar[2];
$ch = curl_init();
$mh = curl_multi_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL,"http://api.mercadopublico.cl/servicios/v1/publico/ordenesdecompra.json?fecha=".$nuevaFecha."&CodigoOrganismo=7106&ticket=DF140AC7-B227-44C7-95DD-FEA0AF61C542");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$data = curl_exec($ch);
curl_close($ch);
$result = json_decode($data,true);
echo $nuevaFecha."<br>";
if(is_array($result['Listado']) || is_object($result['Listado'])){
$h = 0;
sleep(10);
foreach ($result['Listado'] as $value) {
$ch2 = curl_init();
$mh2 = curl_multi_init();
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2,CURLOPT_URL,"http://api.mercadopublico.cl/servicios/v1/publico/ordenesdecompra.json?Codigo=".$value['Codigo']."&ticket=DF140AC7-B227-44C7-95DD-FEA0AF61C542");
curl_setopt($ch2,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch2, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
curl_setopt($ch2, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch2, CURLOPT_TIMEOUT, 60);
$data2 = curl_exec($ch2);
curl_close($ch2);
$result2 =json_decode($data2,true);
if(is_array($result2['Listado']) || is_object($result2['Listado'])){
foreach ($result2['Listado'] as $value2) {
echo $value2['Codigo']." ".$value2['Nombre']." ".$value2['CodigoLicitacion']." ".$value2['TipoMoneda']."<br>";
sleep(10);
}
}
}
}
//sleep(10);
$cont++;
}
}
cambiarFormatoFecha('01-10-2018');
?>
Alguna idea/recomendacion para hacer esto? Es primera vez que trabajo con una API, y en un proyecto tan grande.
| d738686568fd4907399adc3c859821afca3286ef7985e50a0331528359658800 | ['44223c1d8fda4f4095c48fbee6d7f0d2'] | Es una api externa que almacena datos de compras que las empresas realizan a proveedores del estado. Por ahora solo puedo acceder a la informacion obteniendo el codigo por fecha, y la OC por codigo, si quisiera graficar datos entre una fecha y otra necesito si o si tener todas esas OC, ya que la api no me permite extraer en base a un rango, ademas me pidieron como requerimiento que migrara toda la data a la BD. Y es el servidor de la api quien me limita las request. |
55eadb691bc3cf5bfdc6d2f0d7486fda23d6a7e8fbda32f5f884d9f2373ccba4 | ['4422a91eceda40f7a37b49850d2fbbf5'] | When you want to check if 2 range dates overlap at any point, you need to check for 2 cases:
Case1: The FromDate is inside the range from fromdate_date to todate_date; and,
Case2: The ToDate is inside the range from fromdate_date to todate_date.
If any of these conditions is true, than there is an overlap.
Before the cases, the proof that if neither the conditions are met, than there's no overlap. Using the diagram of <PERSON>:
fromdate_date f***********t todate_date
FromDate F#########T ToDate F#########T
Look how, here, neither the FromDate's nor the ToDate's are between fromdate_date and todate_date.
Case1
It doesn't matter if the billboard finishes before the todate_date, or after, as long it starts after (or at) the fromdate_date AND before (or at) the todate_date.
f***********t
F#########T
F#####T
You can feel that the FromDate is trapped inside fromdate_date and todate_date, and so it must overlap with them.
Case2
It doesn't matter if the billboard starts before the fromdate_date, or after, as long it finishes after (or at) the fromdate_date AND before (or at) the todate_date.
f***********t
F#########T
F#####T
Analogously, you can feel that the ToDate is trapped inside fromdate_date and todate_date, and so it must overlap with them.
So, your conditions about the dates must look like:
...
&& ((FromDate >= fromdate_date && FromDate <= todate_date)
|| ToDate >= fromdate_date && ToDate <= todate_date))
select ...
| ba26d1794ef1d957f833efeda7b48c017407a19482050f355dfdd4957d3869f7 | ['4422a91eceda40f7a37b49850d2fbbf5'] | You can declare it as a List<Sale> (I'm supposing Sales is a collection of Sale's.
Int filter = sale.filter;
List<Sale> sales;
if (filter == null) {
sales = _db.Sales.ToList();
}
else
{
sales = _sb.Sales
.Where(s => s.SalesStatusID == salesStatusfilter)
.ToList();
}
Depending on what you want to do with the data it should suffice.
|
9fd7eb415cb2c72a45825740b6c414cee49d7da98116530affd8ae4e4130ff5b | ['4424643b2ed949219557a4e18e783829'] | <PERSON> What is the exact difference between <PERSON>'s worlds and <PERSON> "multiple histories"? And also, you say we could get a "map" of all <PERSON>'s possible worlds, but, as far as I know, <PERSON>'s worlds would only be based in our laws of physics while in <PERSON>'s "path integral" we could get all logically possible universes (even ones with completely and radically different fundamental constants and laws of physics). So, wouldn't we get much more worlds than <PERSON>'s interpretation? | 073b64354c6a422a914258dc29c138de184af6bd6c1bbb960ea91fac0078e4dc | ['4424643b2ed949219557a4e18e783829'] | You have to be working with a single folder.
"All photographs" and Smart Collections will work if the entire catalog references only a single folder.
Photos excluded by attribute/metadata still count for this purpose. Doing "all photographs" then using metadata filtering to restrict display to a single folder doesn't help.
|
b74abd52a268a9f30c902b0fd6940174833a31c7271fd9a31ad68f1ff46c2e03 | ['442b9ba4c10049e09dc5b52a379aa6c0'] | The simple answer is that an IRQ (Interrupt ReQuest) is a hardware input which is mapped by the system to an interrupt. In the case of the keyboard IRQ1 is mapped to interrupt 9.
The happy answer is that interrupt 31h in this context is obviously an error or typo.
Interrupt request
| d4d6e337757bbc4a16e803ca4b89616cf80ea743cadc99091117f1136bf364db | ['442b9ba4c10049e09dc5b52a379aa6c0'] | The simple answer is that logical sector 19 is the 20th sector (numbering starts at 0).
20 divided by 18 sectors per track results in a remainder of 2. Sector numbering begins at 1 so the sector number is 2. There is only one physical disk in a floppy disk and thus 2 sides - head 0 and head 1. The 2nd sector of the 2nd side is cylinder 0 (numbering starts at 0) and the 2nd side is head 1 (numbering starts at 0).
Head 1 (DL), Cylinder 0 (CH), Sector 2 (CL)
The happy answer is that the latest version of MikeOS will boot and run from a USB flash drive. Say goodbye to floppy disks (if you can find one).
|
71f747df7fcea53d2cdb8bb29a885e9664d4b55532a1f0d5aae83b8b082a1738 | ['442ff933769b4b7e85b33b8098e06b4a'] | http://www.novell.com/support/kb/doc.php?id=7007165
Beginning with kernel 2.6.37, it has been changed the meaning of dropped packet count. Before, dropped packets was most likely due to an error. Now, the rx_dropped counter shows statistics for dropped frames because of:
Softnet backlog full
Bad / Unintended VLAN tags
Unknown / Unregistered protocols
IPv6 frames when the server is not configured for IPv6
[...]
If the rx_dropped counter stops incrementing while tcpdump is running; then it is more than likely showing drops because of the reasons listed earlier.
| cfd49d63c869937566ec2c91a274e413e4ef8ea3e1b319d5508fbb39d3b4942e | ['442ff933769b4b7e85b33b8098e06b4a'] | @wireghoul Not arguing at all, just curious why this isn't considered a premature optimization. To me, in the context of JS, it's like caching an array.length in a for loop. The difference is so minute, it won't be reflected with `console.time()`, and whatever time fluctuations you do register will be due to unrelated factors like other running processes. In a C binary with specialized tools to examine assembly code perhaps, but in JS, no way. |
f6183c37d3784a22fcbd5f9e0d28c102cde1432d12863721c584d7670aafd3c5 | ['443271e4f11040cc9aec3dcb07dd723a'] | I looked over this list and i didn't find any answer on how to create a new network interface like you usually do with `ifconfig'. What i want to achieve is create an interface for every string item in a variable list, but before that i want to delete all interfaces excluding the one that ansible-playbook is using for deploying a play. Does any of you have an idea how to approach such task ?
| 6c6df8d1ee623d8019586c52d7da94739cfa41ef6168f04f5c0dd6c8281f1ffe | ['443271e4f11040cc9aec3dcb07dd723a'] | <PERSON> answer was of much help, but i found just realized that generating config entries in my case could be solved in an less complex way. Instead of trying to iterate over list or a string variable variable in jinja template file template.conf.j2 like did with :
{% for conf_line in conf_list %}
{{conf_line}}
{% endfor %}
you could just enter insert new line signs while generating string in defaults/main.yml:
conf_list: "{%for ip in ip_list%}server {{ip}}:6666\n{%endfor%}"
and then just insert that whole string into a template.conf.j2 like this:
{{conf_line}}
nevertheless i have no other idea how to generate list of ip addresses other than the one <PERSON> proposed.
|
db0e87c351a0078f4c79d8b64c99eb55dc088ea5b42f22ebcb11e8094478c3b7 | ['44439460462c4f6880f13b72b6595d03'] | Here is an example from last API spec:
import com.sendgrid.*;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
Email from = new Email("<EMAIL_ADDRESS>");
String subject = "I'm replacing the subject tag";
Email to = new Email("<EMAIL_ADDRESS>");
Content content = new Content("text/html", "I'm replacing the <strong>body tag</strong>");
Mail mail = new Mail(from, subject, to, content);
mail.personalization.get(0).addSubstitution("-name-", "Example User");
mail.personalization.get(0).addSubstitution("-city-", "Denver");
mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932");
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
}
https://github.com/sendgrid/sendgrid-java/blob/master/USE_CASES.md
| ab09c56cda6920e78b4e507d1548c88c5032f8d6ca415c338ea8b39f77d13c96 | ['44439460462c4f6880f13b72b6595d03'] | No does not worked for me....
sudo apt install --reinstall libboost-all-dev
Preparing to unpack .../libboost-all-dev_1.58.0.1ubuntu1_amd64.deb ...
Unpacking libboost-all-dev (1.58.0.1ubuntu1) over (1.58.0.1ubuntu1) ...
Setting up libboost-all-dev (1.58.0.1ubuntu1) ...
/usr/include$ ls -ld /usr/include/b*
-rw-r--r-- 1 root root 1404 Jan 14 21:49 /usr/include/byteswap.h
marius@HPP:/usr/include |
af32bb9ec628cbecec6fd6e8f3f6265f1feb6500ef77ae316b240e95f0d940c6 | ['444a58bf26b446fa96af7721d8f4a56b'] | I wonder if there is any way to speed up the network communication between 2 KVM guests on the same physical machine.
Would that help at all if I would configure a separate bridge network for just the two of them (vnet5+vnet6) or is there any way to setup an even faster network between Guests something like unix sockets?
Thanks
| 89cc6da45fb05bcdba2df38d68fdb551dea2f007e5db6f1bf5ab252676feda11 | ['444a58bf26b446fa96af7721d8f4a56b'] | В общем у меня есть проект, которые скачивает архив 7zip после проверяет есть ли он и тогда пытается его распаковать с помощью библиотеки rg.apache.commons.compress версии 1.17, но на это строке SevenZFile sevenZFile = new SevenZFile(file); выпадают следующие ошибки
Process: com.example.anton.fias_app, PID: 9102
java.lang.NoSuchMethodError: No virtual method toPath()Ljava/nio/file/Path; in class Ljava/io/File; or its super classes (declaration of 'java.io.File' appears in /system/framework/core-oj.jar)
at org.apache.commons.compress.archivers.sevenz.SevenZFile.<init>(SevenZFile.java:108)
at org.apache.commons.compress.archivers.sevenz.SevenZFile.<init>(SevenZFile.java:262)
at com.example.anton.fias_app.MainActivity$Unzippy.run(MainActivity.java:363)
Подскажите дураку, что делать, файл тот точно существует, в интернете натыкался на людей использующих данную библиотеку в android studio, но сам застрял на этом моменте.
File myPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/FIAS_BD");
File file = new File(myPath, "FIAS.7z");
SevenZFile sevenZFile = new SevenZFile(file);
|
b8cdcc5546b817bc53b7bd6c88d1fd0feab8b755234126bc91c908eae3934b7f | ['444bed9836f0430e881140008f963606'] | I have a variable initial_value, equal to 1000, that I would like to sum to values on Column B. initial_value and Column B will only be summed when Column C is equal to 1 and not 0. Therefore, the resulting initial value after the Class operation should be 1030 (or 1000 + 10 - 30 + 70 + 10). So far I have tried:
import pandas as pd
from __future__ import division
import numpy as np
df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
"B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
"C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})
A = df['A']
B = df['B']
C = df['C']
initial_value = 1000.00
class test:
def __init__(self, A, B, C, initial_value):
self.A = A
self.B = B
self.C = C
self.initial_value = initial_value
def test_values(self):
self.initial_value = self.initial_value + self.B
return self.initial_value
x = test(A, B, C, initial_value)
x.test_values()
print x
| 47db6bedc03caae5f916e759e10af39df72650ff2d3edd8f9008e71db8ebade7 | ['444bed9836f0430e881140008f963606'] | I would like to separate my DataFrame from twelve rows to three DataFrames by column value, and then apply a set of code to all DataFrames simultaneously.
A B C
1 A 0.25 0
2 A 0.50 0
3 A 0.75 0
4 B 1.00 1
5 B 1.25 1
6 B 1.75 1
7 C 0.50 1
8 C -0.25 0
9 C 1.25 1
10 D 0.75 1
11 D -0.75 0
12 D -1.00 -1
The resulting DataFrames should be:
A B C
1 A 0.25 0
2 A 0.50 0
3 A 0.75 0
4 B 1.00 1
5 B 1.25 1
6 B 1.75 1
7 C 0.50 1
8 C -0.25 0
9 C 1.25 1
10 D 0.75 1
11 D -0.75 0
12 D -1.00 -1
So far, I have tried df.groupby(['A']) and df.set_index(['A']) but theses functions do not seem to allow me to apply a set of code without errors.
|
9bfde526121a79d9fc61eb9a54d3c9e96fe9b857ad38133d7611fa8103c90139 | ['4452bb04a11240f39cf61c4817930694'] | Let's assume that we have a sequence Xn of numbers drawn from a uniform distribution on (0,1). Can I, for example, split sequence in two, x1, x3, x5,... (odd indexes) and x2, x4, x6... (even indexes) and treat two sequences as observations of two independent random variable (uniformly distributed over (0,1) )?
UPD.
I will try to reformulate the original question. Given a random number generator X which produces uniformly distributed numbers (on(0,1)) can i make two random number generators Y1 and Y2 considering each first number from X as a number, generated by Y1 and each second as generated by Y2?
| 3e33bc25e9ce3ae0597c27864d7752e17517513209303ff8e9211ce9f7957b5b | ['4452bb04a11240f39cf61c4817930694'] | I have checked "Real Computing Made Real". While it indeed includes some relevant advice, but definitely does not provide a general framework.
The second book seems to be outdated and could be used as starting point for writing a modern book on the topic. However, it is not something which can be used out of the box for the analysis of applied problems. |
5368b95f275f2b7f943d6fc159615b7738f309d854abdd9118938446b59b9219 | ['44533ddc665544a4a7e83b54e331dcb3'] | you can't call this.props.addBookMutation, in your case for a class component call it by this.props.mutate({}) for more info
submitForm(e) {
e.preventDefault();
this.props.mutate({
variables: {
name: this.state.name,
genre: this.state.genre,
author: this.state.author,
}
}).catch(res => {
const errors = res.graphQLErrors.map(err => err.message);
this.setState({ errors });
});
}
| 92f8b5bbd1d1dc6a731a0108f85ec64a99f597eb59e3c39eb01d1b55daeef12b | ['44533ddc665544a4a7e83b54e331dcb3'] | the reason for this error applianceId is required and appliance._id will be undefined because you have to wait for model.appliances.find( ..... )
// add async to the callback function for your endpoint
app.post('/your_url', async (req,res)=>{
const appliance = await model.appliances.find(a => a.name == data.appliance);
if(!appliance) res.status(400).send({error:'appliance not found'});
console.log(appliance._id); // should console the _id
const doc = {
time: data.time,
value: data.value,
applianceId: appliance._id
};
const applianceDataModel = new ApplianceDataModel(doc);
await applianceDataModel.save();
res.send({message:'Appliance has been saved'}
});
|
98ba77a47898bee4dcf8301d0be330e010ee5354687ba76a27f4c90ea3a4a40a | ['4467e93ec5174bb882eb1a77110b7765'] | I would like to know if its possible to make an AJAX post request to submit a file path to a form. Basically, I want to know if its possible to simulate the path a normal input type="file" would create, but in an AJAX request. Also, is it possible for that link to be pointing to a file on another website?
I think I have no other choice since I don't have access to server-side scripts (PHP), and that is because what I want to create is a greasemonkey script (userscript).
Thanks for answers.
| 1e358951cdcc9cded86db0c0a2682e4056c4a6a9c3c16de19954e8528b44cf5c | ['4467e93ec5174bb882eb1a77110b7765'] | One of the source servers is sending the files to destination servers using lftp. The umask setting in the destination host is 007(in proftpd.conf file), so the files landing in the destination servers should be 660(007-666), but the permissions are varying.
What could be the factors contributing to the permissions of the files while transferring from one host to another using lftp?
|
d08e99811b25dfd715f4fa4ff0e8e55efeca319474dde6d3997cc7bf664fa25f | ['447617b5daa04728a6599eaacf8fdf54'] | I created a matrix of entry boxes using Tkinter and Python 2.3. What I want to do is to check the row of the entry box for a keyword and then insert a text into an entry box with the same row but of different column. For example, take a simple 3x3 entry box matrix:
Food Like Dislike
Apple Yes
Orange Yes
Let's say I have two lists that corresponds to each other as such:
1. [Apple, Orange]
2. [Dislike, Like]
I would like to check that if first element in list 1 is Apple and first element in list 2 is Dislike, then I want to insert a text "YES" into the entry box of 2nd row and 3rd column as shown in the above matrix.
I have appended the entry box indexes into two lists. First list contains the indices of the 1st column of entry boxes. Second list contains the 2nd and 3rd columns of the entry boxes. Problem is, how to determine the correspoding row and column of the entry box to insert the Yes???
Hope you can understand! This example is the most elementary one. My actual matrix consist of more rows and columns. An idea or sample code will help a lot.
Thank you Tkinter Gods.
| 0cb9cb242d840ca8ae573a440dcc506a8427ecee37bec3f6055463e8c3f81dfb | ['447617b5daa04728a6599eaacf8fdf54'] | Ok I think the question is not clear to most of you. Anyway here is my solution:
I append the values from each section into a list inside a for loop. For example, in section A, the list will contains 1,2 and 3. The len of the list in section C will be only 2. Thus, we know that a value is missing from section C. From here, we can print out section C. Sorry for the misunderstandings. This question is officially close. Thanks for the view anyway!
|
1a35d4780baad9dd70eaae2ce2a3b2d605df7ab9bd5cad8509b692351018c886 | ['44917fe93e29444382df445c2c9bdcc7'] | DROP PROCEDURE IF EXISTS Cursor_Test;# MySQL returned an empty result set (i.e. zero rows).
DELIMITER $$
CREATE PROCEDURE Cursor_Test()
BEGIN
DECLARE Project_Number_val VARCHAR( 255 );
DECLARE Project_List_val VARCHAR(255);
DECLARE no_more_rows BOOLEAN;
DECLARE loop_cntr INT DEFAULT 0;
DECLARE num_rows INT DEFAULT 0;
DECLARE projects_cur CURSOR FOR
SELECT Project_Id
FROM Project_Details;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_rows = TRUE;
OPEN projects_cur;
select FOUND_ROWS() into num_rows;
the_loop: LOOP
FETCH projects_cur
INTO Project_Number_val;
IF no_more_rows THEN
CLOSE projects_cur;
LEAVE the_loop;
END IF;
SET Project_List_val=CONCAT(`Project_Number_val`,'_List')
-
> ---> **Please check am I doing CONCAT correct here?**
Insert Into test (Panel_Id) select Panel_Id from Project_List_val where Project_Number_val='9';
> --->**Is this taking 9_List as table name?**
SET loop_cntr = loop_cntr + 1;
END LOOP the_loop;
select num_rows, loop_cntr;
END $$# MySQL returned an empty result set (i.e. zero rows).
DELIMITER
Any suggestions?
Hi All,
I have a variable in stored procedure named Project_Number and it is of varchar type.
My Requirement is "for each project number query the table project_Number_List get results from list and insert into other table"
Lets say, Project_Number might be like this 22,21,34,43,434
corresponding tables I need to query is something like this 22_List, 21_List,34_List .....
I'm using cursor to loop through the Project_Number but my problem is how to mix the project_number and _list i.e., 22_list to query the table 22_List
| 5f1adebbe4541ceef212fb22ab5bde5db769ee4de3c9919f3e50339fc672d3c2 | ['44917fe93e29444382df445c2c9bdcc7'] | SET Project_List_val=CONCAT(Project_Number_val,'_List');
Insert Into test (Manthan_Panel_Id) select Manthan_Panel_Id from Project_List_val where Project_Number_val='9';
In the insert statement there is the variable named 'Project_List_val' which consist of table name as concated in the above step. This statement is not taking the content of the variable as table name instead it is taking 'Project_List_val' as table name and giving table not found error.
Any suggestions?
|
5ddd5c13834b0ab4946d32ab4f788e505504a2ccd7c87bb97b79a24a87f132a6 | ['44930103aa2a40f7a124386fc7e9ce44'] | When you are switching pages the data about sorting is lost, because you are reloading site with different parameters. You can either try to pass this data (the column you are going to sort, and info is it asc or desc) to the new page, and sort it before loading, or paginate it using AJAX (but that means loading everything at the first load). I can't tell about the "pagination does not work problem", because I don't know what you mean.
In general, this thing you are trying to do is rather complicated, and there is no simple solution for that. There is a library for JS called Datatables that (in theory) makes it easier. There is another library called jQ-Bootgrid, and a ruby gem called "Smart listing".
| 5185038ab3c4aacce0a989f8162a5eab6837abf2651270267dc5afb768f3ddce | ['44930103aa2a40f7a124386fc7e9ce44'] | I think you can do something like this:
<%= f.submit "update Details",name: "update_details", value: true, class: "x-update" %>
<%= f.submit 'Next Template', name: "next_template", value: true, class: "x-next" %>
Optionally, I think you can use same names, and different values.
<%= f.submit "update Details",name: "next_template", value: false, class: "x-update" %>
<%= f.submit 'Next Template', name: "next_template", value: true, class: "x-next" %>
And in the controller:
if params[:next_template]
something
else
something_else
end
|
8ac6d210e4f9a2e22de09b5e478374c031adafcdf7deeb39d5f2cfe09dc1c695 | ['44b20027fc474362a9359d1af8eb1f15'] | I have the Hamburger/Menu icon in the top left corner of the app in the Action Bar. I know that the normal action bar items (which are on the right) have specific rules about size and opacity (like 60 or 80% opacity, etc). Do those same rules apply to the hamburger icon on the right?
| db2af1ca500065e5daabe00a764edb6b7a51f1cddf6305d2b7b79a3e2d8404d0 | ['44b20027fc474362a9359d1af8eb1f15'] | I have been using my Windows 10 system for about half a day now following the Creators Update install. I have been getting the following sound being played randomly:
Windows Critical Stop.wav
I don't know the source, as there is no associated messagebox or notice anywhere.
How can I go about tracing this annoying problem?
|
b117454761eb05c1f62246d478ef339e8c31359199bf4ec5c4240d5cdc46d9d4 | ['44bcddb1dfcb4d208933186652985a72'] | I know this is a method, but i'd like to use only css if possible. I've posted it as answer so maybe others having this problem might consider this a temporary solution.
var maxWidth = $('.bigParent').width(),
childWidth = $('.child').width(),
nrOfChildren = Math.floor(maxWidth/childWidth),
parentWidth = nrOfChildren*(childWidth);
$('.parent').width(parentWidth);
http://jsfiddle.net/te9fzaub/6/
Still waiting for a CSS method anyway.
| 67df45e9ec51e79f384119132d9ad8ba4fdb57d2dfe2f342732108002098c4be | ['44bcddb1dfcb4d208933186652985a72'] | So basically i want to html() a php file but i seem to fail, maybe it isn't possible but i want to make sure.
This is an example code (not the real one):
page.php:
<? //some code generating html ?>
<div class='content'></div>
<script type='text/javascript'>
$('.content').html("<? include('php/content.php'); ?>");
</script>
php/content.php:
<div class='realContent'>Awesome Stuff Here</div>
Note: I know there is .load(), $.post and many others. I just want to know if this practic is possible, .html()-ing a php file's contents.
Thank you in advance, awesome community!
|
57cc3d199d72928d88cf792335019d159e37d3a55465486dcd015639ac9e5a9e | ['44ca67093e6e423fb14b33587ccb9b84'] | It's not clear for me what is the proper way to remove a branch from a custom model class derived from QAbstractItemModel. I have a method that should refresh a tree node (remove all subbranches and insert the new ones).
void SessionTreeModel<IP_ADDRESS>refresh(const QModelIndex &index, const DbObjectI *object)
{
auto item = getItem(index);
assert(item != nullptr);
if (item != nullptr)
{
if (item->childCount() > 0)
{
beginRemoveRows(index, 0, item->childCount() - 1);
item->removeAll();
endRemoveRows();
}
if (object != nullptr && object->getChildCount() > 0)
{
beginInsertRows(index, 0, static_cast<int>(object->getChildCount()) - 1);
item->appendChildren(object);
endInsertRows();
}
}
}
void SessionTreeItem<IP_ADDRESS>removeAll()
{
for (auto& child : childItems_)
{
child->removeAll();
}
childItems_.clear();
}
The problem is that the app often crashes after a few refreshes when 'beginRemoveRows()' is called and according to the call stack the problem is that the SessionTreeModel<IP_ADDRESS>parent() is called with an index which holds a dangling internal pointer.
QModelIndex SessionTreeModel<IP_ADDRESS>parent(const QModelIndex &child) const
{
if (child.isValid())
{
auto childItem = getItem(child);
auto parentItem = childItem->parent();
if (parentItem != nullptr &&
parentItem != rootObject_.get())
{
return createIndex(static_cast<int>(parentItem->childCount()),
0, parentItem);
}
}
return QModelIndex{};
}
It looks like the tree view is holding an index for an item that is already removed and is trying to get its parent.
Could you please advise what could be wrong?
| 872ffdc1e760afee6215f7e56b269a8bea11946edda7ac5d16c97b89cd5e86cd | ['44ca67093e6e423fb14b33587ccb9b84'] | First of all, I would like to say thanks to <PERSON> for his comment. I'm glad I didn't have to go in this direction ;)
After hours spent digging into my code, I finally found the issue. A stupid one indeed! In the parent() method the index is created using parentItem->childCount() instead of parentItem->row().
|
7e60fc6a6747e5cb94680c1a7ce822214bf88a040912f07e812b1489e327171d | ['44d16f0c8b6e49c6bb08ae1b764f65b8'] | After numerous trials and errors, I was able to figure this out. Hopefully, it will help someone. Here's how it works: You need to have an iterator or an external source (file/database table) to generate dags/task dynamically through a template. You can keep the dag and task names static, just assign them ids dynamically in order to differentiate one dag from the other. You put this python script in the dags folder. When you start the airflow scheduler, it runs through this script on every heartbeat and writes the DAGs to the dag table in the database. If a dag (unique dag id) has already been written, it will simply skip it. The scheduler also look at the schedule of individual DAGs to determine which one is ready for execution. If a DAG is ready for execution, it executes it and updates its status.
Here's a sample code:
from airflow.operators import PythonOperator
from airflow.operators import BashOperator
from airflow.models import DAG
from datetime import datetime, timedelta
import sys
import time
dagid = 'DA' + str(int(time.time()))
taskid = 'TA' + str(int(time.time()))
input_file = '/home/directory/airflow/textfile_for_dagids_and_schedule'
def my_sleeping_function(random_base):
'''This is a function that will run within the DAG execution'''
time.sleep(random_base)
def_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime.now(), 'email_on_failure': False,
'retries': 1, 'retry_delay': timedelta(minutes=2)
}
with open(input_file,'r') as f:
for line in f:
args = line.strip().split(',')
if len(args) < 6:
continue
dagid = 'DAA' + args[0]
taskid = 'TAA' + args[0]
yyyy = int(args[1])
mm = int(args[2])
dd = int(args[3])
hh = int(args[4])
mins = int(args[5])
ss = int(args[6])
dag = DAG(
dag_id=dagid, default_args=def_args,
schedule_interval='@once', start_date=datetime(yyyy,mm,dd,hh,mins,ss)
)
myBashTask = BashOperator(
task_id=taskid,
bash_command='python /home/directory/airflow/sendemail.py',
dag=dag)
task2id = taskid + '-X'
task_sleep = PythonOperator(
task_id=task2id,
python_callable=my_sleeping_function,
op_kwargs={'random_base': 10},
dag=dag)
task_sleep.set_upstream(myBashTask)
f.close()
| 8853cc8e6e9f01f2e79e2100d089b2ed575906754c787640db22ccb647c5f771 | ['44d16f0c8b6e49c6bb08ae1b764f65b8'] | This one did the trick for me. I had other errors before hitting this one on Ubuntu machine. Let me share that in case someone else runs into them. I was getting
NOQUEUE: SYSERR(www-data): can not chdir(/var/spool/mqueue-client/): Permission denied.
usermod -a -G smmsp www-data
chmod 770 /var/spool/mqueue-client (don't use 775, it gives dangerous permission error in the log)
service apache2 restart (this is required for the above to take effect)
Now sending email gives a different error.
- NOQUEUE: SYSERR(www-data): can not write to queue directory /var/spool/mqueue-client/
- chmod 4555 /usr/sbin/sendmail
- Above command fixed the email issue. => didn't see any error in the mail.log this time.
|
dda6481eef1a0fd8a2294e3df8866e5387e2c2bcb8fac0e0af0f5767c8a54cd1 | ['44eb0f20dff9497bb09b790764ddcc07'] | There are two potential problems:
First, docker:dind requires privileged mode
Second, since version 19.03 docker:dind listens on TLS socket only by default (port 2376).
/ # netstat -ntpul
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 <IP_ADDRESS>:2376 <IP_ADDRESS>:* LISTEN 1/dockerd
So you can choose using TLS authentication and somehow pass certificate to inside a client container, or disable TLS doing something similar to:
tests-website:
stage: test
variables:
DOCKER_TLS_CERTDIR: ""
before_script:
- apk update
- apk upgrade
...
Then it degrades to plain TCP (port 2375)
/ # netstat -ntpul
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 <IP_ADDRESS>:2375 <IP_ADDRESS>:* LISTEN 1/dockerd
What makes me curious, if you are not using kubernetes or something similar to run your jobs (plain docker I mean) then why not just use shell runner and talk to docker through the unix socket available on that machine? If it is not an option, then you can just pass machine's docker socket to inside a client container using mounts, rather than starting an additional instance of docker server
| a63bd96a0c5c71c89ca9de60d4e2a54950793439e1b425c350d0dfff8568f4d9 | ['44eb0f20dff9497bb09b790764ddcc07'] | I can see two possible issues here:
First of all, security groups can be assigned to EKS control plane only during creation. To add additional security groups you unfortunately have to re-create your cluster
Second, the above won't help you, as this is only about the control plane. If you need to add more security groups to your worker nodes, you need to make modification on "compute" tab using launch templates
|
e480226aabafb3ee122d37b022683619f58232b8e59fd76e8b3104e1f86e4298 | ['44f49e906fce4b728a164b45b4db21f1'] | As a suggestion why don't you look at the documentation about your adapter and see what the supported output is, and then load this applet and see if that resolution is supported?
I for one got stuck on the driver support when I first fooled with Ubuntu, the native driver under analysis probably runs smoother, this will verify what resolutions are supported
https://apps.ubuntu.com/cat/applications/natty/resapplet/
Do a google search:
NVIDIA Optimus Hints At Better Support To Linux After Linus’ Middle Finger
| 03a66ca9fff90c96f6bc9a7271427845b7859b0e386278a979d05d687991a9f6 | ['44f49e906fce4b728a164b45b4db21f1'] | I'm not sure I understand your reasoning. We don't want imputed values to affect the center and scale of the data set. So wouldn't it be easier to ignore the missing values before they are replaced with valid values? It seems to me that imputation should follow enumeration of categorical features, standardization (of mean and variance) and vectorization (where relevant), and precede censoring, binning, and other numerical transformations. What do you think? |
33d73cf471bf7c887afd598508b6506d93f433a5a467649b3debe239cba8ea06 | ['44feb4cad0ba406ba20ce12962eaf274'] | I have an issue with multiple AJAX requests modifying a form within drupal 8.
Let me explain - I have been trying to build a quiz module within drupal, and decided to use a widget to create a variable amount of quiz questions, within this question widget is a list of possible answers.
I have created an AJAX button within my question widget which allows answers to be removed and it works the first time it is submitted, but for some reason the second time I run the ajax call the form is reset (like no changes have been made, and no answers have been removed). I have debugged the form array after I have unset an answer, aswell as when the ajax callback is run the second time.
The ajax-enabled button uses the default ajax replace method and I have tried different methods of returning the form (minus an answer) within my AJAX callback including simply unsetting the selected form element and returning the form, aswell as using the AjaxResponse and HtmlCommand classes. I have also tried to rebuild both the form, via formbuilder, and form_state with no joy.
Also each button and answer have unique names/id's.
Here is my widget code (including the button definition):
<?php
/**
* @file
* Contains \Drupal\pp_quiz\Plugin\Field\FieldWidget\QuestionWidget.
*/
namespace Drupal\pp_quiz\Plugin\Field\FieldWidget;
use Drupal\pp_quiz\Controller\QuizController;
use Drupal\pp_quiz\Ajax\AjaxHandler;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'question_widget' widget
*
* @FieldWidget(
* id = "question_widget",
* label = @Translation("Quiz question widget"),
* field_types = {
* "quizquestion_type",
* },
* )
*/
class QuestionWidget extends WidgetBase
{
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$ajaxhandler = new AjaxHandler();
$input = $form_state->getUserInput();
//grab answer count from element array (using delta index)
$question = $items->get($delta)->getValue();
$answercount = count(unserialize($question['answer']));
$element['question'] = array(
'#type'=>'text_format',
'#format' => 'normal',
'#title' => gettext('Question'),
'#description' => gettext("The Question Text"),
'#required' => TRUE,
'#element_validate' => array(
array(
'\Drupal\pp_quiz\Controller\QuizController',
'validateQuestion'
),
),
);
$element['answers_description'] = array('#markup' => 'Create answers below and select which are correct by checking boxes');
$tableheader = array(
'answer' => array('data' => t('Answer'), 'field' => 'answer'),
);
for ($i=0; $i<$answercount; $i++) {
$name = "{$delta}answer{$i}";
$options[$name] = array(
'answer' => array(
'data' => array(
'#type'=>'textfield',
//fix for losing answers on addmore button
'#value'=>isset($input[$name]) ? $input[$name] : '',
'#name' => $name,
'#required' => TRUE,
),
),
);
}
$element['answers'] = array(
'#type'=>'tableselect',
'#header' => $tableheader,
'#options' => $options,
);
$element['removeanswer'] = array(
'#type' => 'submit',
'#value' => t('Remove Answer'),
'#name' => "{$delta}removeanswer",
'#questionno' => $delta,
'#attributes' => array(
'class' => array('removeanswer')
),
'#ajax' => array(
'callback' => array(
$ajaxhandler,
'removeAnswerAjax',
),
'wrapper' => 'edit-field-quiz-questions-wrapper',
),
);
$element = array(
'#type' => 'question',
) + $element;
return $element;
}
}
As you can see above, my 'removeanswer' submit button element has an ajax callback to a function called 'removeAnswerAjax' on the class 'AjaxHandler'. Below is the code for this callback:
<?php
/**
* @file
* Contains \Drupal\pp_quiz\Ajax\AjaxHandler.
*/
namespace Drupal\pp_quiz\Ajax;
use \Drupal\pp_quiz\Controller\QuizController;
use \Drupal\pp_quiz\Entities\QuizResults;
use \Drupal\Core\Form\FormStateInterface;
use \Drupal\Core\Ajax\AjaxResponse;
use \Drupal\Core\Ajax\HtmlCommand;
class AjaxHandler {
public function removeAnswerAjax(&$form, FormStateInterface $form_state) {
$questionno = $form_state->getTriggeringElement()['#questionno'];
$response = new AjaxResponse();
//find selected answer for question number (questionno)
foreach($form['field_quiz_questions']['widget'][$questionno]['answers']['#value'] as $answer_key=>$answer) {
unset($form['field_quiz_questions']['widget'][$questionno]['answers']['#options'][$answer]);
unset($form['field_quiz_questions']['widget'][$questionno]['answers']['#default_value'][$answer]);
unset($form['field_quiz_questions']['widget'][$questionno]['answers'][$answer]);
}
$response->addCommand(new HtmlCommand('#edit-field-quiz-questions-wrapper', $form['field_quiz_questions']['widget']));
$form_state->setRebuild();
return $response;
}
}
If anyone could shed any light on why the form is being reset before it is passed as an argument to my ajax callback, I would love you forever :-)
Thanks for reading.
| c691de14951d4f2f085f3cff1b5f34f8ecf2b50bae248a8dc9c2e7cea09ea9cf | ['44feb4cad0ba406ba20ce12962eaf274'] | I am trying to improve upon the wordpress to drupal 8 migration module (https://github.com/amitgoyal/d8_migrate_wordpress) and add functionality to import taxonomy terms.
I have written the queries to join taxonomy terms to posts, but am having trouble assigning multiple terms to a field (called tags, which is an entity reference to taxonomy terms) of my drupal content type article.
I have created a manifest file for mapping to my article content type:
id: posts
label: Wordpress Posts
migration_groups:
- Wordpress
source:
plugin: posts
destination:
plugin: entity:node
process:
nid: id
vid: id
type: type
langcode:
plugin: default_value
default_value: "und"
title: post_title
uid: post_author
status:
plugin: default_value
default_value: 1
body/value: post_content
body/format: normal
field_image/target_id: post_image
field_tags/target_id: terms
In my posts.php file, which handles all the fetching and processing of wordpress data, I have a function (prepareTerms), which sets the property 'terms', which is used by the yaml file above. If I set this to a single value then the everything works as expected:
$terms = '4';
$row->setSourceProperty('terms', $terms);
However, I want to set this property as an array (for multiple taxonomy terms), like below:
$results = $query->execute()->fetchAll();
$terms = array();
foreach($results as $term) {
$terms[] = $term['term_id'];
}
//$terms = Yaml<IP_ADDRESS>dump($terms);
$row->setSourceProperty('terms', $terms);
As each taxonomy term should be a number (term ID), I should be just passing it an array of integers, but I cannot seem to map this to 'field_tags'. I have tried using Yaml<IP_ADDRESS>dump before setting the 'terms' property in posts.php. I have also tried the changing the yaml template to hardcode these, like below:
field_tags/target_id: [1, 2]
field_tags/target_id: {0:1, 1:2}
field_tags: {target_id: 1, target_id:2}
Linked is a screenshot of a dummy node I created where I have assigned two taxonomy terms (loaded through devel) - http://imgur.com/nkqQoNG
Any help stronger appreciated!
|
448f41d3cd4aad0b6228c2d54018fcc40a9b21dc9e457f904382165224f4914e | ['4505841146cc4b91907e283137e3a9fb'] | When i save a DateTime schedule_time to the DB, it saves according to my local time, but the timestamps (created_at) are saved apparently in UTC (7 hours ahead of my pacific time)
So if i submit the form setting my schedule_time for right now it will be 7 hours different than my created_at.
i need to show many users their times in their own selected zone, and i also need to compare times against each other, so i want all db entries to be in the same zone. Testing on my machine, my user has his zone saved as Pacific (-7:00), but its saving schedule_time in local time, not really UTC, so when i try to display the time back like this:
@item.schedule_time.in_time_zone(@user.time_zone)
it actually takes the stored datetime and subtracts seven hours from it giving me 7 hours before i wanted. i think the best thing is to just store all the datetimes in a uniform way so i can compare them easily.
changing this value config.time_zone = 'UTC' does nothing to change the stored format of my datetime. it stores in my local time regardless, while storing the timepstamps in real UTC.
ive also tried to reformat the datetime before storing it, with in_time_zone(@user.time_zone) but it had no effect on the stored time.
if i can just get schedule_time stored in UTC just like my timestamps are stored i could make this work! any ideas?
| ed604b2f81409b3c4bdef648f9de3c675af1f3ee9992835b9153b912a2d49514 | ['4505841146cc4b91907e283137e3a9fb'] | im loading images into my Fabric.js canvas using Image.fromURL like so:
fabric.Image.fromURL(url, function(img) {
//blah blah blah
canvas.add(img).setActiveObject(img);
});
it works, but some images take a few seconds to load and the user has to sit there with no feedback. i want to put in a loading animation but i cant find any events i can use to tell me when the image is finished loading and ready to display.
anyone have a solution? thanks!
|
b97e3b90def75ac58f754a435aa0614d581a535785beac426e6c28d01262cd0e | ['45072b11c7b74160876e11501048c9a6'] | If you are looking for APIs you are probably most interested in libvirt for simple ESX style api for interfacing LOCALLY with the virtualization hypervisor on your system.
libvirt works with qemu, kvm, and xen and probably more.
http://libvirt.org/
redhat has traditionally had better virtualization support in its enterprise offerings. but fedora is not that. I'd suggest ubuntu oneiric.
If you are looking for a REST API to talk to a large number of virtualization servers... ala vsphere. I'd suggest looking at openstack.
http://www.openstack.org/
http://www.devstack.org/
http://www.trystack.org/
| bc33554845bdaeee7e2661a9ef336d288253192b1fdfc4f007cc0d70cb63a346 | ['45072b11c7b74160876e11501048c9a6'] | Well there is an SDK page listing many of the OpenStack API client SDKs that exist.
Ref:
https://wiki.openstack.org/wiki/SDKs#PHP
Listed in there are two PHP SDKs for OpenStack currently:
Ref:
https://github.com/rackspace/php-opencloud
https://github.com/zendframework/ZendService_OpenStack
I wouldn't use Juju as an interface. And frankly I am not sure OpenStack is the right tool for what you are doing. But, if you want to play with devstack and get an idea, I think rackspace's php client SDK is probably a good start. Devstack is not a bad way to get that experience either.
example of spinning up a server with php-opencloud:
$server = $compute->server();
try {
$response = $server->create(array(
'name' => 'My lovely server',
'image' => $ubuntu,
'flavor' => $twoGbFlavor
));
} catch (\Guzzle\Http\Exception\BadResponseException $e) {
// No! Something failed. Let's find out:
$responseBody = (string) $e->getResponse()->getBody();
$statusCode = $e->getResponse()->getStatusCode();
$headers = $e->getResponse()->getHeaderLines();
echo sprintf("Status: %s\nBody: %s\nHeaders: %s", $statusCode, $responseBody, implode(', ', $headers));
}
This would be a polling function:
use OpenCloud\Compute\Constants\ServerState;
$callback = function($server) {
if (!empty($server->error)) {
var_dump($server->error);
exit;
} else {
echo sprintf(
"Waiting on %s/%-12s %4s%%",
$server->name(),
$server->status(),
isset($server->progress) ? $server->progress : 0
);
}
};
$server->waitFor(ServerState<IP_ADDRESS>ACTIVE, 600, $callback);
|
968db96a068386e1f309e8dec9cf3fca917e3269cd01798bcabbcaa5aa81c94a | ['450a946d6e414147945cc658433343ad'] | We had a meeting with Apple last year about the exact same question, regarding a big banking app that the bank wanted approved before release. The clear answer was that Apple does not provide any testing services. They advise, as you'd expect, for you do your own QA testing, or hire a professional testing company.
Then when the app is ready for sale, make sure you read the the App review guidelines as edc1591 suggested, make sure your app conforms to the guidelines, and only then submitted.
| 513f77a9d5689367d8b79f0dd985751374fcc4e2da25bb825bc97167d481bb70 | ['450a946d6e414147945cc658433343ad'] | Finally got it working. The solution was in the steps below:
First I renamed tui.c to tui.cpp
For the header tui.h, I followed the exact same step of wrapping the code as described here.
then in my project i just included the header without any extern "C" block
#include "tui.h"
Compiled and it worked!
|
04350388d0f999d200db2cf9728a6972702460c3891c5c2e88afc1de83052bf4 | ['4520021e34a44216834e0d9353d8263c'] | I was using pgr_nodeNetwork() to generate a new routable network. http://docs.pgrouting.org/2.0/en/src/common/doc/functions/node_network.html. I found that the old_id (cooresponding to the osm id in the old table) in the new table uses integer as its datatype (see following), the docs says the data type for old_id is bigint though. any ideas to fix it?
| fdcc6522f46b8221b59eeb67bed4538f3e45767c8bc37f21096a881ec1d718ad | ['4520021e34a44216834e0d9353d8263c'] | Question:
"Express the number of ways that an integer $n$ can be written as a sum of a cube of an integer $s\ge-1$ plus the fourth power of an integer $t$ plus the square of an odd integer $r$ as a certain coefficient in an appropriate generating series."
So trying to simplify this convoluted question I arrive at:
Express the number of ways that an integer $n$ can be written as a sum of $s^3+t^4+r^2$ where$ -1\lt s \lt Z,t\in Z,r\in Zodd$ as a certain coefficient in an appropriate generating series. (where $Z$ is all integers).
So I believe that the sum would be something similar to
$$\sum_{n=0}^\infty c_n(s^3+t^4+r^2)\ . $$
I think that what it's asking me to do after this is determine the coefficient $c_n$ so that it is the number of combinations of $s,j,r$ so that $(s^3+t^4+r^2) = n$. I'm not sure how to go about this, if I'm even on the right track, or how the constraints on $s,j,r$ would come into play.
Any help would be much appreciated, thank you.
|
7d91c027f293d6b9f039d5d1811a4431183bd902b964a3675513df3d7bac6d11 | ['452ea7a142894fc7bff39f17be921440'] | You have already given the layout_width = "0dp" and layout_weight="1". So, when other two buttons will hide. This home button will take full width. But View.INVISIBLE won't remove them from taking width. You should use View.GONE so that even if they are not visible, they shouldn't take width.
INVISIBLE:
This view is invisible, but it still takes up space for layout purposes.
GONE:
This view is invisible, and it doesn't take any space for layout purposes.
You don't need to set Layout Params again on Home TextView.
| d9f87fb83272ed03a240d20312bf48226f2caa8c2ecc50529bc99e4fb62ffd65 | ['452ea7a142894fc7bff39f17be921440'] | In your json response, there is no GetAdResult object which you are actually referring to. With the above code, "GetAdResult" should come in response and it should be root element.
Just remove "GetAdResult" because it is not there as root element.
Try with -> JSONObject GetAdResult = jObj.getJSONObject();
It will give you json object and then you can get all the string elements.
|
825ad64f77bfea7b3424c55d2668baa276115d5aa493157f25ae6a95bed16879 | ['452f360831b64e14ab773f3977604af5'] | you could try use Timeout to set a timer to execute a funciton
var myVar = setTimeout(myTimer, 3000);//starting the timer at the end of time it will end execute timer
function myTimer(time,limit) {//the action after the time has set
}
you could use Interval to display a counter
var myVar = setInterval(myTimer, 1000);
function myTimer() {//shwing the timer
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
more info about interval https://www.w3schools.com/jsref/met_win_setinterval.asp
more info on timeout https://www.w3schools.com/jsref/met_win_settimeout.asp
| d5bbb814093d22b1106bfa401ff587a61d57adf05947ae8aaf4d7eb40dd417bb | ['452f360831b64e14ab773f3977604af5'] | for my final project, I'm doing a simple Manager app for Car repairment Garages, for DB I'm using MongoDB and I saw a great tutorial by <PERSON>, but I don't know how to generate an Unice Id for each object.
this is my class Actions for each object in the Database
public class MongoActions
{
private static Random random;
public static void UpsertRecord<T>(int id, string table, T record)
{
var collection = Mongo.db.GetCollection<T>(table);
var result = collection.ReplaceOne(
new BsonDocument("_id", id),
record,
new UpdateOptions { IsUpsert = true }
);
}
public static int RandomId<T>(string table)
{
**//how to find a nice Id that is not repeated**
}
public static void InsertRecord<T>(string table, T record)
{
var collection = Mongo.db.GetCollection<T>(table);
collection.InsertOne(record);
}
public static T FindRecord<T>(string table, string field, string value)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq(field, value);
return collection.Find(fillter).First();
}
public static List<T> FillterRecords<T>(string table, string field, string value)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq(field, value);
return collection.Find(fillter).ToList();
}
public static List<T> LoadRecords<T>(string table)
{
var collection = Mongo.db.GetCollection<T>(table);
return collection.Find(new BsonDocument()).ToList();
}
public static void DeleteRecord<T>(string table,int id)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq("_id", id);
collection.DeleteOne(fillter);
}
}
and this is the connection class
public static class Mongo
{
public static string database = "Garage";
public static MongoClient client=new MongoClient();
public static IMongoDatabase db = client.GetDatabase(database);
}
I will be glad if someone help me
|
d6a30d5a113130c053547d514c53089f36cfcd9a02f243b1806f88b6f3f2f59c | ['4531174d164a4bcba423c8daa9958a18'] | I need to get selected checkbox values from table and pass those values into ajax.Below code I need to pass selected_Device_Mac into ajax. Using inner text i am to get single mac values.i want to check multiple checkboxes and pass each mac values into ajax.How to implement this?
function getDeviceType() {
var selected_Device_Mac = '';
var selected_device_id = '';
($('#query-type').val() === 'single'){
if ($('#PA').is(":visible")) {
console.log("before")
selected_Device_Mac = document.getElementById("macaddr1").innerText;
selected_device_id = '#Selected_Device';
console.log("after")
} else if ($('#MP').is(":visible")) {
selected_Device_Mac = document.getElementById("macaddr2").value;
selected_device_id = '#Selected_Snmp_Device';
}
}
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "getDeviceType",
data: {
mac : selected_Device_Mac,
},
| 8f0842a93ab7a066319aa18317f0d0b6ac64501cafd9431c6303bbf53b098be2 | ['4531174d164a4bcba423c8daa9958a18'] | I need to push values which i am getting from database to multi select.Below code will push data to text area based on onchange in select.I need to change text area to multi select.How to achieve this? Calling below method like
HTML
<select id="select-execution-group-update" class="form-control" onchange="getParamListForCustomGroupUpdate()">
//JS file
function getParamListForCustomGroupUpdate() {
var selected_execution_group = document.getElementById("select-execution-group-update").value;
$.ajax({
method: "GET",
dataType: "text",
url: "getObjectList",
data: {
execution_group_name: selected_execution_group
},
success: function (result) {
result = result.replace(/\\/g, "");
document.getElementById("object_custom_name").value = result;
}
}
);
}
|
a226b9b27fec3260a5b037c01e37d326ccca04ecbae4aea69074a95524d27a1d | ['4549bd951c814723b92f6bb1ebc9a8b1'] | You can use Map.merge(..) to chose the newer record. In the example bellow it is functionally equivalent to Map.put(..), but allows you to compare other Entity attributes, such as a creation timestamp or other.
// Extract Entity<IP_ADDRESS>getId as a Map key, and keep the Entity object as value
Map<Long, Entity> result = first.stream()
.collect(Collectors.toMap(Entity<IP_ADDRESS>getId, Function.identity()));
// Merge second collection into the result map, overwriting existing records
second.forEach(entity -> result.merge(entity.getId(), entity, (oldVal, newVal) -> newVal));
// Print result
result.values().forEach(System.out<IP_ADDRESS>println);
If you want to use Stream API only, then you can concat the two Collections into a single Stream using Stream.concat(...) and then write a custom Collector
Map<Long, Entity> result2 = Stream.concat(first.stream(), second.stream())
.collect(LinkedHashMap<IP_ADDRESS>new, // the placeholder type
(map, entity) -> map.merge(entity.getId(), entity, (oldVal, newVal) -> newVal),
(map1, map2) -> {}); // parallel processing will reorder the concat stream so ignore
| 9877654a76d7ad1cb444bb6f2e979167740da40b279d7e6bab4c625bdc889ded | ['4549bd951c814723b92f6bb1ebc9a8b1'] | I would suggest you use StringUtils.isBlank() from Apache Commons libraries https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
Then you can use a temporary value to store Objects with blank values using
List<String> blank = Stream.of(stringA, stringB,stringC, stringD)
.filter(StringUtils<IP_ADDRESS>isBlank)
.collect(Collectors.toList());
if (blank.size() > 0) {
// your code here
}
I suggest you use multiple if(StringUtils.isBlank(stringX)){} statements if you need to execute different code in each case.
|
a6a179645019a48ff761f20767ab61f88373349d031797bf52a1b41283cc1adc | ['455c3365fcfa4389917079ac42746f68'] | I'm using youtube-dl frequently and have a quite simple file-naming scheme: lower case only and things of the same group are connected with "-" (minus, dash, etc.) while different things are connected with "_" (underscores).
I'm not into regex and therefore, really puzzled if it is possible to configure youtube-dl config-file to store the downloaded clips according to my naming scheme. E.g.:
video:
youtube-dl https://www.youtube.com/watch?v=X8uPIquE5Oo
my youtube-dl config:
--output '~/videos/%(uploader)s_%(upload_date)s_%(title)s.%(ext)s' --restrict-filenames
my output:
Queen_Forever_20111202_Bohemian_Rhapsody_Live_at_Wembley_11-07-1986.mp4
desired output:
queen-forever_20111202_bohemian-rhapsody-live-at-wembley-11-07-1986.mp4
NB: The manual says there are possible python options, but I cannot transfer them to my case.
| 5f8f9518b400038c62204f6c7fc389376f96c011b9d6b87a077bdcacc6f404bc | ['455c3365fcfa4389917079ac42746f68'] | I use e1071 package for SVM multiclass classification on text documents. The usual evaluation of multiclass classification models is made with agreement, precision (micro, macro), recall (micro, macro), f1 (micro, macro), etc.. I would like to get the results from 10-fold cross validations for this evaluations (manually implemented). Is there a posibility to do this?
If yes, can you name the function, functions?
If no, is there any work around?
|
4218c3573fe67870b1738219055fd8131d13feeb6afab3f889a214b4babb744d | ['45644f9c6b20452bbdbafc4e14e80993'] | Please see the simple example below; a text box that is bound to a computed observable. My problem is that IE calls the write method twice when the text box is updated. Firefox and other browsers do not appear to have this problem. I have observed this issue in IE 7 & 8.
First of all, am I doing something wrong? If not, what is the recommended approach to deal with it?
<script>
var viewModel = {
myTestVar: "aaa"
};
viewModel.myTest = ko.computed({
read: function () {
return viewModel.myTestVar;
},
write: function (value) {
alert(value);
viewModel.myTestVar = value;
},
owner: viewModel
});
$(document).ready(function () {
ko.applyBindings(viewModel);
});
</script>
</head>
<body>
<input data-bind="value:myTest",type="text" style="width:150px;" />
</body>
| 236c211b408891e5c3b829d013cebdabd9f7ddc7dc499e256fc88c2572eca5c4 | ['45644f9c6b20452bbdbafc4e14e80993'] | This issue is now finally resolved. I can't say I completely understand this, but this is what I found:
Don't create the Service Fabric Cluster using the Portal. You'll need to use the template so you have access to configure the certs.
Also no need to mess around with Admin Certs on the security tab that I originally did (see original question). Those don't work for this, or at least not the way I'd expect them to.
You must edit the ARM template and add the following certificate information to the "secrets" array on each VM:
Note section above is added and points to a Certificate URL
"settingCertificateUrlValue": {
"value": "https://vault-my-site.vault.azure.net:443/secrets/studiosecrets/487a94749ee148979cc97a68abe9fd3a"
},
The cluster is now "green" and the app runs fine.
|
e1a82858f22c342b224ad63f78176c43b297eb1c7d4c2884da9d81f8721b2ecd | ['4567b96075774b22a03ee35d3f5d8f35'] | Activity A starts Activity B.
I need a way to get Activity B return to Activity A a success/fail code based on the result of some operations, so Activity A can execute some other operations (IE: B is a signup page on some services. A starts B from a button and, after B signs up correctly, sends to A username and password to autologin on that service).
I can't use handler since they're not Parcelable neither Serializable, so I can't put a handler to Activity A in the Extra when I start Activity B. Any other way to make them comunicate?
| f4a90fc752f528caa8a95d6b2d16ed172670f7fcf2ca0d295076748d21d12f1a | ['4567b96075774b22a03ee35d3f5d8f35'] | I have an old project using a custom autoload class to talk with a MySQL database and PHPExcel:
function __autoload($class_name)
{
if (stripos($class_name, 'controller') !== false) {
require_once(System<IP_ADDRESS>getPath('CONTROLLERS') . $class_name . '.class.php');
} else if (stripos($class_name, 'PHPExcel') !== false) {
$path = System<IP_ADDRESS>getPath('EXTERNAL') . str_replace('_', '/', $class_name) . '.php';
if (is_readable($path)) {
require_once $path;
}
} else {
if (stripos($class_name, 'abstract') === false) {
$class_name = str_ireplace('mapper', '', $class_name);
}
require_once(System<IP_ADDRESS>getPath('MODELS') . $class_name . '.class.php');
}
}
Now I want to migrate my project from PHPExcel to Spout ( https://github.com/box/spout/ ) since PHPExcel is too slow when it has to write big files (30000+ cells with custom styles). If i use the suggested way to integrate Spout in my project by adding
require_once System<IP_ADDRESS>getPath('EXTERNAL') . '/Spout/Autoloader/autoload.php';
to my file, PHP can no longer find my classes (the one loaded with autoload). Is there any way I can successfully integrate Spout in my project by keeping my custom __autoload function?
|
10ad1ae342530310895305488777cd69288e5321a2af4fc1cdc7b76f562ab532 | ['4567cc3e0291416794e00d6898d27968'] | The statement is true even in a more general context. Let T be any linear map on a finite dimensional vector space V.
Then $V \supset T(V) \supset T^2(V) \supset T^3(V) \supset \cdots$
Taking the dimension of this sequence we obtain a decreasing sequence of nonnegative integers, which has a lowest value. This means that the sequence of subspaces stabilizes:
$T^{n+1}(V)=T^n(V)$ for some n. In other words, the subspaces $Im T^k$ are all equal for $k \geq n$.
| 2a834e49a5db51079c9cdd795673db36050e376f62df14ac3b5d85880b0a2df3 | ['4567cc3e0291416794e00d6898d27968'] | All Email Accounts will Auto Reply from outlooks default sent folder. You need to Change sent setting from each email to send from the email account it self instead of the default sent folder. Then you can save 2 auto replies for each email account. Just make two different templates and save them with obvious names. Then Apply that rule to that email account.
|
e0ca82eb8f78a3e8d11f4a3bd01dc8c28c814af243754f19957470e0706d361f | ['4567d8bf3b1241eab8bae9a3a41aeebb'] | Not exactly, but something is kinda there to help in such situations. There is a Clipboard History built-in Sublime Text (atleast in 3, not sure 2). Just copy the text you are replacing, then press <C-k><C-v>. This will popup a small window with clipboard's history. Select the previous copied text to replace currently selected text.
This option is available under Edit -> Paste from History.
HTH
| 5744093e846568688f7ccb92c7a96ec72dec75bbc15d690c30e657eff7df2cdb | ['4567d8bf3b1241eab8bae9a3a41aeebb'] | Based on your data:
\d{19}_0+\d_0_(V|E)?_(-?(\d{2}|\d{4}))+_(-?\d{2})+\.db
If seeking more generic:
\d{19}_\d+_\d_[A-Z]?_\d{4}(-\d{2}){2}_(-?\d{2})+\.db
HTH
EDIT: On a side note, I would rather split this string with _, and then validate each section individually based on some pattern and/or property. That way you will have more control over how this string must look.
|
51bd58e49f6e942b1fb026ff266998751d3c91f9ac88aa11eabb12e5885537ad | ['4569165c29cd47028790dc55e7d71cb4'] | Perhaps http://code.google.com/p/as3plist/wiki/Intro is what you're looking for? I haven't tried it, but it came up in the same search as your question.
Edit: I misparsed your question, sounds like you actually have something like this, but it's not working. Still, maybe this will give you a clue as to why your own version's not working.
| 0a3c386aad3821ab141e2cba70abcbd1a60e5a067267a3d70ce5789dc92aae47 | ['4569165c29cd47028790dc55e7d71cb4'] | I know it isn't what you want, but I found that it wasn't too bad to package up the bits of rabbitmq that the rabbitmq-erlang-client needs, plus the rabbitmq-erlang-client, into a Debian packages, and get that working pretty easily.
I have a build-dep on rabbitmq-server though, so it's not the cleanest solution. And it never went into production.
I didn't find an alternative AMQP client for erlang at the time either.
|
c37cae6721dc88315937e5bff7a97bc101b4002e787d74170c2528efcf54fd10 | ['457978ad24ed4c61bc01f0ad4fd2eb51'] | <PERSON> has probably suggested the best and most intuitive solution to make it appear as if the data is being loaded dynamically to the user.
The other alternative would be to submit the form when the select box is changed. Once the form has been submitted PHP would pick up the ID from the POST array and then re-populate the sub-category select box. This is often used as a fallback in case the user doesn't have JavaScript enabled.
| 3fe103a76507128e763b2699f457abdbef395088edb2a9f5a21c81f29449a3dd | ['457978ad24ed4c61bc01f0ad4fd2eb51'] | You're correct, it does speed up development by a substantial amount. The other comparison is 'preference' - Doctrine 2 feels more truly 'object orientated'. It's also important to note that Doctrine 2 uses transactions to execute queries to speed up execution time and although this can be done using PDO as you mentioned previously it requires you to write more code.
I guess it's like having your own PHP libs and using frameworks. It just 'speeds up' the development process and therefore it's an obvious winner with people writing large applications.
|
9fe9d5f7250f11d7ec70174d7310da9e286ab1e3505b30d91d9c905e6ec445dd | ['4586aac7c73346998397e4fe3fe6db27'] | I am getting a null returned by SimpleDateFormat. But I feel I have done everything correctly.
Below is my code snippet
format = new SimpleDateFormat("yyyy-dd-MM'T'H:mm:ss'Z'", Locale.US);
format.setLenient(true);
ParsePosition pos = new ParsePosition(0);
String timeStr = "2013-10-05T01:21:07Z";
System.out.println(format.format(new Date()));
System.out.println(timeStr);
Date d = format.parse(timeStr,pos);
d.getTime();
Gives the output
2014-30-05T13:43:05Z
2013-10-05T01:21:07Z
Exception in thread "main" java.lang.NullPointerException
I have tried a couple of options mentioned in other posts in this forum. But I am still getting the error. Am I overlooking something trivial?
| 578074fa547478d81e439b2ee57685f1e88837c348efd81be88baa54f8c60b68 | ['4586aac7c73346998397e4fe3fe6db27'] | This is something like mix of groovy and Java. I created the code as part of learning.
===================================================================
@Entity
public class GroovyBoy implements SimpleEntity {
@Id
@GeneratedValue
private long Id;
private String name;
@OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
private List<GroovyBro> brothers;
@Override
public Long getId() {
return Id;
}
@Override
public void setId(Long id) {
Id = id;
}
}
===================================================================
@Entity
class GroovyBro implements SimpleEntity {
@Id
@GeneratedValue
private long Id;
private String name;
@ManyToOne(fetch=FetchType.EAGER)
private GroovyBoy brother;
@Override
public Long getId() {
return Id;
}
@Override
public void setId(Long id) {
Id = id
}
}
===================================================================
def <PERSON> = (MyDaoImpl) appContext.getBean("dao")
def <PERSON> = new GroovyBoy()
boy.name='boy1'
def <PERSON> = new GroovyBro()
bro1.name='bro1'
def <PERSON> = new GroovyBro()
bro2.name='bro2'
boy.brothers = [bro1, bro2]
dao.save(boy)
//dao.evict(boy)
println 'Id: ' + boy.brothers[0].id
def <PERSON> = new GroovyBro();
loadBro.id = boy.brothers[0].id
GroovyBro bro = (GroovyBro) dao.get(loadBro)
println 'Bro: ' + bro.brother
===================================================================
The last line is returning null. But when I fetch the GroovyBoy entity, it loads the persistent bag and then loads the GroovyBro instances.
Why is the GroovyBoy instance not loaded?
Thanks in advance.
|
05a4cb576bd433e886953ad8e426705ab9be6814ff2c41c773bc39c613c13588 | ['45890295951f400982a313bcebd51770'] | I researched a lot of time in google this theme but my split action bar still without dividers. I try to use options
<item name="android:showDividers">beginning</item>
<item name="android:dividerHeight">1dp</item>
<item name="android:divider">@color/grey</item>
or
<item name="android:actionBarDivider">@android:drawable/my_divider</item>
to app theme or actionBar style.
On developers i found nothing too.
How can i add divider?
| e19ffdc96adbe29ec5e92f0385bd8935fbb27292a8fc677edc3bb111dba8a7b5 | ['45890295951f400982a313bcebd51770'] | good links, QArea. Thanks a lot!
At this moment NDK support in Gradle are very limited. If you need to assemble something that gradle not provides that function
I do like this.
I collect the old-fashioned, but to .so-patches automatically picks up the Gradle-plugin:
ndk-build -j4 NDK_LIBS_OUT=src/main/jniLibs
Otherwise, you must wait for next version of gradle 0.13. Devs promise that NDK will fix integration with NDK.
|
1f83bd6c134db94adc4f1498253f3b04a5e3036c193a7ce339f707b2c2869ce9 | ['459000df510040f3adf5456e9a171b96'] | I had trouble with understand the relationship between model frame and world frame.
If
P is the perspective projection matrix (transform from view frame to clip coordinates)
V is the view matrix (transform from world to view frame)
M is the model matrix (transform from model to world frame, may include non-uniform scale)
s_w is a light source location point (in the world frame)
p_m is a point on the model surface (in the model frame)
n_m is the unit surface normal vector at (in the model frame)
What are the best answer for following?
a. The final projected location of p_m in clip coordinates
b. The vector in the view frame from the transformed p_m toward the transformed light source
c. The vector in the view frame from the transformed p_m towards the center of projection
d. The normal vector n_m in view coordinates (before normalization)
For a matrix A, the transpose is indicated by A^T, and the inverse by A^-1.
Choose from one of them below:
1. V (M^-1)^T n_m
2. (0,0,0,1) - (V M p_m)
3. s_w - (M p_m)
4. V M n_m
5. P M V p_m
6. V M^-1 n_m
7. (V s_w) - (V M p_m)
8. (0,0,0,1) - p_m
9. s_w - p_m
10. (P V s_w) - (P V M p_m)
11. V M^T n_m
12. V - p_m
13. p_m P V M
14. M V P p_m
15. P V M p_m
16. (0,0,0,0) - (V M p_m)
| 443abd45af03f396fff779352f34c2b50f9b0fb254bdd3943d18c3201bfec238 | ['459000df510040f3adf5456e9a171b96'] | I have two Racket programming homework questions:
The first one: Write a function kth-item that takes two arguments, the first is a stream s and the second is a number k, and it produces the result of extracting k elements from the stream, returning only the last element. Very similar to the previous one, but only returns a single element. You may assume k is greater than 0.
The second one: Write a stream negate-2-and-5 that is like the stream of natural numbers (i.e., 1, 2, 3, ...) except that numbers divisible by 2 or 5 are negated (i.e., 1, -2, 3, -4, -5, -6, 7, -8, 9, -10, 11, -12, 13, -14, ...). Remember a stream is a thunk that when called produces a pair, where the car of the pair is the next number and the cdr will be the continuation of the stream.
For first questions I know how to get the list of ith but I have not idea how to continues to get the last element.
For second questions, I know how to get either 2 or 5 works, but I have not idea how to combine them, so both 2 and 5 can work at the same time.
(define (next-k-items s k)
(if (<= k 0)
empty
(cons (car (s))
(next-k-items (cdr (s)) (- k 1)))))
(define (negate-2-and-5)
(define (f x) (cons (if (= 0 (remainder x 5)) (- x) x)
(lambda () (f (+ x 1)))))
(f 1))
Here are the testing codes:
(check-expect (kth-item nats 3) 3)
(check-expect (next-k-items negate-2-and-5 7) '(1 -2 3 -4 -5 -6 7))
|
5aaaa1b5a44d8c1c264c1d4cbe1bc24fdccdc086a557457ca6bb6753a3876d81 | ['45909fc0e4564799a5814aa17e00ddc6'] | You don't use [-r|--reset]. You use either -r or --reset. The square brackets indicate that what's inside is optional and the pipe is an "or" operator. So, you'll use:
php ./magento migrate:settings --reset /var/www/html/magento2/vendor/magento/data-migration-tool/etc/ce-to-ce/<IP_ADDRESS>/config.xml
Or:
php ./magento migrate:settings -r /var/www/html/magento2/vendor/magento/data-migration-tool/etc/ce-to-ce/<IP_ADDRESS>/config.xml
| 7d1ea2cb80722b876c8f4206c41821d72e8178ded44b1d3bfe5d487bff00ab21 | ['45909fc0e4564799a5814aa17e00ddc6'] | Could you be more prescise in what you miss about the way disabilities are featured? - Especially, could you point to something that is not featured "as a series of points" but is still integral to the games core? ----- And: could you expand on how a dis-ability, i.e. an ability that is absent, would not be punished mechanically, without that dis-ability disappearing (as in: not make an appearance)? |
2cf8e0615925d8e91b57e4c77039ccfc04b650fb3ded272ae40081734cdd8358 | ['4594ed3a27f4426993ac0da793c1c111'] | Since I am unable to comment on the above answer from <PERSON>, creating a new answer for the follow-up
sudo apt-get update
sudo apt-get install libtool
And try again
sh autogen.sh
If you see the below error
./configure: line 11408: syntax error near unexpected token PKG_CHECK_MODULES'
install pkg-config:
sudo apt-get install pkg-config
sh autogen.sh
./configure && make
This should take care of everything.
| 7cdf5aa71614b4c48737e5f0eff2ad00e067d96ed2dcc876f2c72053b242ba02 | ['4594ed3a27f4426993ac0da793c1c111'] | I want to prove the following :
Let $V$ be an irreducible affine variety in $\mathbb{A}^n$ with $V \not=\mathbb{A}^n $. Then $dimV < n$.
I tried to prove this by contradiction but my proof doesn't work. I thought my choice of $y_i$ was enough to garantee algebraic independence but it isn't. Can someone help me modify my proof ?
This is what I tried so far:
Suppose $dimV \geq n$. Then there exists a strictly increasing chain of irreducible subvarieties of $V$
$$V_0 \varsubsetneq ... \varsubsetneq V_n \subset V \varsubsetneq \mathbb{A}^n$$
and a corresponding decreasing chain of prime ideals in $\mathbb{C}[x_1,...,x_n]$
$$I_0 \varsupsetneq ... \varsupsetneq I_n \supset I \varsupsetneq (0) $$
with $I_i = I(V_i)$ and $I = I(V)$.
Now we choose any $y_n \in I_n \setminus (0)$ and for all the other $I_i$ choose a $y_i \in I_i\setminus (y_n,...,y_{i+1})$. By construction all the $\{y_0,...,y_n\}$ are $n+1$ independent elements of $\mathbb{C}[x_1,...,x_n]$ which is impossible.
|
844bbab5bae223b5e7e43c590181216c2d9dab80efb378dc0ece3d6b97df2196 | ['45b32f6770144b43b471f227671c6c7a'] | I think i misunderstood validation rules, so i answered the following challenge creating a validation rule that only applies if the insertion is different for what i write in the rule:
AND(ISBLANK( Account.Id ),
OR( MailingPostalCode = Account.ShippingPostalCode ))
I mean, if the insertion/update is correct, then do it, else display error message.
The challenge has succeeded.
My question is, am i wrong or i should write in the validation rule the conditions where should'nt be accepted?
Here is the challenge
| 23f60c59d0ea74ce744195ad7be10bf984e329cfb8ed66479c4a2a4be12db6c9 | ['45b32f6770144b43b471f227671c6c7a'] | I know that's a completely newbie question but, i want to navigate to "New user" and i can't because i get an infinite url like
lightning/setup/ManageUsers/page?address=%2F005%2Fe%3FretURL%3D%252F005%253FisUserEntit.....
There is anyway to change it or parse it?
PS: I have a dev account.
|
33b47d10fe44e3c016263bfd27bfe07f38e622592840c7b7b3973c37663cd459 | ['45bb2fb60c6448e2906b9f9d3f3adef6'] | This code work fine:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16sp"
app:passwordToggleEnabled="true"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<android.support.design.widget.TextInputEditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="6"
android:inputType="textPassword"
android:maxLines="1"
android:fontFamily="@font/product_regular"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
android {
compileSdkVersion 28
defaultConfig {
applicationId "com"
minSdkVersion 24
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
buildToolsVersion '28.0.2'
}
implementation 'com.android.support:exifinterface:28.0.0-rc02'
implementation 'com.android.support:support-v4:28.0.0-rc02'
implementation 'com.android.support:support-v13:28.0.0-rc02'
implementation 'com.android.support:design:28.0.0-rc02'
implementation 'com.android.support:cardview-v7:28.0.0-rc02'
implementation 'com.android.support:recyclerview-v7:28.0.0-rc02'
| 1ecebbbcfe91a96c62698a94dddb0164a07af590056379d9a841e9c853c77536 | ['45bb2fb60c6448e2906b9f9d3f3adef6'] | I have a ContentPage with a ViewModel. This view contains a ListView.
On XAML i have
<ListView>
<ListView.ItemTemplate>
<DataTemplate:>
<templates:miItemView/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
On MiItemView i have other contentView with a Label. How can binding text property of this label with a String property of my ViewModel????
My ViewModel:
public class RoutePageViewModel : ViewModelBase
{
#region Views
private List<Citizen> _citizens;
private int _citizensPosition;
#endregion
public List<Citizen> Citizens
{
get { return _citizens; }
set
{
_citizens = value;
RaisePropertyChanged();
}
}
public String CitizensPosition
{
get { return _citizensPosition; }
set
{
_citizensPosition = value;
RaisePropertyChanged();
}
}
my ItemView:
<ContentView.Content>
<Grid
HorizontalOptions="FillAndExpand"
RowSpacing="0"
VerticalOptions="Fill">
<Grid>
<!-- Name -->
<Label
x:Name="myTitle"
FontSize="Large"
Text="{Binding Name}" />
<!-- AGE -->
<Label
FontSize="Small"
Text="{Binding Age}" />
</Grid>
<local:PositionIndicatorView
/>
</Grid>
And PositionView:
<StackLayout>
<Label Style="{StaticResource labelGeneralStyle}" Text="HOW BINDING WITH CitizensPosition />
</StackLayout>
|
c6388e56d605338478269ca3e34660c48ff091e4347c6060550a16a281ef40f7 | ['45bc89318d5648c09499305d660d0238'] | The DateTime difference is correct and the error only comes in when you are formatting the output. %d is the day of the month, not the total days in the DateInterval. These two datetimes are 1 month and 20 days apart. So %d only shows the 20 days part. %a should get you the total number of days.
A full guide to the format can be found here:
http://php.net/manual/en/dateinterval.format.php
| 18c7fcacda320cd97e7dc3ee3c69c5e83df76a895e23587d9162ea6d0e17ee62 | ['45bc89318d5648c09499305d660d0238'] | I think most of the problems come from general confusion about arrays. E.g. the line from the code block run when you press w:
gridArray[randomRow][randomCol] = gridArray[randomRow+1][randomCol];
sets the char value of the array at randomRow, randomCol (in this case an 'x') to the char value of the of the array space one row below it at randomRow+1, randomCol. And then the line of code after that:
gridArray[randomRow][randomCol] = ' ';
assigns a new value to that same space making the code above worthless! And in the end, randomRow and randomCol are never modified. (also you had some confusion about which way the x would move with a higher row value)
all you actually need to do in this code block is:
randomRow -= 1;
after this, you can simply reprint the whole grid with the printing code from before. Although there are other issues with this code that make it far from optimal. Also there are a similar problem in that if statement in the for loop that worked but led to problems later down the road. Simply rewriting it to fix all the things wrong, you get this:
char[][] gridArray = new char[10][10];
int randomRow;
int randomCol;
int randomRow2;
int randomCol2;
String moveSelect;
boolean validInput = true;
int min = 0;
int max = 9;
Random tRNG = new Random();
randomRow = tRNG.nextInt(max - min + 1) + min;
randomCol = tRNG.nextInt(max - min + 1) + min;
randomRow2 = tRNG.nextInt(max - min + 1) + min;
randomCol2 = tRNG.nextInt(max - min + 1) + min;
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (!((i == randomRow && j == randomCol) || (i == randomRow2 && j == randomCol2)))
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
System.out.println("Enter a movement choice W A S or D");
do{
Scanner keyboard = new Scanner(System.in);
moveSelect = keyboard.nextLine();
if ( moveSelect.equals("w"))
{
randomRow -= 1;
validInput = true;
}
else if ( moveSelect.equals("a"))
{
randomCol -= 1;
validInput = true;
}
else if ( moveSelect.equals("s"))
{
randomRow += 1;
validInput = true;
}
else if (moveSelect.equals("d"))
{
randomCol -= 1;
validInput = true;
}
else
{
System.out.println("Invalid Entry. Try again.");
validInput = false;
}
} while (validInput == false);
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (!((i == randomRow && j == randomCol) || (i == randomRow2 && j == randomCol2)))
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
|
0c5b0a33112f88d28c8889d2cbff0961aac5f1bcb5438d6ec1a031bcb42c160a | ['45bd9364c60f4754998075004d059e50'] | Sorry I'm a newbie with CRS
I have a shapefile (points) with coordinates in CRS EPSG:3854 (SRP) so that I can show the points within the open layers plugin.
Now I need to transform those points in EPSG:4326. The points do now have Long/Lat coordinates.
But i want to have them in E: and N:
e.g.
LAT: 53.<PHONE_NUMBER> LONG: 9.288940
equals
E:<PHONE_NUMBER> N: <PHONE_NUMBER>
How can I transform them if I have many (like 100) points? Is there a fast way to do this?
| 405634d931231c2c8b4eb7071d60d2435832dba85e67468172b6571490573750 | ['45bd9364c60f4754998075004d059e50'] | I am using past sales data to predict the next days inventory, but what I actually care about is low inventory. My dependent variables are whatever manipulations of sales I can imagine might be relevant (finite difference, various sums). Someone might have a more creative way of looking at this, but I just want to be able to train a model with a focus on the inventory data 'close' to zero. |
5eb134c9ce899bf5de3786276920b61627770a59b5dff780c18a35caef3e0150 | ['45bf7056ec2e423787fab48fd48434b2'] | I just noticed that when I download html5boilerplate V5.3.0 it comes with
Bootstrap v3.3.1 (but Bootstrap v3.3.7 is available)
normalize.css v3.0.2 (but normalize.css 7.0.0 is available)
modernizr 2.8.3 respond 1.4.2 (but modernizr 3.5 is available)
so why html5boilerplate come with old version of Bootstrap, normalize & modernizr ?
Can I update latest version of all Bootstrap, normalize & modernizr on my own ? will that break any settings of html5boilerplate ? is it safe to update all Bootstrap, normalize & modernizr on my own ?
Again how can I update Bootstrap, normalize & modernizr into html5boilerplate ? any shortcut or something ?
or html5boilerplate is old thing now ? anything new and better then html5boilerplate came in ?
Usefull links :
1. https://html5boilerplate.com/
2. https://necolas.github.io/normalize.css/
3. http://getbootstrap.com/
4. https://modernizr.com/
| 2f47a40c822d4e04f37878b2ff92df7b4e62b274840fceea099f1e2090fba1e7 | ['45bf7056ec2e423787fab48fd48434b2'] | I have downloaded one html theme in which I have seen this code on body tag. now I know little bit about antialiased and grayscale but what is kern ? and what is exactly a use of this all code ? can anyone guide ?
is there any simple common fix for all font issues ? so fonts look same in all the browser
font-synthesis: none;
-webkit-font-feature-settings: 'kern';
font-feature-settings: 'kern';
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
|
695b347ef4d828241241ba5324ffbf98ad3363370842ca595ce43b3fbe2f1130 | ['45e39d6219da4ca08904f9b93ffd94c3'] | I'm just setting up my first BigCommerce store, and I'd like to know if I can use their API to add products to a shopper's cart and forward them to the checkout page programmatically?
The problem I'm trying to solve is creation of bundles of products in the store. I need to have each product in a bundle show up as a separate line item and sku on the order, but BigCommerce does not natively support this. The next best thing I can think of is to send the user to a specially crafted php page that will add the constituent parts to their cart, then forward them to the checkout page.
Am I barking up the wrong tree? Is there a simple way to do this that I've missed?
| 7c7157d9c79b39daa6f3667d3f83a99de4c8c2b5f442bb2320655fda8489f5ef | ['45e39d6219da4ca08904f9b93ffd94c3'] | As is common, I've got a trigger that updates a date_last_modified field in one of my tables. The issue I've run into is sometimes I need to manually adjust the timestamp in that date_last_modified field. When I do, though, the trigger fires and sets it right back to now().
Here is my trigger:
CREATE TRIGGER Preference_on_update After UPDATE ON Preference for each row
begin
update Preference set date_last_modified = datetime('now')
where rowid = old.rowid;
end
What I'd like to do is ONLY have this trigger fire when the update does not already include a value for the date_last_modified field. If the update statement included date_last_modified, the trigger should not adjust anything.
I've looked through the docs and syntax for triggers for SQLite, and see there is a "WHEN" clause, but none of my incantations of it so far have been fruitful.
Can this be done?
|
dbbc04a4e155c60eb5022c1a36992a30eb079a2af7715776b5c7f2680491e920 | ['45e8583dc00d450dad78990e4c093eca'] | I should state that this is not a permutation issue and that I would like to do this in C#. I have a variable number of lists of strings and each list has a variable number of elements.
So for example:
List 1:
One
Two
List 2:
Uno
Dos
Tres
List 3:
1
2
3
4
The results should end up being:
OneUno1
OneUno2
OneUno3
OneUno4
OneDos1
OneDos2
OneDos3
OneDos4
OneTres1
OneTres2
OneTres3
OneTres4
TwoUno1
TwoUno2
TwoUno3
TwoUno4
TwoDos1
TwoDos2
TwoDos3
TwoDos4
TwoTres1
TwoTres2
TwoTres3
TwoTres4
The real issue here is that the final list can get very large very fast so I run into problems if I do this in memory, so my thought is to write the strings out to a file as I generate them but I'm having issues trying to figure out the logic/algorithm for doing this.
| 90ac27e274dc01bae645f2c6aa6bababae1ce8da1f19ddbadc96aeeabeb0dd03 | ['45e8583dc00d450dad78990e4c093eca'] | I'm using the NuGet package of ZeroMQ for Visual Studio. The version I'm using is 3.0.0-rc1.
I've been searching around for quite some time and still haven't been able to find an "elegant" solution to my issue. I am creating a server (ROUTER) socket and then basically waiting on any data to arrive on that socket. I do this by creating a poller and waiting in an infinite loop. My issue is trying to figure out how to break out of the call to Poll() when I am trying to shutdown the application. By the way, the code below is being done in a separate thread and I am passing in my context to the thread in order to create the Socket.
using (ZmqSocket server = cntxt.CreateSocket(ZeroMQ.SocketType.ROUTER))
{
string strSocketAddress = String.Format("tcp://{0}:{1}", strIPAddress, nPort.ToString());
try
{
server.Linger = TimeSpan.FromMilliseconds(1); ;
server.Bind(strSocketAddress);
server.ReceiveReady += server_ReceiveReady;
ZeroMQ.Poller poller = new Poller(new List<ZmqSocket> {server});
while (true)
{
poller.Poll();
}
}
catch (ZmqException zex)
{
server.Disconnect(strSocketAddress);
server.Close();
server.Dispose();
}
}
Everything here works as expected and I do receive the event whenever I receive data on the socket. But when I want to shutdown the app, I can't figure out how I am suppose to break out of the loop. I do understand that I can put a timeout on the poll and put some sort of flag in to say that I'm shutting down but I was hoping there would be a "better" solution than that.
What happens now is that when I am wanting to shut down, I call Terminate on the context but at that point the application hangs and never returns. I am assuming it is hanging because I still have a socket open. I also read that by setting the Linger flag to something really small that the socket should shutdown after the call to Terminate on the context but that isn't happening.
The reason I have the catch clause in is because when I was using version 2.0 and I called Dispose() on the context, I would receive an exception and I could gracefully get rid of the socket, but I'm no longer getting an exception with version 3.0.
So I was wondering if I'm just missing something? And if there is a more "elegant" approach to shutting down a socket that is in it's own thread waiting for messages?
|
10c98339665c9b1a3965f647bafee29e581b47b5dcfb3c320d18c9d8b44fe639 | ['460204621d034a218e250fe6f2bf849b'] | This is how I would do it. Define the role by grabbing it from the first argument in the message's content, and define the member how you did. Check if they exist.
When command is used, the role must be before the @mentioned user.
bot.on("message", message => {
const prefix = '!'; // just an example, change to whatever you want
if (!message.content.startsWith(prefix)) return; // ignores all messages that don't start with the prefix
const args = message.content.slice(prefix.length).trim().split(/ +/g) // creates an array of arguments for each word after the command
const cmd = args.shift().toLowerCase(); // this makes the command cASe iNseNsiTiVE
if (cmd === 'addroll' || cmd === 'ar') { // can use 'addrole', or 'ar' to run command
let roleToAdd = message.guild.roles.find(r => r.name === `${args[0]}`); // grab the role from the first argument
let userToModify = message.mentions.members.first(); // grabs the mentioned user
if (roleToAdd === null) {// if role doesn't exist(aka = null)
return message.reply(`I couldn't find the ${args[0]} role.`);
}
if (userToModify === undefined) {// if noone is mentioned after the role
return message.reply('You must `@mention` a user!');
}
userToModify.addRole(roleToAdd)// add the role
return message.reply(`${userToModify} has been given the ${roleToAdd} role.`)
// more code
}
});
Tried and tested.
| fdcba68172b60707b2be21bb227478cb576d0b049ea7a093ad88305672f73cdf | ['460204621d034a218e250fe6f2bf849b'] | Ugh I'm an idiot...
I just needed to define a blank 'type' variable the same way I did responseTitle and responseMsg....
let type = '';
'type' is made from args given by command user like so:
let responseTitle = '';
if (newArgs.includes("xa")) {
type = "Xanax";
responseTitle = "Xanax used from Armory\n__*" + endDate + "*__ to __*" + startDate + "*__\n"
} else if (newArgs.includes("morph")) {
type = "Morphine";
responseTitle = "Morphine used from Armory\n__*" + endDate + "*__ to __*" + startDate + "*__\n"
} else if (newArgs.includes("bb") || newArgs.includes("blood bag") || newArgs.includes("blood") || newArgs.includes("bag")) {
type = "BloodBag";
responseTitle = "Blood Bags used from Armory\n__*" + endDate + "*__ to __*" + startDate + "*__\n"
} else if (newArgs.includes("re")) {
type = "Refill";
responseTitle = "Blood Bags refilled from Armory\n__*" + endDate + "*__ to __*" + startDate + "*__\n"
} else if (newArgs.includes("sf")) {
type = "SFAK";
responseTitle = "Small First Aid Kits used from Armory\n__*" + endDate + "*__ to __*" + startDate + "*__\n"
} else if (newArgs == "fak") {
type = "FAK";
responseTitle = "First Aid Kits used from Armory\n__*" + endDate + "*__ to __*" + startDate + "*__\n"
}
|
3488ad028a32637f028454690855902c327c4ad7ec4dc4949548535ccccdf067 | ['4605c7f5092e49cbaca9e02294435e15'] | Just experienced the same issue as the OP when publishing an ASP.net 4.5.2 SPA via web deploy in VS2015.
The solution I found to work was to remove the Nuget package "Microsoft.CodeDom.Providers.DotNetCompilerPlatform".
You could, alternatively, simply remove the system.codedom compiler config section from your Web.config file, which would have the same affect.
| ea59ccbb7a555cd0181d0dca3085f925626c0a67ebc2d035ac2d2356bbb8eaf3 | ['4605c7f5092e49cbaca9e02294435e15'] | Encountered the same issue with a ASP.Net Web App and two library class projects which needed to be referenced within the Web App. I had no information provided on why the build failed and the references were invalid.
Solution was to ensure all projects had the same Target Framework:
In Visual Studio 2015- Right Click project > Properties > Application > Target Framework
Save, Clean and Rebuild solution. The project references should no longer appear as yellow warnings and the solution will compile.
My Web App was targeting .Net 4.5 whereas the other two dependent library class projects targeted .Net v4.5.2
|
828266f7a31b624c0e3d64dcfcce25402c980b2cc569d89a6246698d9a530437 | ['4619859e27a64d4e89bd230aa23eb8e9'] | I am trying to cycle through my images to present in one col but seems I can't make it work. Tried different ways but couldn't get help form official docs either.
Would be glad to get solutions from anyone. Following is the code:
<section class="banner-home-bottom container">
<div class="widget-title wow fadeIn">
<fieldset class="box-title lang1">
<legend align="center">#Featured On <PERSON> </legend>
</fieldset>
</div>
{% for object in object_list %}
<div class="row">
<ul class="row">
<li class="col-sm-4 wow fadeInUp" data-wow-delay="100ms">
<a href="#"><img src="{{ object.image.url }}" alt="" /></a>
<div class="des">
<h4 style="color: #000000;font-size: 20px;">
<span class="lang1">{{ object.title }}</span>
</h4>
<p style="color: #2d2d2d;font-size: 12px;">
<span class="lang1">{{ object.description }}.</span>
</p>
<a href="#" title="Shop Now " class="btn lang1">
Shop Now
<span class="arrow">arrow</span>
</a>
</div>
</li>
</ul>
{% cycle "" "" "" "</div><br/><hr/><div class='row'>" %}
</div>
</section>
{% endfor %}
| b88dbbe06689953c634142e0f82c3d9bc4c46aef097d6daf4272ab154f5d12a8 | ['4619859e27a64d4e89bd230aa23eb8e9'] | I've created the cart view but I can't get the cart updated with my products. I tried many ways from stackoverflow examples but none worked. I am adding my whole code for Cart Application.
Following is my Model for Cart app:
class CartItem(models.Model):
cart = models.ForeignKey("Cart")
item = models.ForeignKey(Variation)
quantity = models.PositiveIntegerField(default=1)
line_item_total = models.DecimalField(max_digits=10, decimal_places=2)
def __unicode__(self):
return self.item.title
def remove(self):
return self.item.remove_from_cart()
def cart_item_pre_save_receiver(sender, instance, *args, **kwargs):
qty = instance.quantity
if qty >= 1:
price = instance.item.get_price()
line_item_total = Decimal(qty) * Decimal(price)
instance.line_item_total = line_item_total
pre_save.connect(cart_item_pre_save_receiver, sender=CartItem)
def cart_item_post_save_receiver(sender, instance, *args, **kwargs):
instance.cart.update_subtotal()
post_save.connect(cart_item_post_save_receiver, sender=CartItem)
class Cart(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
items = models.ManyToManyField(Variation, through=CartItem)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=60.00)
def __unicode__(self):
return str(self.id)
def update_subtotal(self):
print "updating..."
subtotal = 0
items = self.cartitem_set.all()
for item in items:
subtotal += item.line_item_total
self.subtotal = subtotal
self.save()
In my View I got:
from django.views.generic.base import View
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404
from django.views.generic.detail import SingleObjectMixin
from products.models import Variation
from .models import Cart, CartItem
# Create your views here.
class CartView(SingleObjectMixin, View):
model = Cart
template_name = "carts/view.html"
def get_object(self, *args, **kwargs):
self.request.session.set_expiry(0) #for expire the session when we login, 0 means when we close browser session expire.
cart_id = self.request.session.get("cart_id")
if cart_id == None: # for cart id
cart = Cart()
cart.save()
cart_id = cart.id
self.request.session["cart_id"] = cart_id
cart = Cart.objects.get(id=cart_id)
if self.request.user.is_authenticated(): # for making user
cart.user = self.request.user
cart.save()
return cart
def get(self, request, *args, **kwargs):
cart = self.get_object()
item_id = request.GET.get("item")
delete_item = request.GET.get("delete")
if item_id:
item_instance = get_object_or_404(Variation, id=item_id)
qty = request.GET.get("qty", 1)
try:
if int(qty) < 1: #if qty <1 delete item
delete_item = True
except:
raise Http404
cart_item = CartItem.objects.get_or_create(cart=cart, item=item_instance)[0]
if delete_item: # for delete item
cart_item.delete()
else:
cart_item.quantity = qty
cart_item.save()
context = {
"object": self.get_object() # get_object from above
}
template = self.template_name
return render (request, template, context)
In my Template I got added context for cart:
{% extends 'home.html' %}
<script>
{% block jquery %}
$(".item-qty").change(function(){
$(this).next(".btn-updated").fadeIn();
});
{% endblock %}
</script>
{% block content %}
<table class="table">
{% for item in object.cartitem_set.all %}
<tr>
<form action="." method="GET" >
<td>{{ item.item.get_title }}</td>
<input type="hidden" name="item" value="{{ item.item.id }}" /> <!-- for item id-->
<td><input type="number" class="item-qty" name="qty" value="{{ item.quantity }}" /> <!-- for quantity selection -->
<input type="submit" class="btn-update btn btn-link" value="Updated item" style="display: None;" /></td> <!-- for update the item-->
<td>{{ item.line_item_total }}</td>
<td class="text-right"><a href="{{ item.remove }}">X</a></td>
</form>
</tr>
{% endfor %}
<tr>
<td colspan="4" class="text-right">Subtotal: {{ object.subtotal }}</td>
</tr>
</table>
{% endblock %}
|
f7dafd53a0292200712c6d99f2f6fdab8b07957f56ae3c836b463c08954cf07e | ['46237204eb0b4d7e9f33a45133950a10'] | Thanks <PERSON>, lots of improvement! Sorry if I was unclear about the usage of this code, I do not want a string as the output so the stringifier part is unnecessary (dictionary works for me). And sys.arv is not needed because this being used as a module within my larger program, and will be called directly. I took your code with some tweaks and inserted it into my original Q, let me know what you think. The use of a dictionary for 'sequences', and regex, definitely cleans things up! However this runs only a tad faster than my original code, any ideas to speed it up? | 584449323364f367b315f54714343c25af3084eb98c471ddb78d63d8f4a49a58 | ['46237204eb0b4d7e9f33a45133950a10'] | Not yet, but it wont even give me the option to try. You think the bios is smart enough to detect an incompatible bootloader and prevent me from selecting USB media as an option? In the past with other computers, I've had all kinds of incompatible bootloaders and the BIOS happily let me to boot into them, to my doom. |
2a697256f38fd47398b1c48a795f6ea1d54923937f788f873a1fa4c3894d6725 | ['462fc5174eca4b37a7bfd310bb8df23c'] | @TonyStewart.EEsince'75 "But this should not occur": What is "this"? "during 80% of the time or so during CC mode from say 50% SoC and only significant cell imbalance is more than 1%": I know what CC & SoC are, but it's unclear what you mean. Thanks for the reply | 98102cbc1e88e621d05df77d93e0dfca2b64da22712cd78c831bdc0629f7f299 | ['462fc5174eca4b37a7bfd310bb8df23c'] | I just ran through all the steps, and I'm having issues with the blt setup. It keeps failing with the Drupal installation. It gives me a warning [warning] Failed to drop or create the database. Do it yourself before installing. dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Referenced from: /usr/local/bin/mysql
Reason: image not found
sh: line 1: 71580 Abort trap: 6 mysql --defaults-file=/private/tmp/drush_jEVO19 --database=information_schema --host=localhost --port=3306 --silent -A < /private/tmp/drush_Xugn6U |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.