text:
Q: Representing a phrase as a block of code How can I represent the concept "I have 99 issues but a bug ain't one" using some fancy code?
Background
I picked the lead dev for Secret Santa. I'd like to get him a tshirt with the above on it expressed as a block of code / fuction / query string.
We were all in a meeting one day discussing Jira issues and he said "I have 99 issues" and I shouted out "but a bug ain't one" and everyone had a good laugh.
So I'd like to put that on a tshirt for him as it think it would be a fun present.
He is a really awesome guy, super smart, always has time to explain something to us non tech folk, a real heat of gold.
Can you help me?
If it could have something to do with .net/SQL/Bash that would be great.
Thanks

A: Very goofy question but I'll shoot xD.
Javascript Classical
class Me{
  issues: 99,
  bug: 0,
}

JavaScript Functional
function status() {
  if (I.problems === 99 && I.bugs !== 1) {
    console.log('hit it');
  }
}

SQL
SELECT * FROM I
WHERE issues=99 AND bugs<>1;


text:
Q: how send-register works on mvvm light? I know how to use/code sending and registering objects in mvvm light. This is not what I want to ask but I am curious what is happening behind the scenes? I was searching all over and I couldnt find a deep explanation. Is it like address pointing in the memory. objects are addressed somehow by type or? I mean how one class sends and others finds it just by indicating their type. Can somebody shed some lights here please or a link reference where I can read about it?

A: I think the below links will help you to understand how register/subscription  works in mvvm light.
https://msdn.microsoft.com/en-us/library/ff921122.aspx
http://brentedwards.net/2010/04/13/roll-your-own-simple-message-bus-event-aggregator/
I guess Mvvm light also using similar implementation. You can see the mvvm light messenger code here
Hope it helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Car App htc one m 8 As the HTC ONE M8 is certified for MirrorLink usage, it also has a customized car app, which comes with an activity that allows phone calls while driving.
Is there a way to start this activity from an external application? Is the only way to call this activity if the app or rather that activity has implemented the ACTION_CALL intent?
thanks

A:
Is there a way to start this activity from an external application?

Yes, you can do that with an intent filter, here´s the information:
http://developer.android.com/training/basics/intents/filters.html
but if you only want to open the application, knowing the application package is enough with:
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("your.other.app");
startActivity(intent);


text:
Q: I am having an issue with useEffect and React Redux. I am getting errors within useEffect saying "nothing was returned from render" I cannot tell why I am getting the error below. I suspect it has to do with the provider but I do not know how to fix this. The reason I suspect it has to do with the provider is simply because when I comment out lines 71-73 and uncomment lines 67-69 it renders and the error goes away.
Error: Main(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
Error:
  40 | useEffect(() => {
  41 |   setLoaded(true);
  42 |   firebase.auth().onAuthStateChanged(user => {
> 43 |     user ? setLoggedIn(true) : setLoggedIn(false);
     | ^  44 |   });
  45 |   // return() => null;
  46 | }, []);

My code:
     1  import { StatusBar } from 'expo-status-bar';
     2  import React, { useState, useEffect } from 'react';
     3  import { NavigationContainer } from "@react-navigation/native";
     4  import { createStackNavigator } from "@react-navigation/stack";
     5  import { View, Text } from "react-native"
     6  import { Provider } from "react-redux"
     7  import { createStore, applyMiddleware } from "redux"
     8  import LandingScreen from "./components/auth/Landing"
     9  import RegisterScreen from "./components/auth/Register"
    10  import MainScreen from "./components/Main"
    11  import firebase from "firebase"
    12  import config from "./config"
    13  import rootReducer from "./redux/reducers"
    14  import thunk from "redux-thunk"
    15
    16  const store = createStore(rootReducer, applyMiddleware(thunk))
    17
    18  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    19  const firebaseConfig = {
    20    apiKey: config.API_KEY,
    21    authDomain: config.AUTH_DOMAIN,
    22    projectId: config.PROJECT_ID,
    23    storageBucket: config.STORAGE_BUCKET,
    24    messagingSenderId: config.MESSAGING_SENDER_ID,
    25    appId: config.APP_ID,
    26    measurementId: config.MEASUREMENT_ID
    27  };
    28
    29  if(firebase.apps.length === 0) {
    30    firebase.initializeApp(firebaseConfig);
    31  }
    32
    33  const Stack = createStackNavigator();
    34
    35  export function App() {
    36
    37    const [ loaded, setLoaded ] = useState(false);
    38    const [ loggedIn, setLoggedIn ] = useState(false);
    39
    40    useEffect(() => {
    41      setLoaded(true);
    42      firebase.auth().onAuthStateChanged(user => {
    43        user ? setLoggedIn(true) : setLoggedIn(false);
    44      });
    45      // return() => null;
    46    }, []);
    47
    48    if(!loaded) {
    49      return(
    50        <View style={{ flex: 1, justifyContent: "center" }}>
    51          <Text>Loading</Text>
    52        </View>
    53      );
    54    }
    55
    56    if(!loggedIn) {
    57      return (
    58        <NavigationContainer>
    59          <Stack.Navigator initialRouteName="Landing">
    60            <Stack.Screen name="Landing" component={LandingScreen} options={{ headerShown: false }}/>
    61            <Stack.Screen name="Register" component={RegisterScreen} options={{ headerShown: false }}/>
    62          </Stack.Navigator>
    63        </NavigationContainer>
    64      );
    65    } else {
    66      return (
    67        // <View style={{ flex: 1, justifyContent: "center" }}>
    68        //   <Text>jawn</Text>
    69        // </View>
    70
    71        <Provider store={store}>
    72          <MainScreen />
    73        </Provider>
    74      );
    75    };
    76
    77  }
    78
    79  export default App

A: This might help
if (!loaded) {
  return (...);
}

return !loggedIn ? (
  <NavigationContainer>
    <Stack.Navigator initialRouteName="Landing">
      <Stack.Screen
        name="Landing"
        component={LandingScreen}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Register"
        component={RegisterScreen}
        options={{ headerShown: false }}
      />
    </Stack.Navigator>
  </NavigationContainer>
) : (
  <Provider store={store}>
    <MainScreen />
  </Provider>
);


text:
Q: data and file upload form using php and mysql I need help with uploading data (dealer name, make, model etc) and multiple files (images & videos) to a folder and then the paths to a database.
I have the code which seems perfect because I am not getting any errors, but nothing is being sent to the database or the folder.
upload.php
<?php

$con = mysqli_connect('localhost', 'root', 'mbiti', 'vaws');

//check connection
//if (!$link) {

//  die('Connect Error(' .mysqli-connect_errno(). ')'
//                  .mysqli-connect_errno());

//}

//escape variables for added security
//these field are entered by user using the form
$dealer_name = mysqli_real_escape_string($con, $_POST['dealer_name']);
$phone_number = mysqli_real_escape_string($con, $_POST['phone_number']);
$advert_title = mysqli_real_escape_string($con, $_POST['advert_title']);
$make = mysqli_real_escape_string($con, $_POST['make']);
$model = mysqli_real_escape_string($con, $_POST['model']);
$type = mysqli_real_escape_string($con, $_POST['type']);
$year = mysqli_real_escape_string($con, $_POST['year']);
$price = mysqli_real_escape_string($con, $_POST['price']);
$condition_ = mysqli_real_escape_string($con, $_POST['condition_']);

$query2="INSERT into advert('dealer_name' , 'phone_number' , 'advert_title' , 'make' , 'model' , 'type' , 'year' , 'price' , 'condition_') VALUES ('$dealer_name' , '$phone_number' , '$advert_title' , '$make' , '$model' , '$type' , '$year' , '$price' , '$condition_')";
mysqli_query($con, $query2);

if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];
        if($file_size > 20971520){
            $errors[]='File size must be less than 20 MB';
        }

        $query="INSERT into media (`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$file_name','$file_size','$file_type')";

        $desired_dir="user_data";

        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"user_data/".$file_name);
            }else{                                  //rename the file if another one exist
                $new_dir="user_data/".$file_name.time();
                 rename($file_tmp,$new_dir) ;
            }
            mysqli_query($con, $query);
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}

mysqli_close($con);

?>


text:
Q: DRY in RelayCommand in WPF How to avoid this kind of repetition in the RelayCommand part of the code below:
MainViewModel.cs
public class MainViewModel : BaseViewModel
{
    public RelayCommand HomeViewCommand { get; set; }
    public RelayCommand CustodyViewCommand { get; set; }
    public RelayCommand OperationsViewCommand { get; set; }

    private BaseViewModel _currentViewModel;
    public BaseViewModel CurrentViewModel
    {
        get => _currentViewModel;
        set
        {
            _currentViewModel = value;
            OnPropertyChanged("CurrentViewModel");
        }
    }
    public MainViewModel()
    {
        CurrentViewModel = new HomeViewModel();

        HomeViewCommand = new RelayCommand(o =>
        {
            CurrentViewModel = new HomeViewModel();
        });

        CustodyViewCommand = new RelayCommand(o =>
        {
            CurrentViewModel = new CustodyViewModel(); ;
        });

        OperationsViewCommand = new RelayCommand(o =>
        {
            CurrentViewModel = new OperationsViewModel(); ;
        });
    }
}

And then I bind the Commands to the Buttons...
MainWindow.xaml
<Button Content="Home"
        Command="{Binding HomeViewCommand}"/>
<Button Content="Custody"
        Command="{Binding CustodyViewCommand}"/>
<Button Content="Operations"
        Command="{Binding OperationsViewCommand}"/>

I couldn't figure out how to implement a kind of NavigateToCommand

A: Simply create identifiers for the view models e.g., enum and store each view model in a Dictionary with the ID object as key. Then use the key as CommandParameter with the button. The command handler can use this key to select the appropriate view from the Dictionary. Alternatively select the view models by index. For example a "Next" or "Previous" button could navigate by index.
The following example use an enum as identifier for the view and as key for the Dictionary.
ViewId.cs
public enum ViewId
{
  Default = 0, Home, Custody, Operations
}

MainViewModel.cs
public class MainViewModel : BaseViewModel
{
  public RelayCommand NavigateToCommand
    => new RelayCommand(ExecuteNavigateToCommand);

