Quantcast
Channel: Programming Forums
Viewing all 51036 articles
Browse latest View live

Upload torrent to bytebx.com

0
0
http://bytebx.com/storage
POST /storage HTTP/1.1
Host: bytebx.com
User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:34.0) Gecko/20100101 Firefox/34.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://bytebx.com/storage
Cookie: xxxxxxx
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------1461596626053
Content-Length: 444
-----------------------------1461596626053
Content-Disposition: form-data; name="url"

[i]mod: removed torrent link[/i]
-----------------------------1461596626053
Content-Disposition: form-data; name="file"; filename=""
Content-Type: application/octet-stream


-----------------------------1461596626053--


i made a request file as below where ccont is my generated login cookiecontainer:
Static rnd As New Random()
        Dim boundary As String = "---------------------------" & String.Concat(Enumerable.Range(0, 13).Select(Function(x) rnd.Next(3, 9).ToString()))
        'Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
        Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.bytebx.com/storage"), HttpWebRequest)
        req.Method = "POST"
        req.CookieContainer = ccont 'ccont is my login coociecontainer
        req.KeepAlive = True
        req.Referer = "http://www.bytebx.com/storage"
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; rv:29.0) Gecko/20100101 Firefox/29.0"
        req.ContentType = "multipart/form-data; boundary=" & boundary 
        Dim builder As New StringBuilder()
        builder.Append(boundary & vbNewLine & "Content-Disposition: form-data; name=""url""" & vbNewLine & vbNewLine)
        builder.Append(TextBox3.Text & vbCrLf)
        builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""file""; filename=""""" & vbCrLf)
        builder.Append("Content-Type: application/octet-stream")
        builder.Append(vbNewLine)
        builder.Append(vbNewLine)
        'MsgBox(builder)
        ' Footer Bytes
        Dim close As Byte() = Encoding.UTF8.GetBytes("--")
        Dim postHeader As String = builder.ToString()
        'TextBox4.Text = postHeader
        Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)
        Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(vbCrLf & boundary & "--" & vbCrLf)
        Dim length As Long = postHeaderBytes.Length + boundaryBytes.Length
        req.ContentLength = length
        Dim requestStream As Stream = req.GetRequestStream()
        Dim fulllength As Integer = postHeaderBytes.Length + boundaryBytes.Length
        ' Write out our post header
        requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
        ' Write out the trailing boundary
        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
        Dim responce As WebResponse
        responce = req.GetResponse()
        requestStream.Close()
        Dim s As Stream = responce.GetResponseStream()
        Dim sr As New StreamReader(s)
        Dim Content As String = sr.ReadToEnd()




ohhh sorry... I did not mentioned something..

textbox3.text = [i]mod: removed torrent link[/i]


and i also tried

    Dim boundary As String = "---------------------------" & String.Concat(Enumerable.Range(0, 13).Select(Function(x) rnd.Next(3, 9).ToString()))


And also tried with this

    Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")


but no progress...
Firstly i can login successfully but unable to upload torrent file from remote url.....
textbox3.text contains my remote torrent file url

Display if the letters are in ascending order or not in ascending.

0
0
Hey there i am trying to make a programm that reads a word and display if the letters are in
ascending order or not in ascending order(All kind of letters..capitals..etc).I have made a code but its not 100% correct.
My code:
class Main
{
   public static void main(String args[]) 
   {
    System.out.print( "#Enter text : " );
    String text = BIO.getString();
    
    while ( ! text.equals( "END" ) )
    {
    if (text.equals("END"))
      break;
    for (int i=1; i<text.length(); i++){
    if (text.charAt(i) <= text.charAt(i+1))
        {
            System.out.println(text + " letters in ascending order");
        }
      else 
        {
            System.out.println(text + " letters not in ascending order");
        }
      System.out.print( "#Enter text : " );
      text = BIO.getString();
    }
    }
}
}


Please help me,all answers are accepted :)

Multiple arrays of same type

0
0
Hi all

I'm 99% sure that I've worded the title incorrectly so if you have any suggestions to change it to then please let me know.

Here's kind of what I'm after.

So lets say I want my users to have 'Titles', a user has the title "Mr" so they are displayed as "Mr User". However, I want to give them a drop down list option where they can change it. I would do this via a simple SELECT form.

I can easily do this but what I want is different...If you've ever played World of Warcraft (or any other decent MMO) you'll know you are awarded titles for certain things, so if one of my users is 50 days old, they are awarded a title (lets call it Veteran).

Again I can do a simple "IF age is higher than 50, have 'Veteran' as an option in the SELECT form" but again that's not specifically what I am after, I can do that easily too.

Best way to describe it would be to store each title in a single database row/column, so I would have a column called "Titles" with the values of "Mr, Mrs" in it for user "Dave", so when Dave goes to the SELECT form, he is displayed those two titles as a choice. I know this is not possible in mysql but it would be perfect, if there's anything similar I can do with php/mysql?

This is for a game. There's so many things I could add if I get my head around this (weapons/armour, achievements etc)


EDIT

Closest thing I can think of is have 5 or so columns which each hold a title each, a user can only have 5 titles at once and must replace an old one if they want a new one. This is not ideal but is possible and I wouldn't be unhappy if this was the only way

Send email through Java Mail API

0
0
Hi All,

This is the program i tried
package com.readAlerts;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailUsingGMailSMTP {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "siddharth.polisiti@gmail.com";//change accordingly

// Sender's email ID needs to be mentioned
String from = "sid120s@gmail.com";//change accordingly
final String username = "sid120s";//change accordingly
final String password = "**********";//change accordingly

// Assuming you are sending email through relay.jangosmtp.net
String host = "smtp.gmail.com";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");

// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);

// Set From: header field of the header.
message.setFrom(new InternetAddress(from));

// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));

// Set Subject: header field
message.setSubject("Testing Subject");

// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI ");

// Send message
Transport.send(message);

System.out.println("Sent message successfully....");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}


But I am getting below error:

Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.readAlerts.SendEmailUsingGMailSMTP.main(SendEmailUsingGMailSMTP.java:63)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1545)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:453)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at com.readAlerts.SendEmailUsingGMailSMTP.main(SendEmailUsingGMailSMTP.java:58)
Caused by: java.net.SocketException: Permission denied: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:267)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1511)
... 7 more

Tried every permutation and combination but all leading to this same error.
Any help will be appreciated. THanks in Advance.

Regards,
Siddharth

Change listbox color

0
0
I've changed the listbox foreground color to default application background color so I get:
http://i.imgur.com/pVeaTXI.jpg
which is fine but when I select any element I get white background/foreground(or whatever it is):
http://i.imgur.com/xVy257a.jpg

How can I change this so I will have the same default color in the second case?

It is a windows store app

Xaml code(listbox is at the end):
<Page
    x:Name="pageRoot"
    x:Class="ExchangeRate2.MainPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ExchangeRate2"
    xmlns:common="using:ExchangeRate2.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
 
    <Page.Resources>
        &lt!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">My Application</x:String>
    </Page.Resources>
 
    &lt!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid removed="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
 
        &lt!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding Navigationhelper.GoBackCommand, ElementName=pageRoot}"
                        Style="{StaticResource NavigationBackButtonNormalStyle}"
                        VerticalAlignment="Top"
                        AutomationProperties.Name="Back"
                        AutomationProperties.AutomationId="BackButton"
                        AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                        IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
        <StackPanel HorizontalAlignment="Left" Height="541" Margin="521,28,0,0" Grid.Row="1" VerticalAlignment="Top" Width="684">
            <Grid Height="100">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="300"/>
                    <ColumnDefinition Width="200"/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Border Grid.Column="0" Grid.Row="1">
                    <TextBlock Text="Value Name" FontSize="30" VerticalAlignment="Center" TextAlignment="Center" />
                </Border>
                <Border Grid.Column="1" Grid.Row="1">
                    <TextBlock Text="Value Code" FontSize="30" VerticalAlignment="Center" TextAlignment="Center" />
                </Border>
                <Border Grid.Column="2" Grid.Row="1">
                    <TextBlock Text="Exchange Rate" FontSize="30" VerticalAlignment="Center" TextAlignment="Center" />
                </Border>
            </Grid>
                <ItemsControl ItemsSource="{Binding Data2}" Height="175">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid Height="300" Width="453">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="300"/>
                                    <ColumnDefinition Width="200"/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Grid.Resources>
                                    <Style TargetType="TextBlock">
                                        <Setter Property="Margin" Value="5,0"/>
                                    </Style>
                                </Grid.Resources>
                                <TextBlock Grid.Column="0" Text="bfgbgfbgfbgfbgf" />
                                <TextBlock Grid.Column="1" Text="{Binding ValueCode}" />
                                <TextBlock Grid.Column="2" Text="{Binding ExchangeRate}" />
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
        </StackPanel>
        <Button x:Name="GetExchRate_button" Content="GetExchangeRate" HorizontalAlignment="Left" Margin="346,62,0,0" Grid.Row="1" VerticalAlignment="Top" Click="GetExchRate_button_Click"/>
        <TextBox x:Name="textbox1" HorizontalAlignment="Left" Margin="342,278,0,0" Grid.Row="1" TextWrapping="Wrap" Text="{Binding ValueCode}" VerticalAlignment="Top"/>
        <ListBox x:Name="listbox" HorizontalAlignment="Left" Height="205" Margin="69,224,0,0" Grid.Row="1" VerticalAlignment="Top" Width="187" removed="{x:Null}" BorderBrush="Transparent">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="10">
                        <TextBlock Text="{Binding ValueName}"/>
                        <TextBlock Text="{Binding ValueCode}"/>
                        <TextBlock Text="{Binding ExchangeRate}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Page>


Algorithm inside of a book im reading I don't understand

0
0
So my strong point is not with pointers and references in c/c++ but I am trying to get better with them so I picked up a book to learn a little more about algorithms and I am trying to get connected with an open source community to help me understand some of these hard topics so I just registered today. But my question is this: what does the parameter of this function do?


int maxSubSum1(const vector<int> & a){ // <--- I am seeing this a lot and really wanted to understand it before I kept moving forward.
    int maxSum = 0;
    
    for(int i = 0; i < a.size(); i++){
        for(int j = i; j < a.size(); j++){
            int thisSum = 0;
            
            for (int k = i; k<=j; k++) {
                thisSum = thisSum + a[k];
                //thisSum += a[k];
            
                if (thisSum > maxSum) {
                    maxSum = thisSum;
                }
            }
        }
    }
    return maxSum;
}




The book was very vague on what this algorithm actually did, so I was hoping someone might know and be able to explain it a bit more. Also some practical uses of it.

Thanks,

-bmc

converting int to double pointer outside the main function

0
0
I have int pointer called p and i want to calculate average.Since average involves using double or float so i am trying to convert this in the function averagetemp. It still gives me an error saying "cannot be converted"
Please have a look and help me out.

#include <iostream>
using namespace std;
int* createArray(int n);
int lowesttemp(int *p,int f);
int highesttemp(int *p,int f);
double averagetemp(int *k,double f);
void print(int *p,int lowest_temp,int highesttemp,int average_temp);

int main()
{
	int f,lowest_temp=0,highest_temp=0;
	double average_temp=0;
	cout<<"enter the number of days in a month";
	cin>>f;

	int *p = new int[f];
    p = createArray(f);
	lowest_temp = lowesttemp(p,f);
    highest_temp = highesttemp(p,f);

	average_temp = averagetemp(p,f);
	print(p,lowest_temp,highest_temp,average_temp);


	return 0;
}

int* createArray(int n)
{
   int* ar = new int[n];
   for(int i =0;i <n;i++)
   {
    cout<<"enter the temperatures";
	cin>>*(ar+i);
   }
   return ar;

}

int lowesttemp(int* p,int f)
{
	int c=0,i=0,lowest=0;
    c++;
	if(c==1)
	{
	 lowest=*(p+i);
	}
    for (i = 0; i < f; i++ )
       {
		 if(lowest>*(p+i) )
		 {
		  lowest=*(p+i);
		 }
	   }

	 return lowest;

}
int highesttemp(int *p,int f)
{
 
	int c =0,highest=0,i=0;
	c++;
	if(c==1)
	{
      highest=*(p+0);	
	}
	for (i = 0; i < f; i++ )
       {
		 if(highest<*(p+i) )
		 {
		  highest=*(p+i);
		 }
	   }
	return highest;
}

double averagetemp(double *k,int s)
{
	double n=s;
	double sum=0.0;
	double avg=0.0;
	//double f = (int)s;
	for(int i=0;i<n;i++)
	{
	 sum = sum + *(k+i);
	}
	avg = sum / n;
	return avg;
}
void print(int *p,int lowest_temp,int highesttemp,double average_temp)
{
	cout<<"highest temperature is"<<highesttemp;
	cout<<"lowest temperature is"<<lowest_temp;
	cout<<"average temperature is"<<average_temp;
}


Question Game

0
0
I am trying to set up a game where a question is asked, based on a response of "A", "B", "C", "D" the player either gets the answer right or wrong. However, I'm having a problem in my first question where it will allow the user to input an answer but will state every possible response in the if statement instead of just one. Please keep in mind when responding that I would like to be able to tally up the points after each question to give them a score at the end of the last question. Also, I am a beginner at java. If you find a more efficient way to write out any of the other code below...let me know! Thank you for any help.
[
import java.util.Scanner;
public class GuessGame {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("We are going to play a game.");
		System.out.println("I am going to ask you questions.");
		System.out.println("Please answer with the correct letter");
		System.out.println("Always use a capital letter when answering");
		System.out.println("If you get them right, you get 5 points, if you get them wrong you loose 2 points");
		System.out.println("Let's see how you do!");
		
		System.out.println("Okay, are you ready?");
		String text = input.nextLine();
		switch (text) {
		case "yes":
			System.out.println("Alright, let's begin!");
			break;
		case "Yes":
			System.out.println("Alright, let's begin!");
			break;
		case "no":
			System.out.println("Okay, maybe another time");
			break;
		case "No":
			System.out.println("Okay, maybe another time");
			break;
		}
		System.out.println("When did California become a state?");
		System.out.println("A: September 9, 1850");
		System.out.println("B: August 25, 1875");
		System.out.println("C: December 13, 1453");
		System.out.println("D: May 15, 1854");
		String question1 = input.nextLine();
		String response = "A: September 9, 1850";
		String fresponse = "B: August 25, 1875";
		String sresponse = "C: December 13, 1453";
		String tresponse = "D: May 15, 1854";
		if(question1 == response);
		System.out.println("That is correct! You earned five points");
		if (question1 == fresponse);
			System.out.println("That is wrong. You lost 2 points");
		if (question1 == sresponse);
			System.out.println("That is wrong. You lost 2 points");
		if (question1 == tresponse);
			System.out.println("That is wrong. You lost 2 points");
		}
	
	}

/]

Python 3: Remove decimal without rounding.

0
0
amount = float(input("Enter amount: "))
print(amount)



if user enters 11.65 I need it to convert to 1165

Thanks.

Delete Strikeout Text

0
0
i used this loop to delete all strikeout text and was working fine, the problem is that, when it comes to large files, this becomes very slow

is there a more faster and effective way of removing strikeout text?

Thanks

For i = .TextLength To 1 Step -1
   .Select(i, 1)
   If .SelectionFont.Strikeout Then
      .SelectedText = ""
   End If
Next

Infragistics UltraGrid.PerformAction doesn't do specified action

0
0
Private Sub findSelectedRowID()
        Dim SaveID As Integer = 0
        If Not IsNothing(grdTimeCard.ActiveRow) Then
            Dim rowID As Integer = 0
            rowID = grdTimeCard.ActiveRow.Index + 1
            SaveID = grdTimeCard.Rows(rowID).Cells("RecID").Value
        End If
        RefreshGrid()
        If SaveID > 0 AndAlso grdTimeCard.Rows.Count > 0 Then
            Dim Count As Integer = 0
            Dim Found As Boolean = False
            While Not Found AndAlso Count < grdTimeCard.Rows.Count
                If grdTimeCard.Rows(Count).Cells("RecID").Text = SaveID Then
                    Found = True
                    grdTimeCard.Rows(Count).Activate()
                    grdTimeCard.ActiveCell = grdTimeCard.Rows(Count).Cells("WorkDate")
                    grdTimeCard.PerformAction(UltraGridAction.EnterEditMode, False, False)
                Else
                    Count = Count + 1
                End If
            End While
        End If
    End Sub


Here is the code that I've came up with. The breakdown is as follow:

1) After updating a row in the grid, it goes and finds the RecID of the row after going to the next row index.
2) It then refills the table adapter and does all the grid "stuff" (not relevant to this portion).
3) It sets the row in which you are continuing from.
4) It sets the ActiveCell and then enter into edit mode (which enters edit mode on the active cell).

Only problem is that there is no way to enter edit mode except with the .PerformAction(UltraGridAction.EnterEditMode) function (that I know of through searching). For some reason, it doesn't enter into edit mode at the first visible cell (which I set manually). Does anyone know how to get the grid into edit mode as I have specified. If there is another way to get the UltraGrid to enter edit mode, I would definitely be open to trying a different way into forcing it into edit mode. Thanks in advance! :)

Reading multiple option values from a config file

0
0
I had an issue earlier where my script wasn't reading the option values from my config files. I have solved that issue but I still can't get it to read multiple option values. I want any file that is uploaded with the option values to create an error if the option values don't match what's in the config files. The end product is to allow a non-coder to be able to add option values that get read to a config file. Here are the two config files I'm using and the script.

[Actions]
actionItems = Add,Update,Delete




[Objects]
objects = Host Group, Service Group, Service



#!usr/bin/python


from subprocess import *
from pynag import Model
import sys
import ConfigParser, os
import csv
import getopt
import time
import datetime
from datetime import date
from time import gmtime, strftime
import logging
sys.path.insert(1, '/opt/pynag')
from sys import argv
script, solution_id, input_file = argv

#creating time stamp and returning as a string to add to solution id log name
def timeIzNow():  
    full = time.strftime(" %Y-%m-%d %H:%M:%S")
 
    return full

#set up logging file
LOG_FILENAME = solution_id  + timeIzNow() 
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s %(process)d',
                    datefmt='%d %b %Y %H:%M:%S', 
                    filename=LOG_FILENAME,
		      filemode='w')   
# defining a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# setting a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
# telling the handler to use this format
console.setFormatter(formatter)
# adding the handler to the root logger
logging.getLogger('').addHandler(console)

def knownActions():
    #set up configuration Parser
    actions = ConfigParser.RawConfigParser()
    actions.read('/etc/nagios/ingestion/action.cfg')
    #get the action items
    actions = actions.get('Actions','actionItems')
    return actions

def knownObjects():
     #set up configuration Parser
     config = ConfigParser.RawConfigParser()
     config.read('/etc/nagios/ingestion/objectItems.cfg')
     #get the object types
     objects = config.get('Objects', 'objects')
     return objects



#Get inputs and check value and path to file
try:
    current_file = csv.reader(open(input_file, "rb"), delimiter='\t')
except:  
    logging.error('No such file or directory. Please try again')
else:
    for line in current_file:        
        for row in current_file:       
            if solution_id != row[2]:
                logging.error('Solution ID is invalid. Please check the number and try again')        
            elif knownActions() != row[0]:                    
                logging.error("Undefined action")               
            elif knownObjects() != row[1]:              
                logging.error("Unknown object")             
            else:    
                print row
                    
finally:
     print "all error checks done!" 
 
sys.exit(0) 





















































Is this possible with Python?

0
0
Hey guys,

Yes it is probably possible with Python and maybe simple for some of you, but since I am new to Python I have no idea how.
I don't want that you code the program for me, but would greatly appreciate it, if you would lead me into the right direction
and tell me how I can make this a success :)


The program should do the following:


1) Go To a Website "www.productinfo.com"
2) Login with Account
3) go to menu point "search product"

4) Then open an Excel table
5) Copy row 1 column B "Product A" from the Excel table
6) Enter the value "Product A" into the search
7) Start the search
8) On the result page: read "Purchase price= "X" ",
9) Enter value of "X" into Excel table row 1 column C

10) Jump into the next row of Excel table
11) Copy row 2 column B "Product B" from the Excel table
12) ...

and so on until the last row is empty and the program stops.

Your help into the right direction is greatly appreciated!!

Thanks a lot

JANROS

Help with RobotC programming

0
0
My students are part of a robotics team. We are a brand new team and can't find anyone to help us with RobotC. Can anyone help us out?
#pragma config(Hubs,  S1, HTMotor,  HTMotor,  HTServo,  HTMotor)
#pragma config(Hubs,  S2, HTMotor,  none,     none,     none)
#pragma config(Sensor, S1,     ,               sensorI2CMuxController)
#pragma config(Sensor, S2,     ,               sensorI2CMuxController)
#pragma config(Motor,  mtr_S1_C1_1,     LeftWheelMotor, tmotorTetrix, PIDControl, encoder)
#pragma config(Motor,  mtr_S1_C1_2,     RightWheelMotor, tmotorTetrix, PIDControl, reversed, encoder)
#pragma config(Motor,  mtr_S1_C2_1,     RightLiftMotor, tmotorTetrix, openLoop)
#pragma config(Motor,  mtr_S1_C2_2,     RightLiftMotor2, tmotorTetrix, openLoop)
#pragma config(Motor,  mtr_S1_C4_1,     LeftLiftMotor, tmotorTetrix, openLoop, reversed)
#pragma config(Motor,  mtr_S1_C4_2,     LeftLiftMotor2, tmotorTetrix, openLoop, reversed)
#pragma config(Motor,  mtr_S2_C1_1,     IntakeMotor,   tmotorTetrix, openLoop)
#pragma config(Motor,  mtr_S2_C1_2,     motorK,        tmotorTetrix, openLoop)
#pragma config(Servo,  srvo_S1_C3_1,    IntakeServo,          tServoContinuousRotation)
#pragma config(Servo,  srvo_S1_C3_2,    LeftHook,             tServoStandard)
#pragma config(Servo,  srvo_S1_C3_3,    RightHook,            tServoStandard)
#pragma config(Servo,  srvo_S1_C3_4,    servo4,               tServoNone)
#pragma config(Servo,  srvo_S1_C3_5,    servo5,               tServoNone)
#pragma config(Servo,  srvo_S1_C3_6,    servo6,               tServoNone)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//

/////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                           Tele-Operation Mode Code Template
//
// This file contains a template for simplified creation of an tele-op program for an FTC
// competition.
//
// You need to customize two functions with code unique to your specific robot.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////

#include "JoystickDriver.c"  //Include file to "handle" the Bluetooth messages.


/////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                    initializeRobot
//
// Prior to the start of tele-op mode, you may want to perform some initialization on your robot
// and the variables within your program.
//
// In most cases, you may not have to add any code to this function and it will remain "empty".
//
/////////////////////////////////////////////////////////////////////////////////////////////////////

void initializeRobot()
{
 // Place code here to sinitialize servos to starting positions.
 // Sensors are automatically configured and setup by ROBOTC. They may need a brief time to stabilize.

 return;
}


/////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                         Main Task
//
// The following is the main code for the tele-op robot operation. Customize as appropriate for
// your specific robot.
//
// Game controller / joystick information is sent periodically (about every 50 milliseconds) from
// the FMS (Field Management System) to the robot. Most tele-op programs will follow the following
// logic:
//   1. Loop forever repeating the following actions:
//   2. Get the latest game controller / joystick settings that have been received from the PC.
//   3. Perform appropriate actions based on the joystick + buttons settings. This is usually a
//      simple action:
//      *  Joystick values are usually directly translated into power levels for a motor or
//         position of a servo.
//      *  Buttons are usually used to start/stop a motor or cause a servo to move to a specific
//         position.
//   4. Repeat the loop.
//
// Your program needs to continuously loop because you need to continuously respond to changes in
// the game controller settings.
//
// At the end of the tele-op period, the FMS will autonmatically abort (stop) execution of the program.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////

task main()

  {
   initializeRobot();
 int threshold = 10;

 waitforstart();   // wait for start of tele-op phase

 while (true)
  ///////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////
  ////                                                   ////
  ////      Add your robot specific tele-op code here.   ////
  ////                                                   ////
  ///////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////

  // Insert code to have servos and motors respond to joystick and button values.

  // Look in the ROBOTC samples folder for programs that may be similar to what you want to perform.
  // You may be able to find "snippets" of code that are similar to the functions that you want to
  // perform.

  getJoystickSettings(joystick);

    // Driver Joystick 2
  if (joystick.joy2_y1)
  {
   motor[rightWheelMotor] = joystick.joy2_y1 *100 /127;
  }
  if (joystick.joy2_y2)

   motor[leftWheelMotor] = joystick.joy2_y2 *100 /127;

  // Intake Servo control Joystick 1
  if(joy1Btn(7))
  {
     //Do something...
   //servo[IntakeServo] = 131;
   motor[IntakeMotor] = -100;
  }

  // Intake Servo control Joystick 1
  if(joy1Btn(5))
  {
   //servo[IntakeServo] = 0;
   motor[IntakeMotor] = 100;
  }

  // Intake Servo control Joystick 1
  if(joy1Btn(1))
  {
   //servo[IntakeServo] = 255;
   motor[IntakeMotor] = 0;
  }

  // Lift motor control Joystick1
  if (abs(joystick.joy1_y1) > 10)
  {
   //motor[RightLiftMotor] = joystick.joy1_y1 *100 /127;
  }
  else
  {
   //motor[RightLiftMotor] = 0;
  }
  if (abs(joystick.joy1_y2) > 10)
  {
   //motor[LeftLiftMotor] = joystick.joy1_y2 *100 /127;
  }
  else
  {
   //motor[LeftLiftMotor] = 0;
  }

  if(joystick.joy1_TopHat == 0)
  {
   //servo[RightHook] = 200;
   servo[LeftHook]  = 200;
  }
  if(joystick.joy1_TopHat == 4)
  {
     //servo[RightHook] = 250;
   servo[LeftHook]  = 250;
  }
 }

Approximate Sine Function with Taylor Series

0
0
hi

i need help i have been doing this for days

i dont want people directing me to articles or just been negative

Write a C program with a separate function which calculates the sine function from the first principles according to the formula below.

the code should find the sine value in 5 stages and then final answer

formula below

sin(x) = x −x3/3!+x5/5!−x7/7!+x9/9!

ihave done the code and it just gives me a final sine wave

it should find a error then plus one so on till it gets the answer


thank you

]My link

My link

these are images of what it shold look like and the image of a the formula

any one can be used

Posted Image

Print out a Rubik's Cube using a [3][4] matrix

0
0
I am trying to print out a rubix cube nicely so that it looks something along the lines of this:
** ** ** R1 R2 R3 ** ** ** 
** ** ** R4 R5 R6 ** ** ** 
** ** ** R7 R8 R9 ** ** ** 
B1 B2 B3 Y1 Y2 Y3 G1 G2 G3
B4 B5 B6 Y4 Y5 Y6 G4 G5 G6
B7 B8 B9 Y7 Y8 Y9 G7 G8 G9
** ** ** O1 O2 O3 ** ** ** 
** ** ** O4 O5 O6 ** ** ** 
** ** ** O7 O8 O9 ** ** ** 
** ** ** W1 W2 W3 ** ** ** 
** ** ** W4 W5 W6 ** ** ** 
** ** ** W7 W8 W9 ** ** **



however, when I try to print out the entire cube, I get this:
** ** ** 
** ** ** 
** ** ** 
	R1 R2 R3 
R4 R5 R6 
R7 R8 R9 
	** ** ** 
** ** ** 
** ** ** 
	
B1 B2 B3 
B4 B5 B6 
B7 B8 B9 
	Y1 Y2 Y3 
Y4 Y5 Y6 
Y7 Y8 Y9 
	G1 G2 G3 
G4 G5 G6 
G7 G8 G9 
	
** ** ** 
** ** ** 
** ** ** 
	O1 O2 O3 
O4 O5 O6 
O7 O8 O9 
	** ** ** 
** ** ** 
** ** ** 
	
** ** ** 
** ** ** 
** ** ** 
	W1 W2 W3 
W4 W5 W6 
W7 W8 W9 
	null	


I have found out the area that causes this, my toString, but I want to know if there is something built in or not that will allow me to print it such that I can continue printing it at the same row level as its neighbor, even though I create a new line for each individual column?

Here is the code that I try to print out the entire cube:
void printEntireCube(){
		
		for(int row = 0; row < 4; row++){
			for(int col = 0; col < 3; col++){
				System.out.print(cube[col][row] + "\t");
			}
			System.out.println();
		}
	}
void createCube(){
		/*each of these are being assigned to a sideObject of a cube
so for example, left = B1 B2 ... B9 */
		cube[0][0] = blank;
		cube[0][1] = left;
		cube[0][2] = blank;
		cube[0][3] = blank;
		cube[1][0] = back;
		cube[1][1] = top;
		cube[1][2] = front;
		cube[1][3] = bottom;
		cube[2][0] = blank;
		cube[2][1] = right;
		cube[2][2] = blank;
		cube[2][2] = blank;		
	}



Here is the reason why it comes out the way it does:
public String toString(){
		
		for(int i = 1; i <= 9; i++){
			System.out.print(side[i-1] + " ");
			if(i % 3 == 0)
				System.out.println();//because of this!, but I still need it
		}
		return "";
	}

EXE code injector (sorth of)

0
0
hi, i got interested by the way how virusses work a while ago. i decided to write my own just as a challenge, i want to make my own little infectious program just becouse i can, i would like to test it in virtual box. I know that you guys wont help me creating a real virus but that's not where i am here for anyways so i decided to still ask this question becouse its just educational and almost any anti virus will detect a visual basic file. but anyways i want to make a program that displays a message box on each file that is infected. so when you open the virus it will try to infect as many other exe files on the pc or in the directory as possible. when the files are infected and you run them they should display a msgbox just like the original virus does and also try to infect other exe files. I was thinking to do it with a file binder witch binds a vbs script with a msgbox
msgbox "hello world"
to all the exe files in the directory and replace the original exe. what i've got with my current google knowledge is this
DELETED
the visual form contains 3 buttons (button 1 to choose file 1, button 2 to choose file 2 and button 3 to bind the 2 files and save them) and 2 textbox' (textbox1 to save the location of file 1 and textbox2 to save the location of file 2) the code is almost all from google becouse i couldn't find a real non copy/paste TUT witch i think is kind of sad... but anyways i want the program to create a vbs file and bind it with the exe files and (if possible) make the exe file's icon the same as the replaced program. i've tried searching this but couldn't find anything usefull for me. way to complicated... im kinda new to vb.net so take it easy on me if i make some dumb mistakes (^.^) and thanks in advance!

Arithmetic progression

0
0
The question:
Calculate the sum of arithmetic progression.

The answer is:

int GradeSequence (int start, int diff, int end)
{
	int x, sum, i;
		for (x=start, sum=x, i=1; i<end; i++)
        {
		x+=diff;
		sum+=x;
	}
	return (sum);
}


I remember the for loop formula is
for(INITIALIZATION; CONDITION; INCREMENT/DECREMENTS)
{
}
Why this answer writes
for (x=start, sum=x, i=1; i<end; i++)
And what's the logic about x+=diff; sum+=x;
Thank you very much

How can I delete an image that was previously shown in ItemsControl?

0
0
On line 128 I'm attempting to delete an image file that was previously shown in an ItemsControl, but was removed by line 126. So the image is not being shown in the program at the time I'm wanting to delete the file.

I've racked my brain for hours on this. I keep reading about needing to Dispose of images when you're done with them before messing the the file, but again, I've had zero luck getting anything even close to working.

Any guidance or assistance would be a huge help. Thanks.

Error:
Additional information: The process cannot access the file 'c:\Studio\Exit Popup\Keith Sketch.png' because it is being used by another process.


My Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Drawing;
using System.ComponentModel;

namespace StudioManager
{

    public class ComboboxItem
    {
        public string Text { get; set; }
        public string Value { get; set; }
        public override string ToString() { return Text; }
    }

    public class ImageDetails
    {
        /// <summary>
        /// A name for the image, not the file name.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// A description for the image.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// Full path such as c:\path\to\image.png
        /// </summary>
        public string Path { get; set; }

        /// <summary>
        /// The image file name such as image.png
        /// </summary>
        public string FileName { get; set; }

    }

    /// <summary>
    /// Interaction logic for Mainwindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            PopulateCombobox();

        }

        public void PopulateCombobox()
        {
            //Clear Combobox Items
            projectList.Items.Clear();

            // Set root folder location
            DirectoryInfo rootdir = new DirectoryInfo(@"C:\Studio");

            // Get the subdirectories under our set root folder. Filter hidden folders
            var dirInfos = rootdir.GetDirectories("*.*").Where(x => (x.Attributes & FileAttributes.Hidden) == 0);

            // Run through the directory list and populate project dropdown
            foreach (DirectoryInfo d in dirInfos)
            {
                ComboboxItem item = new ComboboxItem();
                item.Text = d.Name;
                item.Value = d.Name;
                projectList.Items.Add(item);
            }

        }

        private void ComboBoxItem_Selected(object sender, RoutedEventArgs e)
        {

        }

        private void ComboBox_Selectionchanged(object sender, SelectionchangedEventArgs e)
        {
            int selectedIndex = projectList.SelectedIndex;
            Object selectedItem = projectList.SelectedItem;

            if (selectedIndex != -1)
            {
                // Set root folder location
               DirectoryInfo rootdir = new DirectoryInfo(@"C:\Studio\" + selectedItem.ToString());

               List<ImageDetails> images = new List<ImageDetails>();

               foreach (var fi in rootdir.GetFiles("*.jpg").Concat(rootdir.GetFiles("*.png")))
               {

                   ImageDetails id = new ImageDetails();
                   id.Path ="c:\\Studio\\Exit Popup\\" + fi.Name;
                   id.FileName = fi.Name;

                   images.Add(id);

               }

               ImageList.ItemsSource = images;
            }

        }

        private void CommandBinding_Executed_Remove(object sender, ExecutedRoutedEventArgs e)
        {
            IEditableCollectionView items = ImageList.Items;

            if (items.CanRemove)
            {
                items.Remove(e.Parameter);

                File.Delete(  ((StudioManager.ImageDetails)(e.Parameter)).Path );

            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Specify the directory you want to manipulate. 
            string path = @"c:\Studio\" + newProjectName.Text;            

            try
            {
                // Determine whether the directory exists. 
                if (System.IO.Directory.Exists(path))
                {
                    return;
                }

                // Try to create the directory.
                System.IO.DirectoryInfo di = System.IO.Directory.CreateDirectory(path);
                
                // Delete the directory.
                //di.Delete();

                PopulateCombobox();
            }
            catch (Exception er)
            {

            }
            finally { }
        }
    }
}

Run console app on remote computer

0
0
Hey guys. I'm looking for a way to run my console app in C# on one computer, but the actual program is ran on another computer. IE I open the file or hit "Run" in Visual Studio on computer1, the computer2 runs the program. I was looking online and found some stuff that may be applicable, but I didn't see a very clear answer.
Viewing all 51036 articles
Browse latest View live




Latest Images