  private BaseViewModel _currentViewModel;
  public BaseViewModel CurrentViewModel
  {
    get => _currentViewModel;
    set
    {
      _currentViewModel = value;
      OnPropertyChanged(nameof(this.CurrentViewModel));
    }
  }

  private Dictionary<ViewId, BaseViewModel> Views { get; }

  public MainViewModel()
  {
    this.Views = new Dictionary<ViewId, BaseViewModel>
    {
      { ViewId.Home, new HomeViewModel() },
      { ViewId.Custody, new CustodyViewModel() },
      { ViewId.Operations, new OperationsViewModel() }
    };
  }

  private void ExecuteNavigateToCommand(object commadParameter)
  {
    if (commandParameter is ViewId viewId
      && this.Views.TryGetValue(viewId, out BaseViewModel view)
    {
      this.CurrentViewModel = view;
    }
  }
}

View.xaml
<Button Content="Home"
        Command="{Binding NavigateToCommand}"
        CommandParameter="{x:Static ViewId.Home}" />
<Button Content="Custody"
        Command="{Binding NavigateToCommand}"
        CommandParameter="{x:Static ViewId.Custody}" />
<Button Content="Operations"
        Command="{Binding NavigateToCommand}"
        CommandParameter="{x:Static ViewId.Operations}" />


text:
Q: Ordering a table in PostgreSQL on two columns, so that the value in column X is equal to the value in column Y of the previous record I have a table in PostgreSQL, with the following structure:
   id        | from     | to
----------+----------+--------
    11    | 18       |     123
    3     | 88       |     6
    23    | 33       |     18
    7     | 123      |     88

I would like to sort that table, so that the value of the "from" field in a given record is equal to the value of the "to" field in the previous record. In other words, the example above, when ordered, should look like this:
 id        | from     | to
----------+----------+--------
    23    | 33       |     18
    11    | 18       |     123
    7     | 123      |     88
    3     | 88       |     6

Does someone know how this can be accomplished in PostgreSQL? Thank you very much.

A: You can do this using recursive CTEs, keeping track of the root and the level.  The following assumes that you have no cycles:
with recursive t (id, fr, t) as (
      values (11, 18, 123), (3, 88, 6), (23, 33, 18), (7, 123, 88)
     ),
     cte as (
      select t.id, t.fr, t.t, t.fr as root, 1 as lev
      from t
      where not exists (select 1 from t t2 where t2.t = t.fr)
      union all
      select t.id, t.fr, t.t, cte.root, cte.lev + 1
      from t join
           cte
           on t.fr = cte.t
     )
select *
from cte
order by cte.root, cte.lev;

Note: from and to are bad column names because they conflict with SQL keywords.


text:
Q: How many well-behaved norms are there on $C[0,1]$?
Let $\Vert \cdot \Vert$ a norm on $X=C([0,1])$ s.t.
1. $X$ is complete w.r.t. $\Vert \cdot \Vert$;
2. convergence in $\Vert \cdot \Vert$ implies pointwise convegence, i.e.
  $$
\Vert x_n - x \Vert \to 0 \Rightarrow \forall t \in [0,1], \quad x_n(t) \to x(t).
$$
Is $\Vert \cdot \Vert$ equivalent to the usual $\sup$-norm, $\Vert \cdot \Vert_{\infty}$?

By open mapping and 1 (completeness), we just need to prove only one inequality of the two we need to prove equivalence (indeed, the other would follow by open mapping).
Anyway, I think the answer is affirmative; am I right? I do not know how to prove it. Any ideas, please? Thanks.

A: The hypothesis implies that for all $t\in I=[0,1]$ the linear functional $\mathrm{ev}_t:X\to\Bbb R, ~f\mapsto f(t)$ is continuous. Also, for any $f\in X$, $$\sup_{t\in I}~|\mathrm{ev}_t(f)|=||f||_{\infty}<+\infty$$ Since $X$ is a Banach space, the uniform boundedness principle applies, and $$ C=\sup_{t\in I}~||\mathrm{ev}_t||_{X'}<+\infty$$ that is, for any continuous function $f$ and any $t\in I$, $|f(t)|\leq C||f||_X$ thus $$||\cdot||_{\infty}\leq C||\cdot||_X$$ As you noted, the open mapping theorem then tells us that both norms are equivalent.


text:
Q: How to do a simple Count in Linq? I wanted to do a paging style table, but NeerDinner example fetches the entire data into a PaggingList type, and I have more than 10 000 rows to be fetched, so I skipped that part.
so I come up with this query
var r = (from p in db.Prizes
            join c in db.Calendars on p.calendar_id equals c.calendar_id
            join ch in db.Challenges on c.calendar_id equals ch.calendar_id
            join ca in db.ChallengeAnswers on ch.challenge_id equals ca.challenge_id
            join cr in db.ChallengeResponses on ca.challenge_answer_id equals cr.challenge_answer_id

            where
                p.prize_id.Equals(prizeId)
                && ch.day >= p.from_day && ch.day <= p.to_day
                && ca.correct.Equals(true)
                && ch.day.Equals(day)

            orderby cr.Subscribers.name

            select new PossibleWinner()
            {
                Name = cr.Subscribers.name,
                Email = cr.Subscribers.email,
                SubscriberId = cr.subscriber_id,
                ChallengeDay = ch.day,
                Question = ch.question,
                Answer = ca.answer
            })
        .Skip(size * page)
        .Take(size);

Problem is, how can I get the total number of results before the Take part?
I was thinking of:
var t = (from p in db.JK_Prizes
            join c in db.JK_Calendars on p.calendar_id equals c.calendar_id
            join ch in db.JK_Challenges on c.calendar_id equals ch.calendar_id
            join ca in db.JK_ChallengeAnswers on ch.challenge_id equals ca.challenge_id
            join cr in db.JK_ChallengeResponses on ca.challenge_answer_id equals cr.challenge_answer_id

            where
                p.prize_id.Equals(prizeId)
                && ch.day >= p.from_day && ch.day <= p.to_day
                && ca.correct.Equals(true)
                && ch.day.Equals(day)

            select cr.subscriber_id)
        .Count();

but that will do the query all over again...
anyone has suggestions on how can I do this effectively ?

A: If you take a query as such:
var qry = (from x in y
           select x).Count();

...LINQ to SQL will be clever enough to make this a SELECT COUNT query, which is potentially rather efficient (efficiency will depend more on the conditions in the query). Bottom line is that the count operation happens in the database, not in LINQ code.

A: Writing my old comments :Well i was facing the same issue some time back and then i came up with LINQ to SP =). Make an SP and drop that into your entities and use it.you can get write Sp according to your need like pulling total record column too. It is more easy and fast as compare to that whet you are using wright now.

A: You can put count for query logic as well as, see the sample as below:
 public int GetTotalCountForAllEmployeesByReportsTo(int? reportsTo, string orderBy = default(string), int startRowIndex = default(int), int maximumRows = default(int))
        {
            //Validate Input
            if (reportsTo.IsEmpty())
                return GetTotalCountForAllEmployees(orderBy, startRowIndex, maximumRows);

            return _DatabaseContext.Employees.Count(employee => reportsTo == null ? employee.ReportsTo == null : employee.ReportsTo == reportsTo);
        }


text:
Q: How to join two tables matching for unique column ID? Here is my code below.
select cserv.cust_id,serv.service_id,serv.service_name,cserv.cust_id,cserv.channel_id,cserv2.cust_id,cserv2.channel_id
from services as serv
left join cust_services as cserv on serv.channel_a=cserv.channel_id
left join cust_services as cserv2 on serv.channel_b=cserv2.channel_id
where cserv.cust_id IS NOT NULL
order by cserv.cust_id

and below is picture of my result which generates by this query.

and below is the image of issue. issue is marked with red color.

I want to remove the highlighted record . How can i do that? Please help me.
below is the pictures of my service table and cust_service tables.
service table :-

cust_service :-

A: I've tested this with your data sets and it appears to provide the output you are looking for:
SELECT MIN(cserv.cust_id) AS cust_id1
      ,MIN(serv.service_id) AS service_id
      ,serv.service_name
      ,MIN(cserv.cust_id) AS cust_id2
      ,MIN(cserv.channel_id) AS channel_id
      ,cserv2.cust_id
      ,cserv2.channel_id
FROM services as serv
    LEFT JOIN cust_services AS cserv ON serv.channel_a=cserv.channel_id
    LEFT JOIN cust_services AS cserv2 ON serv.channel_b=cserv2.channel_id
WHERE cserv.cust_id IS NOT NULL
GROUP BY serv.service_name
        ,cserv2.cust_id
        ,cserv2.channel_id
ORDER BY cust_id1, service_id

Here is the sqlfiddle of the OP and my answer with respective outputs: http://sqlfiddle.com/#!9/74bc16/2
Notice, I changed the name of cust_id fields because they were causing a field ambiguous error since they were both named the same thing.  Now they are labeled cust_id1 and cust_id2 so you can do order and sorting by them.  I also added service_id in the ORDER BY clause so the order in your original example is retained; you may choose to order by something else.


text:
Q: How to embed Youtube live chat whitin github pages I was trying using embed iframe but it actually doesn't work, maybe it is a problem with github pages because it is not in a custom domain.
<iframe width="350px" height="500px" src="https://www.youtube.com/live_chat?v=yourvideoid&embed_domain=yourdomainnamegoeshere.com" ></iframe>

In domain I put these options:

*

*https://lucho19jose.github.io/

*lucho19jose.github.io

*www.lucho19jose.github.io
It throw 404 error


text:
Q: printing data columnwise in same workbook - java poi I am using Java and POI to print some data to excel files. I think I am just missing a small logic to solve this question. I have data stored in array lists in following format:
a = [1,2,3] // arraylist
b = [4,5,6] // arraylist
c = [7,8,9] // arraylist

I want to print this data columnwise to excel file in below given format:
1 | 4 | 7
2 | 5 | 8
3 | 6 | 9

The code that I am using is as below:
public final_out = new FileOutputStream(new File(final_output_path));

public XSSFWorkbook workbook = new XSSFWorkbook();

public XSSFSheet sheet = workbook.createSheet("data_vertical_final");

public Row row;

for (int i=0; i < a.size(); i++) {

     String value = a.get(i);
     row = sheet.createRow(i);
     Cell cell = row.createCell(13);
     cell.setCellValue(value);

}

for (int i=0; i < b.size(); i++) {

     String value = b.get(i);
     row = sheet.createRow(i);
     Cell cell = row.createCell(15);
     cell.setCellValue(value);

}

for (int i=0; i < c.size(); i++) {

     String value = a.get(i);
     row = sheet.createRow(i);
     Cell cell = row.createCell(17);
     cell.setCellValue(value);

}

workbook.write(final_out);
workbook.close();
final_out.close();

Error I am getting:
There is no error, but everything is getting overwritten in new excel file and the final output looks broken. Do I need to make new workbooks for every loop? or there is something I am missing.
P.S:
The data that is shown below is just an example. Some of my original files that I am using are between 1000 to 2000 values or maybe more.
I want to dynamically create the rows and extract the values from arraylists and store it in rows that I created.

A: Create only a.size() rows,
not a.size() squared rows.
Don't overwrite them in your code.
I assume that a.size() == b.size() and b.size() == c.size().
public List<Row> rows = new ArrayList<Row>(a.size());

for (int i=0; i < a.size(); i++) {
    rows.add(sheet.createRow(i));
}

for (int i=0; i < a.size(); i++) {
     String value = a.get(i);
     Cell cell = rows.get(i).createCell(13);
     cell.setCellValue(value);
}

for (int i=0; i < b.size(); i++) {
     String value = b.get(i);
     Cell cell = rows.get(i).createCell(15);
     cell.setCellValue(value);
}

for (int i=0; i < c.size(); i++) {
     String value = a.get(i);
     Cell cell = rows.get(i).createCell(17);
     cell.setCellValue(value);
}

If you already solve the problem:
It would be even cleaner to place a, b and c into one collection and use only one loop to iterate through them (in place of 3 separate loops).
I assume that a is the longest list.
Check this out:
public List<Row> rows = new ArrayList<>(a.size());
for (int i=0; i < a.size(); i++) {
    rows.add(sheet.createRow(i));
}
List<List<String>> alphabet = new ArrayList<>();
alphabet.add(a);
alphabet.add(b);
alphabet.add(c);
for(int i=0; i < alphabet.size(); i++) {
    for (int j=0; j < alphabet.get(i).size(); j++) {
        String value = alphabet.get(i).get(j);
        Cell cell = rows.get(j).createCell(13 + i*2); //<- 13, 15, 17...
        cell.setCellValue(value);
    }
}


text:
Q: Android: How to have a common socket connection to server in all activities I am pretty new to android. How could I make a socket connection to a server which is available to all the activities, instead of me establishing connection to the same server in every activity?
In the MainActivity I have a thread which is running, but this is thread is not accesible by other activities.
public class MainActivity extends Activity implements OnItemSelectedListener {
    private Socket socket;
    private static final int SERVERPORT = 8020;
    private static final String SERVER_IP = "192.168.1.36";

    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         new Thread(new ServerThread()).start();
}

class ClientThread implements Runnable {
    private Socket socket;
    private static final int SERVERPORT = 8020;
    private static final String SERVER_IP = "192.168.1.36";

    @Override
    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            socket = new Socket(serverAddr, SERVERPORT);
        } catch (UnknownHostException e1) {
                e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
 }

How do i make the same connection to server on 192.168.1.36 available to all activities instead of me creating a connection on every activity.
EDIT TO ANSWER
I created a class which stores all the connection parameters
     package com.example.clientmobile2;
 public class DataHolderClass {
 private static DataHolderClass dataObject = null;

 private DataHolderClass() {
 // left blank intentionally
 }

public static DataHolderClass getInstance() {
if (dataObject == null)
    dataObject = new DataHolderClass();
return dataObject;
}
private int server_port=8020;
private String server_ip="192.168.1.33";;

public int get_server_port() {
return server_port;
}

public String get_server_ip() {
return server_ip;
}

}

MainActivity is as follows :-
    public class MainActivity extends Activity implements OnItemSelectedListener {
    private static final int SERVERPORT = DataHolderClass.getInstance().get_server_port();
private static final String SERVER_IP = DataHolderClass.getInstance().get_server_ip();
     public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     }
     public void onClickon(View view) {
    Socket socket = null;
    try{

        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

        socket = new Socket(serverAddr, SERVERPORT);

    //sending the message to the linino as 0 to turn of the light
    PrintWriter out = new PrintWriter(new BufferedWriter(
            new OutputStreamWriter(socket.getOutputStream())),
            true);
    out.println("0");
    }
    catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        socket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
   }

The application crashes everytime i click on the button associated with onClickOn.
Error Log
05-08 10:38:40.171: E/AndroidRuntime(12909): FATAL EXCEPTION: main
05-08 10:38:40.171: E/AndroidRuntime(12909): Process: com.example.clientmobile2, PID: 12909
05-08 10:38:40.171: E/AndroidRuntime(12909): java.lang.IllegalStateException: Could not execute method of the activity
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.view.View$1.onClick(View.java:3841)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.view.View.performClick(View.java:4456)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.view.View$PerformClick.run(View.java:18462)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.os.Handler.handleCallback(Handler.java:733)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.os.Handler.dispatchMessage(Handler.java:95)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.os.Looper.loop(Looper.java:136)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.app.ActivityThread.main(ActivityThread.java:5102)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at java.lang.reflect.Method.invokeNative(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at java.lang.reflect.Method.invoke(Method.java:515)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at dalvik.system.NativeStart.main(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909): Caused by: java.lang.reflect.InvocationTargetException
05-08 10:38:40.171: E/AndroidRuntime(12909):    at java.lang.reflect.Method.invokeNative(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at java.lang.reflect.Method.invoke(Method.java:515)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.view.View$1.onClick(View.java:3836)
05-08 10:38:40.171: E/AndroidRuntime(12909):    ... 11 more
05-08 10:38:40.171: E/AndroidRuntime(12909): Caused by: java.lang.NullPointerException
05-08 10:38:40.171: E/AndroidRuntime(12909):    at com.example.clientmobile2.MainActivity.onClickon(MainActivity.java:331)

A: you can create a singleton class and define that object there or either use application class which is provided by android and then define your socket object there.Then your object will accessible in all activities.  read here how to use Application class.

A: here in this case you have to use SINGLETON CLASS.from your first screen you have to set the creditiontials then you have yo get them at any screen.you can use the  below code:
public class DataHolderClass {
private static DataHolderClass dataObject = null;

private DataHolderClass() {
    // left blank intentionally
}

public static DataHolderClass getInstance() {
    if (dataObject == null)
        dataObject = new DataHolderClass();
    return dataObject;
}
    private int server_port;
private String server_ip;

    public String get_server_port() {
    return server_port;
}

public void set_server_port(String server_port) {
    this._server_port = server_port;
}

    public String get_server_ip() {
    return server_ip;
}

public void set_server_ip(String server_ip) {
    this.server_ip= server_ip;
}

}

now in your activity you have to set the values like below:
DataHolderClass.getInstance().set_server_port("8020");
DataHolderClass.getInstance().set_server_ip("192.168.1.36");

now to get the values use below code:
 String a = DataHolderClass.getInstance().get_server_port();
String b = DataHolderClass.getInstance().get_server_ip();


text:
Q: Returning the data from a deferred? I have a class that uses Google's places service. A user can enter an address and Google will return information about it.
Later on I wish to find out lat and lng coordinates on this place, so I have this method which utalizes Google's places service to get the coords.
I return a deferred as this may take some time.
p.getLatLong = function() {

    var dfd = $.Deferred();

        this.placesService.getDetails({
            reference: this.pacReference
        }, function(details, status){
            if(details){
                dfd.resolve({'lat' : details.geometry.location.lat(), 'lng' : details.geometry.location.lng()});
            }
            else{
                dfd.reject();
            }
        })
    }

    return dfd;
};

I want to be able to access the above method and just return the coords or null (if the dfd is rejected) but the method returns a deferred.
How can I just return the result of the dfd rather than the dfd itself?
I do not wish to have to call:
this.geo.getLatLng().done(function(data){console.log(data})

But something like this:
console.log(this.geo.getLatLng());

A: I get your point, though promises exist for a reason, the reason here being the asynchronous nature of asking for data.
There is a way, I used to think it was good before I understood the goal of promises. You could return the reference of the 'to be populated' data, but then, when will you be able to use it? Are you planning on polling the state of an object...? I hope not, seriously stick to promises you will avoid a lot of problems for small profit of a bunch of keystrokes.

A: Deferred objects are meant to allow the thread to continue while long running operations proceed in the background. They serve a specific purpose, and shouldn't work the way you describe by design.
Remember that JavaScript is single-threaded. That means that if you pause the thread waiting for a long operation to complete, the entire page/UI will be frozen as well.

That warning stated, you could potentially accomplish what you want by wrapping all this into your own closure with a loop that checks to see if the process completes.
Please note this is dangerous, will freeze the page, and should be avoided. It is here for academic reasons only.
var getGetLatLng = (function () {
    var running = false;

    return function () {
        var latlng;

        //While we haven't instructed the loop to break.
        while (!breakLoop) {
            //If we haven't instructed the API call to execute in this iteration of the loop.
            if (!running) {
                //On next iteration, tell it we are already running, to prevent multiple requests being fired.
                running = true;

                //Your logic here for getLatLng
                this.geo.getLatLng()
                    //When it completes successfully, set latlng
                    .done(function (data) {
                        latlng = data;
                    })
                    //always break the loop when HTTP completes.
                    .always(function () {
                        breakLoop = true;
                    });
            }
        }

        //Return latlng - it could be undefined if there was an error.
        return latlng;
    };
})();

You could wrap this same structure around your original p.getLatLng function body too. Again, I don't recommend it.


text:
Q: repeating functions just changing one var This is what i have, and it works but i wonder if it could be easier?
$('.item1').click(function(){
    $('.otheritem').animtate('left':'0');
});
$('.item2').click(function(){
    $('.otheritem').animtate('left':'100');
});
$('.item3').click(function(){
    $('.otheritem').animtate('left':'200');
});
// etc etc etc

I have a file that uses php foreach and generates a couple of items.
foreach($images as $image)
{
    $i++;
    echo "$i";
}

So the more images the more items, so if you click on one of the items generated by the php it will determine the position of  .otheritem

A: If all items are fixed width, you can calculate the position based on it's position in the list.
e.g.
$('.buttons').click( function() {
    $('.otheritem').animate('left', $(this).index() * 100);
});

A: You could embed the changing value inside a data property on the element, and just give all the elements the same selector -
$animLeft = $i * 100;
echo "$i";

Now your jQuery can access all of the elements by the same name and extract the value for the animation :
$('.item').on('click',function(){
  var animateValue = $(this).data('animleft');
  $('.otheritem').animtate('left':animateValue);
});

References -

*

*$.data()

A: Something like this?
$('.item').each(function(i) {
    $(this).click(function() {
        $('.otheritem').animate('left', i * 100);
    });
});


text:
Q: Proof corollary of the theorem about supersolubility A subgroup $ K $ of $ G $ is called almost maximal if $ K $ is a maximal subgroup of $ G $ or the index of $ K $ in $ G $ is of prime power order.
This is the theorem in the article and proved : Suppose that $ H \unlhd G $ such that $ G/H $ is supersoluble. Suppose that there is an element $ y \in H $ such that $ H = \langle y \rangle L $ for any almost maximal subgroup  $ L $ of $ H $; then $ G $ is supersoluble.
Now prove this corollary of above theorem: Suppose that $ H \unlhd G $ such that $ G/H $ is supersoluble. If all the Sylow subgroups of $ H $ are cyclic, then $ G $ is supersoluble. Particularly, if $ H $ is a square free subgroup, then $ G $ is supersoluble. How prove this corollary by above theorem ?

A: I can prove the corollary directly, without using the theorem. Use induction on $|H|$ - result is clear if $|H|=1$. Let $N$ be a minimal normal subgroup of $G$ with $N \le H$. Then, since $H$ is soluble, $N$ is elementary abelian but, since all Sylow subgroups of $H$  are cyclic, $N$ must be cyclic. Now by induction applied to $H/N \unlhd G/N$, $G/N$ is supersoluble. Then $N$ cyclic implies $G$ is supersoluble.


text:
Q: Window function to find differences in String I have a table like the below in MS SQL Server with the first two columns, I would like to apply some kind of window function partitioned by fund_name to output the differences in security_name to give the desired_output?
Is there such a way? I could maybe try reading the data into python but can't think of solution using either.
There will be no consistency in the pattern of desired_output.

Fund_Name
Security_Name
Desired_Output

Morgan Stanley Investment Sust Asn Eq Fd
Morgan Stanley Investment Funds - Sustainable Asian Equity Fund Z
Z

Morgan Stanley Investment Sust Asn Eq Fd
Morgan Stanley Investment Funds - Sustainable Asian Equity Fund B
B

Morgan Stanley Investment Sust Asn Eq Fd
Morgan Stanley Investment Funds - Sustainable Asian Equity Fund I
I

Morgan Stanley Investment Sust Asn Eq Fd
Morgan Stanley Investment Funds - Sustainable Asian Equity Fund A
A

MS INVF Emerging Markets Equity Fund
Morgan Stanley Investment Funds - Emerging Markets Equity Fund Z
Z

MS INVF Emerging Markets Equity Fund
Morgan Stanley Investment Funds - Emerging Markets Equity Fund I
I

MS INVF Latin American Equity Fund
Morgan Stanley Investment Funds - Latin American Equity Fund A
A

MS INVF Latin American Equity Fund
Morgan Stanley Investment Funds - Latin American Equity Fund I
I

MS INVF Latin American Equity Fund
Morgan Stanley Investment Funds - Latin American Equity Fund B
B

MS INVF Latin American Equity Fund
Morgan Stanley Investment Funds - Latin American Equity Fund C
C

MS INVF Latin American Equity Fund
Morgan Stanley Investment Funds - Latin American Equity Fund Z
Z

MS INVF US Growth Fund
Morgan Stanley Investment Funds - US Growth Fund A
A

MS INVF US Growth Fund
Morgan Stanley Investment Funds - US Growth Fund AH (EUR)
AH (EUR)

MS INVF US Growth Fund
Morgan Stanley Investment Funds - US Growth Fund NH (EUR)
NH (EUR)

MS INVF US Growth Fund
Morgan Stanley Investment Funds - US Growth Fund BH (EUR)
BH (EUR)

MS INVF US Growth Fund
Morgan Stanley Investment Funds - US Growth Fund Z
Z

A: using the pattern provided, you can measure if the length of the last term is equal to 1, then append it, else check if it's in brackets (), then append the slice of the last 2 string splits, else apply some additional logic you have, like so:
import pandas as pd

mydata=pd.read_csv("so.csv")
out=[]
for security in mydata['Security_Name']:
    if len(security.split()[-1])==1:
        out.append(security.split()[-1])
    elif security[-1]==")":
        out.append(security.split()[-2:])
    else:
        out.append("add new logic here")
mydata["new_logic"]=pd.DataFrame(out)
print(mydata)


text:
Q: Pressure drop in water fountains In first grade, my class made a list of things that our school could improve on. One of the things on the list was to increase the water pressure in the drinking fountains because it was very poor and made it hard to drink from. Recently, I noticed that the drinking fountain at my church had begun to lack in pressure although it had used to work just fine. This raised two puzzling questions to me: Why does the water pressure in a drinking fountain sometimes drop over time? And: how would a mechanic/technition go about fixing this?
To clarify, in both instances the problem was consistent and not caused by another event like running sprinklers that "siphened" the water supply/pressure.

A: Old pipes get rusted or otherwise clogged by different stuff, such as salts. This will increase the friction of the water flow, resulting in a reduced pressure. The longer the pipes the larger the effect. I do not see any other solutions than to change the clogged pipes, assuming first that you can find which one are the clogged ones (iron pipes instead of copper pipes are usually the problem). My suggestion, replace them with plastic pipes with shark bite unions (sold in Home depot) that do not require soldering. Ir can be a fun school project for any age above about 10.

A: There is a pump somewhere upstream in the system to provide water pressure. Apparently it cannot maintain exactly needed pressure but alternatively goes start-stop depending on actual pressure. Once the pump started it delivers pressure as 'high' adjusted, then stops. Then pressure slowly gets down as the water is taken out so when pressure reaches certain 'low' level then the pump starts again. That's why pressure is maintained not very precisely but within some span. It can be improved if you reduce span between 'high' and 'low' adjustments but that will cause more often pump start-stops that is not good for its life.

A: When you say "pressure", I think you are probably referring to something like "the height to which the water shoots when you operate the fountain". There are actually two things that affect this:

*

*The pressure of the water supply.

*Any obstruction to the pipe (such as corrosion).

As a thought experiment, imagine that you have a completely clear pipe except for an almost complete obstruction ten feet upstream of the fountain. When no water is flowing, the pressure is the same upstream and downstream of the obstruction. When you press the button, water will shoot out of the fountain at that pressure, but the water won't be immediately replaced, because the obstruction slows the flow. So the pressure on your side of the obstruction will drop, and the flow will slow to a trickle. When you release the button, water will continue to flow (slowly) past the obstruction until the upstream and downstream pressures are identical again. (How long the spurt lasts depends, among other things, on how springy the material pipe is: the more it stretches under pressure, the more water it will be able to store on your side of the obstruction).
Of course in real life whatever is obstructing your pipe will be less extreme, and distributed more along the length of the pipe. All the same, you will be able to distinguish between low pressure or an obstructed pipe by seeing to what extent you are getting "spurt, then slow" behaviour.
If your drinking fountain shoots water up into your eye but almost immediately drops to a trickle, an obstruction is the cause.
An indication of low pressure of the water supply as the cause is that the pressure (and so the flow) is different at different times. This depends where your water comes from. If there are pumps directly in the supply then they will pump until a desired pressure is reached, then stop until the pressure drops. That will give you some fluctuation. If you are being fed directly from a tank on the roof (cistern plus ball valve) then the pressure will vary hardly at all. If you are being fed from a distant tank shared with a lot of other water users, the pressure will depend on how many other people have their taps on at the same time as you. You say you have eliminated the last possibility in your case, but I include it here for the benefit of others in similar situations.

A: All the above answers could be correct but really,
the answer is simple.
Water fountains with filters have that exact symptom when the filter needs to be replaced. In schools, the fountains are generally those filtered fountains which periodically will run into this problem.


text:
Q: Sum of all rows by column in postgres This is my table
How do i  make it that i sum all the rows in pca by peid?
The final result should be
pea| pca | peid
----------------
 5 |  1  |  1
10 |  6  |  3

My query for the first table(the image) is:
select peA, pca, peID
from ( select PE."Amount" as peA, PC."Amount" as pcA, PE."Id" as peID from "ProductEntry" as PE
         join "User" U on U."Id" = PE."UserId"
         left join "ProductConsummation" PC on PC."ProductEntryId" = PE."Id"
    where "UserId" = 1 and PE."Status" = 'Active' and PE."ProductType" = 'Signature'
group by PE."Amount", PC."Amount", PE."Id") as "PUP";

A: If you simply would like to replace null values by 0, you can use COALESCE:
SELECT
pe.amount, COALESCE(pc.amount,0)
FROM productentry AS pe
JOIN users u ON u.id = pe.userid
LEFT JOIN productconsummation pc ON pc.productentryid = pe.id
WHERE userid = 1 AND pe.status = 'Active' and pe.producttype = 'Signature'
GROUP BY pe.amount, COALESCE(pc.amount,0)

Take care that this must both be done within the select part and within the group by part of your query. Also take care that you need to write '0' instead of 0 in case your amount column is of kind varchar.
Furthermore, I generally recommend to only write SQL key words in UPPER CASE and the rest of your queries or commands in lower case. And if possible, using SQL key words as table names or column names should be avoided. So in your case, the table "user" should be renamed to "users", "username" or similar. I have applied these suggestions to my example, but of course, it's your decision if you follow them.


text:
Q: How safe is it to import a module multiple times? I've been wondering this for a while: Is it guaranteed to be safe to import a module multiple times? Of course, if the module performs operating systems things like write to files or something, then probably not, but for the majority of simple modules, is it safe to simply perform imports willy-nilly? Is there a convention that governs the global state of a module?

A: Yes, you can import module as many times as you want in one Python program, no matter what module it is. Every subsequent import after the first accesses the cached module instead of re-evaluating it.

A: Importing the os module under ten thousand different names doesn't seem to give any problems.
for i in range(10000):
    exec("import os as foo%i" % i)

for i in range(10000):
    exec("foo%i.getcwd()" % i)

With the imports in different classes:
for i in range(10000):
    exec("""class FooClass%i:
    import os as foo%i
    print foo%i.getcwd()""" % (i,i,i))

Both run without problems. Not a guarantee of course, but at least it appears you don't run into immediate practical problems.


text:
Q: Query by Date in Java Spring Data JPA ETA: TL;DR:
orderRepo.save() converts the date (input):
Wed Jun 22 00:00:00 CDT 2022

into this (output):
2022-06-22 05:00:00.000

I am wondering how I can convert the input into the output, in Java, without putting it in the database first.

Original post:
I have a website that has been working with java.utils.Date for over a year now. I can use the angular date picker which makes an order object, sends it to java, repo.save() puts it in the database, pulls it back to angular and displays the date just fine.
I am now trying to query only a specific date from the DB.
@Query("SELECT o FROM Order o JOIN o.boats b WHERE b.date = ?1")
    Set<Order> findByDate(Date date);

However this keeps turning up empty even though there are dates that match in the DB
How do I fix my query to grab those dates?

I know, "Don't use java.util.Date" but that is the system I am working with and I don't have time at the moment to convert everything to LocalDate. I will at some point but I am already quite behind on current tasks.
Thanks!!

A: This method is a jpql
I would have used another way.
Interface call method or Query methods
By calling a method request in the interface, we need our user interface to inherit the interface specified in the Spring Data Jpa:
public interface UserDao extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User>

The prerequisite for using these methods is that the entity class you define should be marked with appropriate annotations.
@Entity //Mark this as an entity class
@Table(name = "tbl_user") //Setting the mapping relationship between the entity class and the public class User table {

@Id //Declare this attribute as the primary key
@GeneratedValue(strategy = GenerationType.IDENTITY) //Primary key generation strategy, self-reinforcing
@Column(name = "user_id") //The specified attribute corresponds to the column name of the database table
private Integer userId;

@Column(name = "user_name")
private String userName;

@Column(name = "user_address")
private String userAddress;

@Column(name = "user_salary")
private Double userSalary;

//... setter method toString
}


text:
Q: Connect IBM Cognos to SQL Server Currently i'm using IBM Cognos Express, database from SQL Server 2008.
But error has occured when i try to retrieving database from SQL Server to IBM Cognos.
How to connect IBM Cognos Express to SQL Server 2008?
Thanks.

A: What version of Cognos Express (9.0, 9.5)? Here are some generic instructions in the meantime;

*

*Start SQL Server Configuration Manager

*Go to Client Protocols and enable TCP/IP and Named Pipes

*Go to Protocols for SQLEXPRESS and enable TCP/IP and Named Pipes

*Then double click TCP/IP to go into its properties, click IP addresses tab, scroll to bottom for IPAll group

*Make TCP dynamic ports setting to be blank

*Make TCP port to be 1433

*Restart SQLExpress service

*In Cognos configuration you can then select SQL Server and COMPUTERNAME\SQLEXPRESS for database settings


text:
Q: Lining up different sized divs through different zoom levels Here is an example of what I am doing: http://jsfiddle.net/wFjXD/
At a certain zoom level ( the default on my machine ), the top 2 divs have the same width as the bottom 10.
This is because I set the width in pixels, each small div has a width of 20px and a 1px border. The larger divs have a width of 108 px which makes each long div line up with 5 of the small divs.
The problem is that if you zoom in or out using ctrl + or ctrl - in the browser, all of this changes and the divs will no longer line up.
Is there a css fix to maintain the same relative sizes through different zoom levels?
Or is there another best practice way to accomplish what I am trying to do?

A: If you want the proportion to stay the same, use % instead of px.
Thats the best I can think of for your problem. Although it'd have to be a fixed number of children and you'd have to wrap them appropriately.
To give you an idea...


text:
Q: Repetição de palavras Estou desenvolvendo um algoritmo que canta a música do elefante, acredito que todos conheçam. Quem não conhece, funciona da seguinte forma:

a) Para o primeiro elefante, escrever no singular.
b) Para o segundo elefante em diante escrever elefantes.
c) Sempre que a quantidade de elefantes for impar escrever: X
  elefantes incomodam muita gente!, onde X é a quantidade de elefantes.
d) Sempre que a quantidade de elefantes for par, repetir a palavra
  incomodam pela metade da quantidade de elefantes existentes, por
  exemplo, 6 elefantes incomodam, incomodam, incomodam muito mais!.

Já existe aqui no SOpt a seguinte pergunta que aborda o mesmo assunto: Função recursiva com strings - Python. Entretanto eu não desejo utilizar funções para resolver este problema, pois como estou aprendendo a linguagem ainda, entendo que preciso preencher algumas lacunas no meu conhecimento antes de começar a utilizar funções.
O código está aqui:
a = int(input("Digite a quantidade de elefantes: "))
for i in range(1,a):
    if i == 1:
        print("{} elefante incomoda muita gente.".format(i))
    if i % 2 == 0 and i > 1:
        print("{} elefantes incomodam muito mais.".format(i))
    if i % 2 != 0 and i > 1:
        print("{} elefantes incomodam muita gente.".format(i))

Minha dúvida é a seguinte: Como vocês podem perceber, o código que escrevi não faz essa parte do problema:

repetir a palavra incomodam pela metade da quantidade de elefantes existentes

A dúvida é a seguinte: Que função posso utilizar para fazer essa repetição?
Tentei concatenar, mas não deu certo. Tentei a função join(), mas confesso que não entendi muito bem a sintaxe quando li a documentação.

A: Um objeto do tipo string, no Python, permite ser multiplicado por um inteiro gerando uma nova string sendo a primeira repetida várias vezes. Veja:
>>> 'incomodam ' * 3
incomodam incomodam incomodam

Assim, quando o valor for par, basta adicionar essa string no texto:
if i % 2 == 0 and i > 1:
    print("{} elefantes {}muito mais.".format(i, 'incomodam ' * (i//2)))

Desta forma, seu código produzirá:
Digite a quantidade de elefantes: 7
1 elefante incomoda muita gente.
2 elefantes incomodam muito mais.
3 elefantes incomodam muita gente.
4 elefantes incomodam incomodam muito mais.
5 elefantes incomodam muita gente.
6 elefantes incomodam incomodam incomodam muito mais.

Perceba que, inclusive, utilizei i // 2 e não apenas i / 2; isso porque a divisão i/2 retornará um float, enquanto i//2 retornará um inteiro. A string permite ser multiplicada por um inteiro, não por um float. O mesmo resultado seria obtido se multiplicasse por int(i/2).
Também é importante observar os parenteses: 'incomodam ' * (i//2). Eles servirão para definir como prioridade a operação de divisão e não a de multiplicação. Por possuírem naturalmente a mesma prioridade, o interpretador iria analisar a expressão da esquerda para a direita, efetuando primeiro a multiplicação e depois a divisão. Neste caso, você teria 'incomodam incomodam incomodam ' // 2, o que não faz sentido algum (inclusive daria erro dizendo unsupported operand type(s) for /: 'str' and 'int').
Lembre-se também que range(1, n) gerará o conjunto [1, n-1], por isso quando informado 7 elefantes, a saída chega apenas em 6. Isso fará menos sentido ainda quando a entrada for 1, pois não haverá saídas no programa. Talvez seja interessante corrigir para range(1, a+1).


text:
Q: Find matches for two columns on two sheets google script Im am trying to match 2 columns (A:B) in sheet1 with 2 columns in sheet2 (A:B) and if there is a match, copy contents of column C matching row in sheet1 to matching row in sheet2.
I've tried to adapt several scripts without success.  The code below comes closest to my requirements, but with my limited knowledge of script I haven't been able to adapt it to my exact needs.
Sheet1
A       B               C
Week    Rotation    Working
Week1   11          In
Week1   5           In
Week1   4           In
Week1   3           In
Week1   3           Off
Week1   7           Off

Sheet2
A       B               C
Week    Rotation    Working
Week1   6
Week1   5
Week1   4
Week1   3
Week1   3
Week1   11              (In should be copied to here)

My code:
function MatchColumns(){
  // gets spreadsheet A and the range of data
  var sheetA
=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Testa");
  var dataA = sheetA.getRange(2, 1, sheetA.getLastRow(),
2).getValues();

   // gets spreadsheet B and the range of data
  var sheetB =
 SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test2");
  var dataB = sheetB.getRange(2, 1, sheetB.getLastRow(),
 1).getValues();

  // Added
  var res = [];
  for (var b in dataB) {
    for (var a in dataA) {
       if (dataA[a][0] == dataB[b][0]) res.push([dataA[a][3]]);
     }
     if (b != res.length - 1) res.push([""]);
   }
   sheetB.getRange(2, 2, res.length, res[0].length).setValues(res);

A: *

*Note that JavaScript is one of the many languages that use 0-base indexing. So res.push([dataA[a][3]]) is placing the 4th value from the row into the result array, i.e. Column D.

*Your dataA and dataB variables don't actually include the column C data, as you initialized them with only 2 columns of data. So dataA[a][2] and dataA[a][3] are both undefined.

*You probably don't want to collect these new values into an array via push, as this will lose the correlation between which row you matched in A & B, and which row you write into. To avoid losing existing information in column C, you need to read it from sheet 2 and assign to the specific index:
var destC = sheet2.getRange(2, 3, sheet2.getLastRow() - 1, 1).getValues();
/** Find matched rows */
   ...
  destC[b][0] = dataA[a][2];
 ...
// Lastly, write values
sheet2.getRange(2, 3, destC.length, 1).setValues(destC);

A: Try using a nested for to iterate through the Values in Sheet1 and Sheet2 and compare them with
function MatchColumns(){
  // gets spreadsheet A and the range of data
  var sheetA = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var dataA = sheetA.getRange(2, 1, sheetA.getLastRow() - 1, 2).getValues();

  // gets spreadsheet B and the range of data
  var sheetB = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
  var dataB = sheetB.getRange(2, 1, sheetB.getLastRow() - 1, 2).getValues();

  for (var x = 0; x < sheetA.getLastRow() - 1; x++){
    for (var y = 0; y < sheetB.getLastRow() - 1; y++){
      if (dataA[x][0] == dataB[y][0]){
        if (dataA[x][1] == dataB[y][1]){
          sheetB.getRange(y + 2, 3).setValue(sheetA.getRange(x + 2, 3).getValue());
        }
      }
    }
  }
}

This copies the value of column C in Sheet1 to column C in Sheet2 if the corresponding cells in columns and B match.


text:
Q: How to print fibonacci series and its reverse in a single loop in c or java? the output should look something like this:
0 1 1 2 3 5 8 13..
..13 8 5 3 2 1 1 0
I thought of using two arrays in java and then using Arrays.tostring() on those two arrays to print both values,but still I couldn't solve it in one loop.
Apart from that I tries doing it in this way
int main()
{
   int n,j,c;
   int a=0,b=1;
   printf("enter total no of terms:");
   scanf("%d",&n);
   int arr[n];
   arr[0]=a;
   arr[1]=b;

   printf("%d\t %d\t",arr[0],arr[1]);

    for(j=2;j<=((2*n)-1);j++)
    {
       if(j<=n-1)
       {
          c=a+b;
          arr[j]=c;
          printf("%d\t",arr[j]);
          a=b;
          b=c;
          if(j==n-1)
           printf("\n");

       }
       else
       {
           arr[j]=b;
           printf("%d\t",arr[j]);
           c=a;
           a=b-a;
           b=c;
       }

    }

  getch();
}

This solves my problem but is there any shorter and more efficient method to this question?

A: Start with 3 variables with the values 0, 1 (int num1 = 0; and int int num2 = 1;) and undefined (int num3;). Print 1 and 2.
If you want up to 13 and back, do a loop of 12 times.
Inside the loop, check if the loop has been done 6 times (if index starts at 0, index<6). If yes, insert to num3 the value of num1+num2. If not, insert to num3 the value of
After that, print num3 and move num2 to num1 and num3 to num2 (num1=num2; num2=num3;)


text:
Q: Child components not rendering as expected So i have two child components header and occasionlist.And i want the flow to be like header should be processed first followed by my parent component and then occasionlist component should render.
Here is my entry component app.js.Pusher is configured in app.js to capture events triggered from backend(spring).
    var React=require('react');
var ReactDOM=require('react-dom');
var Pusher=require('pusher-js');
/*var fetch = require('node-fetch');*/
var fetch=require('isomorphic-fetch');
require('es6-promise').polyfill();
var Header=require('./components/header.js').Header;
var OccasionList=require('./components/OccasionList.js').OccasionList;

var App = React.createClass({
  getInitialState: function() {
    return { items: [], holidays: [] };
  },

  componentWillMount: function() {
      alert("in mount")

    this.pusher = new Pusher("ba34e3874d4b87905f36", {
      encrypted: true,
      cluster: 'ap2',
    });
    this.channel = this.pusher.subscribe("doodles");
    this.total = 0;
    alert("in pusher")
  },

  componentDidMount: function() {
      alert("in did")
   this.channel.bind('occasionsAdded', this.occasionsAdded);

   fetch('/holidays',{credentials: 'same-origin'}).then(function(response) {
        return response.json();
    }).then(this.getHolidaysSuccess);

  },
  occasionsAdded: function(occasion) {
       alert("event fired");
       var selectedState=[];
      this.setState({

          selectedState:occasion

      })

      },
  componentWillUnmount: function() {
    // Unbind from channel events
    this.channel.unbind();

    // Unsubscribe from the Pusher channel
    this.pusher.unsubscribe(this.channel);

    // Unregister by assign them to an empty function
    this.getHolidaysSuccess = function() {};

  },

  getHolidaysSuccess: function(response) {

       alert(JSON.stringify(response))

    this.setState({
        holidays: response
    });
  },

  render: function() {
      alert("in render1")

    return (

      <OccasionList occasionlist={this.state.selectedState} />

    );
  }
});

ReactDOM.render(<App />, document.getElementById("app"));

In Header component i am populating the select box with states and on clicking that state my action binds to spring controller and it returns a list of all occasions of that state and fires an event occasionsAdded in app.js written above and updates the occasion list.Now i want this list to be rendered on my occasion child
Header component
var React=require('react');
var ReactDOM=require('react-dom');
var fetch=require('isomorphic-fetch');
require('es6-promise').polyfill();
import {Button} from 'react-toolbox/lib/button';
import {Dropdown} from 'react-toolbox/lib/dropdown';
import Input from 'react-toolbox/lib/input';
import AppBar from 'react-toolbox/lib/app_bar';
import Navigation from 'react-toolbox/lib/navigation';
import Link from 'react-toolbox/lib/Link';

var Header = React.createClass({
      getOccasion: function(evt) {
          alert(evt.target.value)
            fetch('/holidays/occasion', {
              credentials: 'same-origin',
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
               state: evt.target.value

             })
            });
          },
  render: function() {
alert("in header")

var state=this.props.holidays.state;
const AppBarTest = () => (
          <AppBar leftIcon='menu'>
            <Navigation type='horizontal'>
            <select onChange={this.getOccasion}>
              <option value="states">States</option>
              {
                  this.props.holidays.map(function(holidays,i) {
                  return <option key={i}
                    value={holidays.state}>{holidays.state}</option>;
                })
              }
            </select>
            </Navigation>
          </AppBar>
        );

    return (

      <AppBarTest />
     /* <select onChange={this.getOccasion}>
      <option value="states">States</option>
      {
          this.props.holidays.map(function(holidays,i) {
          return <option key={i}
            value={holidays.state}>{holidays.state}</option>;
        })
      }
    </select>*/

    );
  }
});
module.exports.Header = Header;

OccasionList component
    var React=require('react');
var ReactDOM=require('react-dom');
var Pusher=require('pusher-js');
/* var fetch = require('node-fetch'); */
var fetch=require('isomorphic-fetch');
require('es6-promise').polyfill();

var OccasionList=React.createClass({

      render: function() {
          alert("in OccasionList")

        return (

          this.props.OccasionList.map(function(occasionslist,i)
                  {

{occasionslist.images}

                  })

        );
      }

});

module.exports.OccasionList = OccasionList;

As of now after control goes to header and without doing much computations it goes to occasionlist due to which select box in header is not getting loaded and i am not able to select any state.So all i want is

*

*Control should first enter app.js and then it should call first child element header.

*It should process the header element and comes back to app.js,load the new list in state(fetching from spring controller) that has to be passed to Occasionlist element and process this child.
Please guide


text:
Q: Running a server on a separate thread I have a program that retrieves data from a serial device, and then puts it in a server that is accessible by certain programs that can handle this protocol. This server is a third party program that is in the form of an active x control.
The hardware devices require a Thread.Sleep, which is unfortunate. The programs that monitor the server sometimes query the server during the time when a thread is sleeping. This causes it to think the server has failed.
My next idea was to put the server on a separate thread, one solely dedicated for the server tasks. In the UI thread, I run the following code:
        Thread workerThread = new Thread(DoServerWork);
        workerThread.SetApartmentState(ApartmentState.STA);
        workerThread.Start();

In the delegate, I have
    public void DoServerWork()
    {
        rtu = new AxASMBSLVLib.AxASMBSLV();
        rtu.CreateControl();
        rtu.BeginInit();
        rtu.OpenPort();

        while (true)
        {

        }
    }

The problem is that the server starts to work, and then becomes unresponsive in about 5 seconds. My initial thought is that the thread is exiting, but the while(true) should prevent that from happening. Any thoughts?

A: Since you are running this in a Single Threaded Apartment (STA), once that thread hits the empty endless loop, nothing more can happen. An endless loop is generally not a good idea. You should probably use a timer to periodically perform the server work in its OnElapsed event handler.

A:
It is a modbus TCP/IP slave from a third party company. The first option is to "drag and drop" it from the toolbox to the GUI, causing it to be on the UI thread.

Since ActiveX requires STA : exactly the right thing.

I must call Thread.Sleep on the UI thread,

that should never be necessary, here lies your real problem. Never block/sleep he main thread.
Your question should be about how to avoid the Sleep().


text:
Q: Doctrine query memory usage Doctrine appears to be taking well over 4MB of RAM to execute a single, simple query:
print memory_get_peak_usage()."
\n";
$q = Doctrine_Query::create()
    ->from('Directories d')
    ->where('d.DIRECTORY_ID = ?', 5);

$dir = $q->fetchOne();
print $dir['name']." ".$dir['description']."
\n";

print memory_get_peak_usage()."
\n";

/***************  OUTPUT:  **************************

6393616
testname testdescription
10999648

/***************************************************/

This is on a test database with very little data in it - the item that I am querying doesn't contain any data other than what is displayed here.
Is there potentially something wrong with the way I have the system set up, or is this standard memory usage for Doctrine?

A: From what I can see, you code doesn't seem to be wrong...

As a test, I've set up a quick example, with a very simple table (only four fields).
Here is the relevant code :
var_dump(number_format(memory_get_peak_usage()));

$test = Doctrine::getTable('Test')->find(1);

var_dump(number_format(memory_get_peak_usage()));

When doing that, I have this kind of output :
string '1,316,088' (length=9)
string '2,148,760' (length=9)

Considering the table is really simple and that I am only fetching one line, it seems "much" to me too -- but that's quite consistent with what you are getting, and with what I saw on other projects :-(

If you only need to display your data, and not work with it (ie update/delete/...), a solution might be to not fetch complex objects, but only a simple array :
$test = Doctrine::getTable('Test')->find(1, Doctrine::HYDRATE_ARRAY);

But, in this case, it doesn't make much of a difference, actually :-( :
string '1,316,424' (length=9)
string '2,107,128' (length=9)

Only 40 KB of difference -- well, with bigger objects / more lines, it might still be a good idea...

In the Doctrine manual, there is a page called Improving Performance ; maybe it could help you, especially for these sections :

*

*Conservative Fetching

*Free Objects

Oh, btw : I did this test on PHP 5.3.0 ; maybe this can have an impact on the amount of memory used...

A: I agree with romanb's answer - using an OpCode cache is a definite must when using large libs/frameworks.
An example related to OpCode caching
I've recently adopted Doctrine usage with Zend Framework and was curious about memory usage - so like the OP, I created a method using similar criteria to the OPs test and ran it as an overall test to see what ZF + Doctrine's peak memory usage would be.
I got the following results:
Result without APC:
10.25 megabytes
RV David
16.5 megabytes

Result with APC:
3 megabytes
RV David
4.25 megabytes

Opcode caching makes a very significant difference.

A: Well, where does this memory usage come from? As Pascal MARTIN pointed out, array hydration does not make a great difference which is logical concerning that we're only talking about a few records here.
The memory consumption comes from all the classes that are loaded on demand through autoloading.
If you dont have APC set up, then yes, there is something wrong with the way your system is set up. Dont even start to measure performance and expect good results with any large php library without an opcode cache like APC. It will not only speed up the execution but also reduce memory usage by at least 50% on all page loads except the very first one (where APC needs to cache the bytecodes first).
And 4MB with your simple example really smells like no-APC, otherwise it would really be a bit high.

A: Caution with fetchOne() on Doctrine Query. This function call will not append "Limit 1" on SQL
If you just need to get one records from DB, make sure:
$q->limit(1)->fetchOne()

The memory usage is tremendous dropped on large table.
You could see fetchOne() will fetch from DB as a collection first then return the first element.
public function fetchOne($params = array(), $hydrationMode = null)
{
    $collection = $this->execute($params, $hydrationMode);

    if (is_scalar($collection)) {
        return $collection;
    }

    if (count($collection) === 0) {
        return false;
    }

    if ($collection instanceof Doctrine_Collection) {
        return $collection->getFirst();
    } else if (is_array($collection)) {
        return array_shift($collection);
    }

    return false;
}

A: Doctrine provides a free() function on Doctrine_Record, Doctrine_Collection, and Doctrine_Query which eliminates the circular references on those objects, freeing them up for garbage collection.
More info..
To make memory usage a little bit less You can try to use folowing code:

*

*$record->free(true) – will do deep free-up's, calls free() on all relations too

*$collection->free() – this will free all collection references

*Doctrine_Manager::connection()->clean()/clear() – cleanup connection (and remove identity map entries)

*$query->free()

A: I would guess that most of that memory is used up loading Doctrine's classes, not actually for objects associated with the query itself.

*

*Which version of Doctrine are you using?

*Are you using the autoloader?

In Doctrine 1.1, the default autoload behavior is called 'aggressive', which means that it load all of your model classes even if you're only using one or two on any particular request. Setting that behavior to 'conservative' would reduce memory usage.

A: I have just did "daemonized" script with symfony 1.4 and setting the following stopped the memory hogging:
sfConfig::set('sf_debug', false);


text:
Q: Take column average of one file, repeat for all .txt files, write all averages to one file in python I have approximately 40 *.txt files, which all contain two columns of data - they have been converted to str format from a previous script and are space delimited. I would like to take the average of the second column for each .txt file, and then put all the averages into one output file. They also need to be read in numerical order, eg file1.txt, file2.txt.
I have the following scripts at the moment a) to read in the last line of all .txt files and b) to take the average of one file, but when I try to combine them I either get an error saying that it cannot convert the string to a float or that the list index is out of range. I've also tried to do the line.strip() method to confirm that there are no blank lines in the .txt file to sort out the latter problem, to no avail.
a) code that reads in the last line of all .txt files:
import sys
import os
import re
import glob

numbers = re.compile(r'(\d+)')
def numericalSort(value):
    parts = numbers.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts

list_of_files = glob.glob("./*.txt")

for file in sorted(list_of_files, key=numericalSort):
    infiles =  open(file, "r")

    outfile = open("t-range","a")

    contents = [""]
    columns = []

   counter = 0

   for line in infiles:
        counter += 1
        contents.append(line)

    for line in contents:
        if line.startswith("20000"):
            columns.append(float(line.split()[1]))
            print columns

    counter1 = 0
    for line in columns:
        counter1 += 1
      outfile.write(','.join(map(str,columns))+"\n")

infiles.close()
outfile.close()

b) script that takes average value of one file:
data = open("file.txt","r").read().split()
s = sum ([float(i) for i in data])
average = s / len(data)

c) combined script
import sys
import os
import re
import glob

numbers = re.compile(r'(\d+)')
def numericalSort(value):
    parts = numbers.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts

list_of_files = glob.glob("./totalenergies*")

for file in sorted(list_of_files, key=numericalSort):
    infiles =  open(file, "r")
    outfile = open("t-range","a")

    contents = [""]
    columns = []

    counter = 0

    for line in infiles:
        counter += 1
        contents.append(float(line.split()[1]))

        contents = ([float(i) for i  in contents])
        s = sum(contents)
        average = s / len(contents)
        columns.append(average)

        counter1 = 0
        for line in columns:
            counter1 += 1
            outfile.write("\n".join(map(str,columns)) + "\n")

infiles.close()
outfile.close()

This last part give an error of could not convert string to float - the traceback shows there is a problem with contents = ([float(i) for i  in contents])

A: This is the line that is giving you the error:
outfile.write("".join(map(str,columns)+"\n"))

When you read the Traceback error, the last part will usually show you the line number in your script that generated the issue, so you should check that first.
The way the line currently reads, +"\n" is part of the join function, when it should be part of the write method:
outfile.write("".join(map(str,columns)) + "\n")

If your intention was to write each average from columns on a new line, and also insert a new line at the end of the list, you need this:
outfile.write("\n".join(map(str,columns)) + "\n")

More: http://docs.python.org/2/library/stdtypes.html#str.join


text:
Q: How to update a customized object in a public api in angular? I fetch data from json.typicode.com that is the public fake rest api and convert that json into object by getting my required number of fields now if I want to update that object would there be any mismatch for type or something or I need to perform anything extra?
I have an interface called User with certain number of fields
export interface  User {
    id: number;
    email: string;
    name: string;
    phone: string;
    username: string;
}

I am fetching data from fake Rest api that is
public getUsers():Observable<User[]>{
    return this.http.get<User[]>("https://jsonplaceholder.typicode.com/users");
}

so the above code is written in a service which I inject in my ts file
if you will hit https://jsonplaceholder.typicode.com/users in browser you will get the Json Objects like below
{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },

I am able to map the Data by using the Map function and getting only those fields which I want.
But now If I want to update users the problem would be how to update the Data with my custom Object that is different from the api json?

A: Its possible with the scenario I am working with the fake Rest api one just need to update the particular fields and can pass the custom object to the service for update no conversion is needed..!!
here is the code
public updateUser(user:User):Observable<User>{
  return this.http.put<User>("https://jsonplaceholder.typicode.com/users/"+user.id,user);
}

So if the object is of type say the interface in the question then one must only need to update the required fields and need to pass in the service and can retrieve for the same as
this._usersService.updateUser(elementObj).subscribe(user=>{
      console.log(user)
    });

This will get you the object of updated Users..!!
Hope it could help the upcoming newbies..!!


text:
Q: Error in substrates' "use macros in a custom pallet" tutorial I'm currently trying substrate tutorial, but it got stack. Please give me an advice.
Following the "use macros in a custom pallet" tutorial, I coded lib.rs file like this.
#![cfg_attr(not(feature = "std"), no_std)]
pub use pallet::*;

#[frame_support::pallet]
pub mod pallet {
    use frame_support::pallet_prelude::*;
    use frame_system::pallet_prelude::*;
    use sp_std::vec::Vec; // Step 3.1 will include this in `Cargo.toml`

    #[pallet::config]
    pub trait Config: frame_system::Config {
        type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
    }
    #[pallet::event]
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
    pub enum Event<T: Config> {
        ClaimCreated(T::AccountId, Vec<u8>),
        ClaimRevoked(T::AccountId, Vec<u8>),
    }
    #[pallet::error]
    pub enum Error<T> {
        ProofAlreadyClaimed,
        NoSuchProof,
        NotProofOwner,
    }
    #[pallet::pallet]
    #[pallet::generate_store(pub(super) trait Store)]
    pub struct Pallet<T>(_);

    #[pallet::storage]
    pub(super) type Proofs<T: Config> = StorageMap<_, Blake2_128Concat, Vec<u8>, (T::AccountId, T::BlockNumber), ValueQuery>;
    #[pallet::hooks]
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
    #[pallet::call]
    impl<T: Config> Pallet<T> {
        #[pallet::weight(1_000)]
        pub fn create_claim(
            origin: OriginFor<T>,
            proof: Vec<u8>,
        ) -> DispatchResult {
            let sender = ensure_signed(origin)?;
            ensure!(!Proofs::<T>::contains_key(&proof), Error::<T>::ProofAlreadyClaimed);
            let current_block = <frame_system::Pallet<T>>::block_number();
            Proofs::<T>::insert(&proof, (&sender, current_block));
            Self::deposit_event(Event::ClaimCreated(sender, proof));
            Ok(())
        }
        #[pallet::weight(10_000)]
        pub fn revoke_claim(
            origin: OriginFor<T>,
            proof: Vec<u8>,
        ) -> DispatchResult {
            let sender = ensure_signed(origin)?;
            ensure!(Proofs::<T>::contains_key(&proof),Error::<T>::NoSuchProof);
            let (owner, _) = Proofs::<T>::get(&proof);
            ensure!(sender == owner, Error::<T>::NotProofOwner);
            Proofs::<T>::remove(&proof);
            Self::deposit_event(Event::ClaimRevoked(sender, proof));
            Ok(())
        }
    }
}

Cargo.toml file is like this.
[package]
name = "pallet-template"
version = "4.0.0-dev"
description = "FRAME pallet template for defining custom runtime logic."
authors = ["Substrate DevHub <https://github.com/substrate-developer-hub>"]
homepage = "https://substrate.io/"
edition = "2021"
license = "Unlicense"
publish = false
repository = "https://github.com/substrate-developer-hub/substrate-node-template/"

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [
    "derive",
] }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
frame-support = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.26"}
frame-system = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.26" }
frame-benchmarking = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.26", optional = true }

[dev-dependencies]
sp-core = { default-features = false, version = "6.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.26" }
sp-io = { default-features = false, version = "6.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.26" }
sp-runtime = { default-features = false, version = "6.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.26" }

[dependencies.sp-std]
default-features = false
git = 'https://github.com/paritytech/substrate.git'
branch = 'polkadot-v0.9.26'

[features]
default = ["std"]
std = [
  "sp-std/std",
    "codec/std",
    "scale-info/std",
    "frame-support/std",
    "frame-system/std",
    "frame-benchmarking/std",
]

runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks"]
try-runtime = ["frame-support/try-runtime"]

And I used command "cargo check -p node-template-runtime". But I got an Error like this.
ensure!(!Proofs::<T>::contains_key(&proof), Error::<T>::ProofAlreadyClaimed);
                      ^^^^^^^^^^^^ function or associated item cannot be called on
`frame_support::pallet_prelude::StorageMap<_GeneratedPrefixForStorageProofs<T>, frame_support::Blake2_128Concat, Vec<u8>, (<T as frame_system::Config>::AccountId, <T as frame_system::Config>::BlockNumber), frame_support::pallet_prelude::ValueQuery>` due to unsatisfied trait bounds

Proofs::<T>::insert(&proof, (&sender, current_block));
             ^^^^^^ function or associated item cannot be called on `frame_support::pallet_prelude::StorageMap<_GeneratedPrefixForStorageProofs<T>, frame_support::Blake2_128Concat, Vec<u8>, (<T as frame_system::Config>::AccountId, <T as frame_system::Config>::BlockNumber), frame_support::pallet_prelude::ValueQuery>` due to unsatisfied trait bounds

ensure!(Proofs::<T>::contains_key(&proof),Error::<T>::NoSuchProof);
                     ^^^^^^^^^^^^ function or associated item cannot be called on `frame_support::pallet_prelude::StorageMap<_GeneratedPrefixForStorageProofs<T>, frame_support::Blake2_128Concat, Vec<u8>, (<T as frame_system::Config>::AccountId, <T as frame_system::Config>::BlockNumber), frame_support::pallet_prelude::ValueQuery>` due to unsatisfied trait bounds

let (owner, _) = Proofs::<T>::get(&proof);
                              ^^^ function or associated item cannot be called on `frame_support::pallet_prelude::StorageMap<_GeneratedPrefixForStorageProofs<T>, frame_support::Blake2_128Concat, Vec<u8>, (<T as frame_system::Config>::AccountId, <T as frame_system::Config>::BlockNumber), frame_support::pallet_prelude::ValueQuery>` due to unsatisfied trait bounds

Proofs::<T>::remove(&proof);
             ^^^^^^ function or associated item cannot be called on `frame_support::pallet_prelude::StorageMap<_GeneratedPrefixForStorageProofs<T>, frame_support::Blake2_128Concat, Vec<u8>, (<T as frame_system::Config>::AccountId, <T as frame_system::Config>::BlockNumber), frame_support::pallet_prelude::ValueQuery>` due to unsatisfied trait bounds

 #[pallet::pallet]
           ^^^^^^ the trait `MaxEncodedLen` is not implemented for `Vec<u8>`

#[pallet::pallet]
          ^^^^^^ the trait `core::default::Default` is not implemented for `<T as frame_system::Config>::AccountId`

#[pallet::storage]
          ^^^^^^^ the trait `core::default::Default` is not implemented for `<T as frame_system::Config>::AccountId`

Somebody, Please help me. I beg you. What should I do next??


text:
Q: Remove Line Under ToolStrip VB.Net I have added a ToolStrip to a form which is going to be used to add menus and set the background colour to match the forms background colour but it always displays a horizontal line under the ToolStrip which I find distracting.
My workaround so far is to use the StatusStrip and add dropdown buttons but ideally I would have liked to have used the ToolStrip as I believe this is the preferred tool for adding menus
Having researched this, I think it has something to do with the Render Property and I have read where it's been mentioned about creating an override.
Can anyone show me an example on how to achieve this in VB.Net please.

A: This is simply the VB.Net version of the code provided in this previous SO question.
Obviously, the line will be there at design-time on your form, but would be gone at run-time:
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ToolStrip1.Renderer = New ToolStripRenderer
    End Sub

    Public Class ToolStripRenderer
        Inherits ToolStripProfessionalRenderer

        Public Sub New()
            MyBase.New()
        End Sub

        Protected Overrides Sub OnRenderToolStripBorder(e As ToolStripRenderEventArgs)
            If Not (TypeOf e.ToolStrip Is ToolStrip) Then
                MyBase.OnRenderToolStripBorder(e)
            End If
        End Sub

    End Class

End Class

An alternative would be to create a whole new class that inherits from ToolStrip and creates the renderer for you.  Then the line would be gone at design-time as well.  The new control would appear at the top of your ToolBox after you compile.  Unfortunately, this means you'd have to delete the old ToolStrip and drag a new one (your version) onto the form and reconfigure it:
Public Class MyToolStrip
    Inherits ToolStrip

    Public Sub New()
        MyBase.New
        Me.Renderer = New ToolStripRenderer
    End Sub

    Public Class ToolStripRenderer
        Inherits ToolStripProfessionalRenderer

        Public Sub New()
            MyBase.New()
        End Sub

        Protected Overrides Sub OnRenderToolStripBorder(e As ToolStripRenderEventArgs)
            If Not (TypeOf e.ToolStrip Is ToolStrip) Then
                MyBase.OnRenderToolStripBorder(e)
            End If
        End Sub

    End Class

End Class

A: Thank you for explaining how to do that. I went with the second option as this seemed more convenient for what I wanted and I presume I can save that Class and reuse it on further projects.
I still need to learn the Class and explore what and how they can be used.
Public Class MyToolStrip
Inherits ToolStrip

Public Sub New()
    MyBase.New
    Me.Renderer = New ToolStripRenderer
End Sub

Public Class ToolStripRenderer
    Inherits ToolStripProfessionalRenderer

    Public Sub New()
        MyBase.New()
    End Sub

    Protected Overrides Sub OnRenderToolStripBorder(e As ToolStripRenderEventArgs)
        If Not (TypeOf e.ToolStrip Is ToolStrip) Then
            MyBase.OnRenderToolStripBorder(e)
        End If
    End Sub

End Class

End Class

A: Here is a screenshot of what I am referring to

I have made the Toolstrip the same colour as the Panel I have put it into.
Underneath the Toolstrip is a white line which I find distracting and would like to be able to remove it.


text:
Q: Profiling Microsoft Dynamics SL 7 (Solomon) performance issues We are using Microsoft Dynamics SL 7 (Solomon) and are having performance issues when logging into the application and pulling up information associated with accounts.  Aside from a very generic approach to diagnosing the problem(s) such as running SQL Profiler, I was wondering if there was an SL specific approach to discovering performance bottlenecks and correcting them.  If there isn't a specific approach, I'd really appreciate a strategy that can be applied.  Thank you for your help.

A: Here's a quick one that should help.  Won't solve all of your issues.  In IE, Options, Advanced, scroll down to the Security section and disable checking certificates.


text:
Q: Python cx_oracle ignores numbers by positional bind variables cursor.execute("SELECT * FROM t WHERE c1=:2 AND c2=:1", (1, 2))

is executed as
SELECT * FROM t WHERE c1=1 AND c2=2

instead of
SELECT * FROM t WHERE c1=2 AND c2=1

as I expected. Why?
In fact all the :numbers are completely ignored
sql = ":5, :0, :0, :2, :1, :3"

is interpreted the same as
sql = ":1, :2, :3, :4, :5, :6"

Is this by intention or a bug?

A: cx_Oracle is using OCI which has this behavior. You can read about it in this white paper (bottom of page 14 and top of page 15):
http://www.oracle.com/technetwork/database/database-technologies/php/whatsnew/building-best-drivers-131920.pdf
Effectively Oracle scans from left to right and assigns position numbers to bind variables in the order they are encountered. You can use named bind variables instead to avoid this potential confusion.


text:
Q: ClassLoader only working from classpath and not url So I'm trying to load a file from a link and run it in memory. Everything is working is working fine but only when the .jar is in the classpath of the project. My code is as follows:
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarInputStream;

public class Main {

    public static URL getURL(String string) throws MalformedURLException {
        try {
            return new URL(string);
        } catch (MalformedURLException x) { return new URL("file:" + string); }
    }

    public static void main(String args[]) throws Exception {

        String jarLocation = "http://www.google.ca/file.jar";
        URL url = new URL(jarLocation);
        getURL(jarLocation);
        JarInputStream jis = new JarInputStream(url.openStream());
        String main = jis.getManifest().getMainAttributes().getValue("Main-Class");
        String classpaths[] = jis.getManifest().getMainAttributes().getValue("Class-Path").split(" ");
        for (String classpath: classpaths) {
            getURL(classpath);
        }
        URLClassLoader loader = new URLClassLoader((new URL[0]));
        Class<?> cls = loader.loadClass(main);
        Thread.currentThread().setContextClassLoader(loader);
        Method m = cls.getMethod("main", new Class[]{new String[0].getClass()});
        m.invoke(null, new Object[]{args});

    }

}

The problem is that no matter what the link is, .jar will only run if it is in the classpath of the project. How can I load the file from a link instead of from having it in the classpath?

A: This is because you are not passing your .jar URLs to the URLClassloader. In your code it takes an empty array, so I don't know how to load classes from your jar file.
Here is an example of how you can modify your code to pass the jar urls to the URLClassloader:
public class Main {

    public static URL getURL(String string) throws MalformedURLException {
        try {
            return new URL(string);
        } catch (MalformedURLException x) { return new URL("file:" + string); }
    }

    public static void main(String args[]) throws Exception {

        String jarLocation = "http://www.google.ca/file.jar";
        List<URL> urls = new ArrayList<>();
        URL url = new URL(jarLocation);
        urls.add(getURL(jarLocation));
        JarInputStream jis = new JarInputStream(url.openStream());
        String main = jis.getManifest().getMainAttributes().getValue("Main-Class");
        String classpaths[] = jis.getManifest().getMainAttributes().getValue("Class-Path").split(" ");
        for (String classpath: classpaths) {
            urls.add(getURL(classpath));
        }
        URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]));
        Class<?> cls = loader.loadClass(main);
        Thread.currentThread().setContextClassLoader(loader);
        Method m = cls.getMethod("main", new Class[]{new String[0].getClass()});
        m.invoke(null, new Object[]{args});

    }

}